-
-
Save amites/3718961 to your computer and use it in GitHub Desktop.
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)) |
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).
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
been a few years since I looked at this, thank you for the reminder I've updated the gist
I don't think this works well. For example:
center_geolocation([(56.012, -3.61), (56.016, -3.62)])
returns: (-0.5346732451559053, 2.6681793850777766)
That makes no sense to me. I would expect something like (56.014, -3.615), or is my thinking wrong?
@AdamEyreWalker I am not sure, because I haven't programmed anything :D Steps I did:
- Select contents of center_geo.py
- Go to https://repl.it/languages/python3
- Paste source code in the editor
- Click run
- Input center_geolocation([(56.012, -3.61), (56.016, -3.62)]) in the console
- Press ENTER
As I said, I didn't change anything. :-)
@AdamEyreWalker @Firzen7 You have to convert to radians first, this funcion assumes input is in radians:
lat_rad = latPi/180
lon_rad = lonPi/180
just convert it back to degrees at the end
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))