Black and white folium map outside certain boundaries

32 views Asked by At

I have a .geojson file with the boundaries of a certain country I'm creating a folium map like this:

m = folium.Map(location=[51.026, 4.476], zoom_start=9)
folium.GeoJson('BELGIUM_-_Municipalities.geojson', name='Municipalities', style_function=style_function).add_to(m)

How can I put the background of the map outside the boundaries in gray scale, mainting the base map coloured inside the boundaries? Basically in the map below I'd like to put everything outside the borders of Belgium in gray scale

enter image description here

.

1

There are 1 answers

0
Timeless On

One possible option to simulate a bit what you're looking for is to use the Cartodb Position as a primary basemap, then add a WmsTileLayer (like the topo layer provided by NGI service) :

m = folium.Map(
    location=[51.026, 4.476] zoom_start=9, tiles="cartodb positron",
)

folium.WmsTileLayer(
    url="https://cartoweb.wms.ngi.be/service",
    fmt="image/png", layers="topo", transparent=True,
).add_to(m)

enter image description here

Alternatively, you can use a localized base layer, i.e a tile from openstreetmap-carto-be that excludes areas outside Belgium:

m = folium.Map(
    location=[51.026, 4.476], zoom_start=9,
    tiles="https://tile.openstreetmap.be/osmbe/{z}/{x}/{y}.png",
    attr='&copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, Tiles courtesy of <a href="https://geo6.be/">GEO-6</a>',
)

enter image description here

NB : Both approaches are indepenent of the extent/bounds of your data (polygons, points, ..).

Used input : BELGIUM_-_Municipalities.geojson

import json
import folium

def style_function(x):
    return {
        "fillColor": "cyan",
        "fillOpacity": 0.3,
        "color": "black",
        "opacity": 0.7,
        "weight": 1,
    }

with open("BELGIUM_-_Municipalities.geojson", "r") as f:
    data = json.load(f)

folium.GeoJson(
    data, name="Municipalities", style_function=style_function,
).add_to(m)