Search code examples
pythonleafletfolium

GeoJson layer not visible on python Folium map


I am trying to add a GeoJSON layer to a Folium map but the layer is not visible in the map though it is visible in the layer selector of folium. I am able to view the data in Qgis so the data is correct. I also do not get an error in Spyder.

I also inspected the HTML in the browser and there seems to be a script added with all the coordinates etc. The browser does not display an error when inspecting the file.

Anyone an idea what I am missing?

import folium

m = folium.Map(
    location=[-59.1759, -11.6016],
    tiles='OpenStreetMap',
    zoom_start=2  # Limited levels of zoom for free Mapbox tiles.
)

folium.GeoJson(
    data=(open('./projects/test/data/breda_bus_route.geojson', "r").read()),
    name='layerName',

).add_to(m)

folium.LayerControl().add_to(m)

m.save('index.html')

Solution

  • It might be case that GeoJSON layer is not visible since it's not fit within the given map view, try to dynamically fit GeoJSON layer to the map view:

    layer = folium.GeoJson(
        data=(open(path, "r").read()),
        name='geojson',
    
    ).add_to(m) # 1. keep a reference to GeoJSON layer
    
    
    m.fit_bounds(layer.get_bounds())  # 2. fit the map to GeoJSON layer 
    

    Update

    It appears it was related with GeoJSON file projection EPSG::3857, Leaflet expects EPSG:4326.

    Once GeoJSON reprojected, the layer will be rendered like this

    enter image description here