Folium – Fully Customizing LayerControl() on Web Mapping Projects

foliumleafletmappingweb-mapping

I currently have a Folium map with this LayerControl component. Would it be possible to fully customise the layer control panel? For example, I would like it to not show the map style button saying "cartodbdark_matter", and I would like it to be transparent. Can I achieve this with Folium? If not, what tool should I be using?

enter image description here

Best Answer

It's possible via combination of three informations

control : bool, default True Whether the Layer will be included in LayerControls.

  • You can set the tiles to None to not add automatically the baseLayer when using folium.Map

tiles: str, default 'OpenStreetMap' Map tileset to use. Can choose from a list of built-in tiles, pass a custom URL or pass None to create a map without tiles.

  • Now, you can add yourself the folium.TileLayer for darkmatter to display the background layer but saying you do not want to display it in the control.

To get transparent layer, we used the opacity option in folium.TileLayer (1 = fully opaque, 0 fully transparent)

A full sample available below can be used to "do the job"

import json
import folium
import requests


url = (
    "https://raw.githubusercontent.com/python-visualization/folium/master/examples/data"
)
antarctic_ice_edge = f"{url}/antarctic_ice_edge.json"
antarctic_ice_shelf_topo = f"{url}/antarctic_ice_shelf_topo.json"

folium.folium._default_css.append(('leaflet_overloaded_css', 'https://your_url/your_css_file.css'))

m = folium.Map(
    location=[-59.1759, -11.6016],
    tiles=None,
    zoom_start=2,
)

tile_layer = folium.TileLayer(
    tiles="https://{s}.basemaps.cartocdn.com/rastertiles/dark_all/{z}/{x}/{y}.png",
    attr='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors &copy; <a href="https://carto.com/attributions">CARTO</a>',
    max_zoom=19,
    name='darkmatter',
    control=False,
    opacity=0.7
)
tile_layer.add_to(m)

folium.GeoJson(antarctic_ice_edge, name="geojson").add_to(m)

folium.TopoJson( 
    json.loads(requests.get(antarctic_ice_shelf_topo).text), 
    "objects.antarctic_ice_shelf", 
    name="topojson", 
).add_to(m) 

folium.LayerControl().add_to(m)
m.save('/tmp/demo.html')