How do I plot a line on a map from a geojson file?

  1. The first issue is that you are redefining the layout mapbox object after you updated some of its fields. To display a map you should do the following:
fig = go.Figure(data=[go.Scattermapbox(lat=[0], lon=[0])])

fig.update_layout(
    margin={"r":0,"t":0,"l":0,"b":0},
    mapbox=go.layout.Mapbox(
        style="stamen-terrain", 
        zoom=10, 
        center_lat = 40.5,
        center_lon = -105.08,
        layers=[{
            'sourcetype': 'geojson',
            'source': fcRailroad,
            'type': 'line',
        }]
    )
)
fig.show()
  1. The second issue is with the geojson file, these are not standard longitude and latitude so nothing will be shown on the map.

  2. Thirdly I would recommend to convert your geojson to Scattermapbox rather than using layers, especially if you want to have some hover actions with the line:

fig = go.Figure(
    data=[
        go.Scattermapbox(
            lat=np.array(feature["geometry"]["coordinates"])[:, 1],
            lon=np.array(feature["geometry"]["coordinates"])[:, 0],
            mode="lines",
            line=dict(width=8, color="#F00")
        )
        for feature in fcRailroad["features"]
    ]
)

fig.update_layout(
    margin={"r":0,"t":0,"l":0,"b":0},
    mapbox=go.layout.Mapbox(
        style="stamen-terrain", 
        zoom=10, 
        center_lat = 40.5,
        center_lon = -105.08,
    )
)
fig.show()

And here is a geojson with proper latitude and longitude:

fcRailroad = {
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "properties": {},
            "geometry": {
                "type": "LineString",
                "coordinates": [
                    [
                        -105.0913953781128,
                        40.49348616373978
                    ],
                    [
                        -105.0906443595885,
                        40.49508532104079
                    ],
                    [
                        -105.0863313674927,
                        40.502411585011934
                    ]
                ]
            }
        }
    ]
}
3 Likes