Skip to content

Instantly share code, notes, and snippets.

@highfestiva
Last active December 9, 2022 14:45
Show Gist options
  • Save highfestiva/8089aca7f4ccb3cede0901ba9cc8ec37 to your computer and use it in GitHub Desktop.
Save highfestiva/8089aca7f4ccb3cede0901ba9cc8ec37 to your computer and use it in GitHub Desktop.
Calculate meters between two geo-coords
from math import *
class Coord:
def __init__(self, x, y=None):
if y is None:
self.lat = x[1]
self.lng = x[0]
else:
self.lat = x
self.lng = y
def diff(self, coord):
return Coord(self.lat - coord.lat, self.lng - coord.lng)
def length(self):
return sqrt(self.lat*self.lat + self.lng*self.lng)
def __str__(self):
return f'https://www.openstreetmap.org/#map=17/{self.lat}/{self.lng}'
def haversine(c1, c2):
R = 6378.137 # Earth's radius in km
lat_diff = c2.lat * pi / 180 - c1.lat * pi / 180
lng_diff = c2.lng * pi / 180 - c1.lng * pi / 180
a = \
(sin(lat_diff/2) ** 2) + \
(cos(c1.lat * pi / 180) * cos(c2.lat * pi / 180)) * \
(sin(lng_diff/2) ** 2)
c = 2 * atan2(sqrt(a), sqrt(1-a))
d = R * c
return d * 1000 # meters
print(haversine(Coord(19.71751,-96.40226), Coord(19.71921,-96.40092)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment