Thursday, January 6, 2011

Generating random locations around a location

Handy.

def generateLocation(startlat, startlon, maxdist):

# converting them radians
startlat *= pi / 180
startlon *= pi / 180
rand1 = random.random()
rand2 = random.random()

maxdist = maxdist / earthradius
dist = acos(rand1*(cos(maxdist) - 1) + 1)
brg = 2*pi*rand2

lat = asin(sin(startlat)*cos(dist) + cos(startlat)*sin(dist)*cos(brg))
lon = startlon + atan2(sin(brg)*sin(dist)*cos(startlat), cos(dist)-sin(startlat)*sin(lat))

if lon < -pi:
lon = lon + 2 * pi

if lon > pi:
lon = lon - 2 * pi

lat *= 180 / pi
lon *= 180 / pi

return [lat, lon]

No comments:

Post a Comment