Drawing Route Objects with the Mapbox Directions API

Drawing Route Objects with the Mapbox Directions APIUsing the Mapbox Directions REST API to draw routes on map visualizations.

Todd BirchardBlockedUnblockFollowFollowingFeb 28If you’ve been here before, you probably already know our affinity for Mapbox and the visualization tools it provides data scientists and analysts.

In the past, we’ve covered encoding location data from raw addresses, as well as an exploration of Mapbox Studio for those getting acquainted with the tool.

Today we’re going a step further: drawing directions on a map.

It sounds simple enough: we already know how to geocode addresses, so all we need to do is literally go from point A to point B.

That said, things always tend to get tricky, and if you’ve never worked with GeoJSON before, you’re in for a treat.

Load Up Some DataI’m going to assume you have a DataFrame ready containing these columns:origin_longitudeorigin_latitudedestination_longitudedestination_latitudeName/description of this routeIf you want to play along, there are plenty of free datasets out there to play with — I sourced some information from BigQuery while I was testing things out.

import osimport pandas as pdimport requestsimport jsonroutes_df = pd.

read_csv('datasources/routes.

csv').

head(10)token = os.

environ.

get('mapbox_token')So far so good- all we’ve done is load our data, and save our Mapbox token from an environment variable.

Mapbox Directions EndpointNext, we’re going to use Mapbox’s Directions API to return a route for us.

The anatomy of a GET call to receive directions looks like this:https://api.

mapbox.

com/directions/v5/mapbox/[method_of_transportation]/[origin_longitude],[origin_latitude];[destination_longitude],[destination_latitude]PARAMS:access_token=[your_mapbox_access_token]geometries=geojsonmethod_of_transportation refers to one of the three methods that Mapbox offers for creating routes: driving-traffic, driving, walking, and cycling.

Note that there is currently no way to draw route objects which follow public transit: this is perhaps Mapbox’s biggest downfall at the moment.

Nevertheless, if this is something you need, data can be imported from Google maps to be used with Mapbox.

access_token can be either your public token (visible upon login at mapbox.

com) or a generated secret token.

geometries accepts the method by which to draw the object.

This can be GeoJSON, polyline, or polyline6.

Let’s stick with GeoJSON.

Constructing API RequestsLet’s construct a request per row in our DataFrame.

By using Pandas’ apply, we fire a function per row to do just that:import osimport pandas as pdimport requestsimport jsonroutes_df = pd.

read_csv('datasources/routes.

csv').

head(10)token = os.

environ.

get('mapbox_token')def create_route_json(row): """Get route JSON.

""" base_url = 'https://api.

mapbox.

com/directions/v5/mapbox/driving/' url = base_url + str(row['home_longitude']) + ',' + str(row['home_latitude']) + ';' + str(row['destination_longitude']) + ',' + str(row['destination_latitude']) params = { 'geometries': 'geojson', 'access_token': token } req = requests.

get(url, params=params) route_json = req.

json()['routes'][0] # Now what?.

. More details

Leave a Reply