Skip to content

Instantly share code, notes, and snippets.

@hobwekiva
Last active March 18, 2021 01:47
Show Gist options
  • Save hobwekiva/9668213d446465f03c0d94ca61c579b1 to your computer and use it in GitHub Desktop.
Save hobwekiva/9668213d446465f03c0d94ca61c579b1 to your computer and use it in GitHub Desktop.
import geocoder
import geopy.distance
import requests
import time
import json
def now():
from datetime import timezone
import datetime
dt = datetime.datetime.now(timezone.utc)
utc_time = dt.replace(tzinfo=timezone.utc)
utc_timestamp = utc_time.timestamp()
return utc_timestamp
last_request = 0
def rate_limiter():
global last_request
now_time = now()
if last_request + 1.0 > now_time:
time.sleep(last_request + 1.0 - now_time)
last_request = now()
else:
last_request = now_time
def driving_distance(p1, p2):
url = 'http://router.project-osrm.org/route/v1/driving/'
# LONGITUDE FIRST
o1 = str(p1[0]) + ',' + str(p1[1])
o2 = str(p2[0]) + ',' + str(p2[1])
x = o1 + ';' + o2
response = requests.get(url+x)
data = json.loads(response.content)
if response.status_code == 200:
return data['routes'][0]['distance']*0.001 #in km
else:
return None
def distance(p1, p2):
if isinstance(p1, str):
rate_limiter()
g = geocoder.osm(p1)
print('%s resolved to %s (long=%s lat=%s)' % (p1, g, g.x, g.y))
p1 = (g.x, g.y)
if isinstance(p2, str):
rate_limiter()
g = geocoder.osm(p2)
print('%s resolved to %s (long=%s lat=%s)' % (p2, g, g.x, g.y))
p2 = (g.x, g.y)
geodesic_km = geopy.distance.geodesic(reversed(p1), reversed(p2)).km
rate_limiter()
driving_km = driving_distance(p1, p2)
return geodesic_km, driving_km
print(distance('Milwaukee', 'Toronto'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment