Black Lives Matter. Please consider donating to Black Girls Code today.

Scattermapbox doesn't load data from local source

Hello,

I started working with Plotly just recently and am trying to figure out how to create interactive cartographic simulations. I followed the Mapbox Chloropleth Tutorial (with some modifications) and my problem is that I can’t load the geojson data into my map from my hard drive (the code is able to open and process it, it just doesn’t show up on the map). The interesting thing is that I can load the data from the GitHub-url in the tutorial (it also works with my geojson-file, but only if I open it from GitHub).

The code looks like this:
import plotly
import plotly.graph_objs as go

datapath='florida-red-data.json'
mapbox_access_token = 'my access token'

layout = go.Layout(
    autosize=True,
    hovermode='closest',
    mapbox=dict(
        layers=[
            dict(
                sourcetype='geojson',
                source=datapath,
                type='fill',
                name='red'
            )
        ],
        accesstoken=mapbox_access_token,
        bearing=0,
        center=dict(
            lat=51.509865,
            lon=-0.118092
        ),
        pitch=00,
        zoom=10
    ),
)
data=[]

data.append(go.Scattermapbox(
    name='test',
    mode='markers'
))

fig=dict(data=data, layout=layout)
plotly.offline.plot(fig, filename='testmap.html')

As I don’t have a lot of Plotly experience yet the answer may be really trivial but I have no real idea what I could change. I tried inserting the path directly into the dict, using relative and absolute paths and trying to open the page in Chrome and Firefox (Windows 10).

Thanks for the help in advance!

Hi Balcse,

I usually load up the geo-json in memory before serving it, works for me and should be faster than serving the json from the HD every time.

import json
 
with open(datapath, 'r') as f:
    geo_data = json.load(geo_data)

After that you can point to the variable you create to serve the layers.

Another thing that may be happening is that your json got some bad character that got sanitised in github, try to copy the content in a json linter to make sure it can be parsed correctly.

2 Likes

Thanks a lot for the tip! It works now, I didn’t had to sanitise my file but load it in memory.