Search code examples
pythonhtmlbackground-colorcolormapfolium

How to add a background color of a colormap in a folium map


I am working with folium maps created based on json files. I added a colormap using branca.colormap and I want to add a background color since the resulting colormap can have some colors with the map behind it and that will cause a visualization problem.

Can I add this colormap to a frame or just add a background color?


Solution

  • This is a rather hacky solution, but it works:

    Open the html-file generated by folium, by the function map_instance.save('map.html').

    Look for the line generating the leaflet-control, by searching for .append("svg")

    Insert this code snippet after it, making sure to get the variable name correct (i.e. copy the random generated id from the variable in your code)

    color_map_<random_generated_id>.svg.append("rect")
        .attr("width", "100%")
        .attr("height", "100%")
        .attr("fill", "white")
        .attr("opacity", "0.8");
    

    You can also position the legend by changing the leaflet-control position attribute in the color_map_<random_generated_id>.legend variable. In my example I use L.control({position: 'bottomleft'});

    Image example