Skip to content

Instantly share code, notes, and snippets.

@code-shoily
Created August 11, 2024 05:09
Show Gist options
  • Save code-shoily/5bbcf672c21f2602c30c0a61743186cd to your computer and use it in GitHub Desktop.
Save code-shoily/5bbcf672c21f2602c30c0a61743186cd to your computer and use it in GitHub Desktop.
Create a random spatial point within specific distance (in meter) of a given point.
from random import random
from math import cos, pi, radians, degrees, sin, sqrt
METER_PER_DEGREE = 111_139
def generate_location_near(*, lat: float, lng: float, distance: float) -> tuple[float, float]:
lat_radian, lng_radian = radians(lat), radians(lng)
w, t = (distance / METER_PER_DEGREE) * sqrt(random()), 2 * pi * random()
pos_lat_radian, pos_lng_radian = (
w * sin(t) + lat_radian,
(w * cos(t)) / cos(lat_radian) + lng_radian
)
return (
degrees(pos_lat_radian),
degrees(pos_lng_radian)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment