Search
Search Menu

routingpy – basic example

Estimated reading time:

In [ ]:
import folium
from pprint import pprint

m = folium.Map(location=[47.376558, 8.540497], tiles='cartodbpositron', zoom_start=13)

coordinates = [[8.512516, 47.380742], [8.557835, 47.359467]]

m

1. Directions

In [ ]:
from routingpy import ORS

# Create your own API key at https://openrouteservice.org/sign-up
api = ORS(api_key=key_ors)

route = api.directions(locations=coordinates,
                      profile='driving-car')

# Access the geometry object as [[lon, lat], ...] list from the geometry 
# Folium (like leaflet) expects coordinates in [[lat, lon], ...] format though. Yep, annoying...
folium.PolyLine(locations=[list(reversed(coord)) for coord in route.geometry]).add_to(m)

# Other attributes are duration and distance. The full response is in 'raw' attribute
print("Duration in seconds: {}".format(route.duration))
print("Distance in meters: {}".format(route.distance))
m

2. Isochrones

In [ ]:
from routingpy import MapboxValhalla

# Create your own API key at https://account.mapbox.com/access-tokens/
api = MapboxValhalla(api_key=key_mapbox)

isochrones = api.isochrones(locations=coordinates[0],
                      profile='auto',
                      intervals=[100,200])

for isochrone in isochrones:
    folium.Polygon(locations=[list(reversed(coord)) for coord in isochrone.geometry],
                  fill='00ff00',
                  opacity=0.5).add_to(m)
    
m

3. Matrix

In [ ]:
from routingpy import HereMaps

# Create your own API key at https://developer.here.com/?create=Freemium-Basic&keepState=true&step=account
api = HereMaps(app_id=here_id, app_code=here_code)

matrix = api.matrix(locations=coordinates,
                   profile='car')

pprint(matrix.durations)
pprint(matrix.raw)

Compare multiple routing API provider with routingpy in this Jupyter notebook: Mapbox, GraphHopper, HERE and OpenRouteService.