Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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(z, sqrt(x * x + y * y)), atan2(y, x))
@lhejazi

This comment has been minimized.

Copy link

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.

Copy link

commented 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).

@AdamEyreWalker

This comment has been minimized.

Copy link

commented Jul 17, 2019

lhejazi is correct; the function returns the results the wrong way round as long, lat - this is easily checked by putting a single set of lat, long coordinates through the function

@amites

This comment has been minimized.

Copy link
Owner Author

commented Jul 17, 2019

been a few years since I looked at this, thank you for the reminder I've updated the gist

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.