Skip to content

Instantly share code, notes, and snippets.

@kols
Last active December 14, 2015 18:49
Show Gist options
  • Save kols/5132059 to your computer and use it in GitHub Desktop.
Save kols/5132059 to your computer and use it in GitHub Desktop.
Distance calculation
import math
EARTH_RADIUS = 6378137. # in meters
def calculate_distance(lat1, lng1, lat2, lng2):
if not all((lat1, lng1, lat2, lng2)):
return
a = math.radians(lat1) - math.radians(lat2)
b = math.radians(lng1) - math.radians(lng2)
distance = 2 * math.asin(
math.sqrt(
math.pow(math.sin(a / 2), 2) + math.cos(math.radians(lat1)) *
math.cos(math.radians(lat2)) * math.pow(math.sin(b / 2), 2))
) * EARTH_RADIUS
return int(round(distance))
def pick_nearest(place_list, lat, lng):
if not (lat and lng):
return place_list[0]
index = 0
distance = float('inf')
for i, p in enumerate(place_list):
if p.lat and p.lng:
cur_distance = calculate_distance(
p.lat, p.lng, lat, lng)
if cur_distance < distance:
distance = cur_distance
index = i
return place_list[index]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment