Working with maps in python using Mapbox and Plotly

There are plenty of mapping services available dominated by Google Map, Here map, OpenStreetMaps, and a few lesser-known as such Mapbox. Of course, they all vary in features, services, and kind of use cases. For mapping applications that require precision and finer control, Google Map is the choice, but they are not convenient and free for all purposes. Some use-cases of Google MAP API are free but you probably need to enter credit card information for billing purposes to prevent any misuse. Recently, my research group started gathering GPS data from consumer cars and I was looking to overlay the GPS data on maps for further downstream analysis of GPS data. In the quest for a suitable python API, I stumbled upon plotly that uses various types of maps, with or without the need for an API key. plotly provides support Mapbox which is convenient to use.
Mapbox provides two sets of API token that can be used for querying mapping service: public and private. plotly uses a public API key to query mapping service from Mapbox. However, plotly doesn’t necessarily need an API token from Mapbox as it has a support mapping without API toke as well, but that won’t let you use Mapbox mapping tiles. I found out that API-token free mapping calls in plotly has poor map rendering. However, API token generation in Mapbox is so easy that there is no reason why we should not use it. So let’s get started
API Token generation
To generate a Mapbox API token, go to mapbox.com, and signup for an account. Once you log in, you can generate a token at https://account.mapbox.com/. Press +create a token button and it will generate two tokens: public and secret. Note down the public token that you will need for use in plotly.

We will also need a map style that can be created at https://studio.mapbox.com/. I have already created a map style whose access URL is mapbox://styles/strym/ckhe4yk7d04hi19kcu9878xyv
Plotly Express and Scatter Mapbox
Plotly since 4.12.0 can be used in the localhost. In addition to that, we will need kaleido that can be used for capturing static images of interactive maps.
pip install plotly==4.12.0
pip install kaleidoPlotly provides a high-level wrapper called plotly express that can be used for overlaying GPS data on a map.
Let’s begin with imports:
import plotly.express as px
import plotly.io as pio
import plotly.offline as pyo
# Set notebook mode to work in offline
pyo.init_notebook_mode()The full data file can be found on my GitHub repository https://github.com/rahulbhadani/medium.com/blob/master/data/gps.csv
Load the dataset and read using a pandas data frame:
import pandas as pd
gps_data = "../data/gps.csv"
gps_df = pd.read_csv(gps_data)
gps_dfAn example of data looks like:






