Skip to content

Instantly share code, notes, and snippets.

@Hiyorimi
Forked from amites/center_geo.py
Last active January 27, 2019 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hiyorimi/e00698c27af3bcb65e13a34a3769ed27 to your computer and use it in GitHub Desktop.
Save Hiyorimi/e00698c27af3bcb65e13a34a3769ed27 to your computer and use it in GitHub Desktop.
Center Geolocations
from math import cos, sin, asin, atan2, sqrt, radians, degrees
def _hsin(theta):
return pow(sin(theta/2), 2)
def distance(lat1, lon1, lat2, lon2):
"""
Calulates distance between two points set as 4 coordinates.
"""
# convert to radians
la1 = radians(lat1)
lo1 = radians(lon1)
la2 = radians(lat2)
lo2 = radians(lon2)
# must cast radius as float to multiply later
r = 6378100.0 # Earth radius in meters.
h = _hsin(la2-la1) + cos(la1)*cos(la2)*_hsin(lo2-lo1)
return 2 * r * asin(sqrt(h))
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(radians(lat))
lon = float(radians(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 (degrees(atan2(z, sqrt(x * x + y * y))), degrees(atan2(y, x)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment