Create a gist now

Instantly share code, notes, and snippets.

Embed
Center Geolocations
from math import cos, sin, atan2, sqrt
def center_geolocation(geolocations):
"""
Provide a relatively accurate center lat, lon returned as a list pair, given
a list of list pairs.
ex: in: geolocations = ((lat1,lon1), (lat2,lon2),)
out: (center_lat, center_lon)
"""
x = 0
y = 0
z = 0
for lat, lon in geolocations:
lat = float(lat)
lon = float(lon)
x += cos(lat) * cos(lon)
y += cos(lat) * sin(lon)
z += sin(lat)
x = float(x / len(geolocations))
y = float(y / len(geolocations))
z = float(z / len(geolocations))
return (atan2(y, x), atan2(z, sqrt(x * x + y * y)))
@lhejazi

This comment has been minimized.

Show comment
Hide comment
@lhejazi

lhejazi Aug 20, 2013

assuming you want your output center location to be in the form (lat, lon), shouldn't you switch the ordering of your return statements?

i.e: return (atan2(z, sqrt(x * x + y * y)), atan2(y, x))

lhejazi commented Aug 20, 2013

assuming you want your output center location to be in the form (lat, lon), shouldn't you switch the ordering of your return statements?

i.e: return (atan2(z, sqrt(x * x + y * y)), atan2(y, x))

@nextcoder

This comment has been minimized.

Show comment
Hide comment
@nextcoder

nextcoder Apr 21, 2014

A very useful function, thank you.
Just a note, most Geolocation API deals latitude and longitude in degrees.
So in most cases, you have to use radians() for the input and degrees() for the output (those two functions are in Python math library).

A very useful function, thank you.
Just a note, most Geolocation API deals latitude and longitude in degrees.
So in most cases, you have to use radians() for the input and degrees() for the output (those two functions are in Python math library).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment