The below Jupyter notebook shows you how to get directions using openrouteservice and its Python wrapper, openrouteservice-py.
Here we import our libraries. OpenRouteService-py is imported as ors
, as that is easier to type and is a common abbreviation used throughout their documentation.
import openrouteservice as ors
import folium
Next, we connect to the server by creating an instance of Client. If you are using a self-hosted instance, uncomment the bottom line and replace the base_url
with wherever the api is hosted. If you are using the hosted solution, simply enter your API key.
client = ors.Client(key='YOUR_KEY_HERE')
# use self-hosted
# client = ors.Client(base_url='localhost:8080/ors')
Here we use the client to get directions between the White House and the Pentagon. The red line shows all the points where an instruction is given, while the blue line shows all points along the route allowing for a smooth route appearance.
import operator
from functools import reduce
m = folium.Map(location=list(reversed([-77.0362619, 38.897475])), tiles="cartodbpositron", zoom_start=13)
# white house to the pentagon
coords = [[-77.0362619, 38.897475], [-77.0584556, 38.871861]]
route = client.directions(coordinates=coords,
profile='foot-walking',
format='geojson')
waypoints = list(dict.fromkeys(reduce(operator.concat, list(map(lambda step: step['way_points'], route['features'][0]['properties']['segments'][0]['steps'])))))
folium.PolyLine(locations=[list(reversed(coord)) for coord in route['features'][0]['geometry']['coordinates']], color="blue").add_to(m)
folium.PolyLine(locations=[list(reversed(route['features'][0]['geometry']['coordinates'][index])) for index in waypoints], color="red").add_to(m)
m
One thought on “Getting Directions in Python with OpenRouteService-py”
Comments are closed.