Skip to content

Instantly share code, notes, and snippets.

@amites
Last active October 15, 2021 23:14
Show Gist options
  • Star 25 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save amites/3718961 to your computer and use it in GitHub Desktop.
Save amites/3718961 to your computer and use it in GitHub Desktop.
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))
@AdamEyreWalker
Copy link

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
Copy link
Author

amites commented Jul 17, 2019

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

@Firzen7
Copy link

Firzen7 commented Mar 2, 2020

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
Copy link

AdamEyreWalker commented Mar 3, 2020 via email

@Firzen7
Copy link

Firzen7 commented Mar 3, 2020

@AdamEyreWalker I am not sure, because I haven't programmed anything :D Steps I did:

  1. Select contents of center_geo.py
  2. Go to https://repl.it/languages/python3
  3. Paste source code in the editor
  4. Click run
  5. Input center_geolocation([(56.012, -3.61), (56.016, -3.62)]) in the console
  6. Press ENTER

As I said, I didn't change anything. :-)

@AdamEyreWalker
Copy link

AdamEyreWalker commented Mar 3, 2020 via email

@JamesGDiaz
Copy link

@AdamEyreWalker @Firzen7 You have to convert to radians first, this funcion assumes input is in radians:
lat_rad = latPi/180
lon_rad = lon
Pi/180

just convert it back to degrees at the end

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