Skip to content

Instantly share code, notes, and snippets.

@czpython
Forked from amites/center_geo.py
Last active February 7, 2018 01:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save czpython/49315978cce419161047 to your computer and use it in GitHub Desktop.
Save czpython/49315978cce419161047 to your computer and use it in GitHub Desktop.
calculate center coordinate from a list of latitude, longitude pairs
# -*- coding: utf-8 -*-
import math
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)
"""
cos = math.cos
radians = math.radians
sin = math.sin
x = 0
y = 0
z = 0
for lat, lon in geolocations:
lat, lon = radians(lat), 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))
latitude = math.atan2(z, math.sqrt(x * x + y * y)) * (180/math.pi)
longitude = math.atan2(y, x) * (180/math.pi)
return latitude, longitude
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment