JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test Map</title>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<script src="https://unpkg.com/leaflet.vectorgrid@latest/dist/Leaflet.VectorGrid.js"></script>
</head>
<body>
<div id="map"></div>
</body>
</html>
CSS
body {
margin: 0;
}
#map {
height: 100vh;
width: 100vw;
}
JavaScript
const map = L.map('map')
.setView([46.801111, 8.226667], 7);
const basemap = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
});
basemap.addTo(map);
const url = 'https://basemaps.arcgis.com/arcgis/rest/services/World_Basemap_v2/VectorTileServer/tile/{z}/{y}/{x}.pbf';
const tileOptions = {
rendererFactory: L.canvas.tile,
vectorTileLayerStyles: {
Road: {
weight: 2,
color: '#ff0000',
fill: false,
}
},
// see https://www.arcgis.com/home/item.html?id=30d6b8271e1849cd9c3042060001f425
attribution: `Esri, TomTom, Garmin, FAO,
NOAA, USGS, and the GIS User Community`,
};
const layer = L.vectorGrid.protobuf(url, tileOptions);
function isLayerHidden(layerName) {
return layerName != 'Road';
}
// workaround, we watch the internal _dataLayerNames object for changes
// and if there are changes, we set any layer style that is unwanted
// to an empty array
layer._dataLayerNames = new Proxy(layer._dataLayerNames, {
set: (target, key, value) => {
if (isLayerHidden(key)) {
layer.options.vectorTileLayerStyles[key] = [];
}
target[key] = value;
return true;
},
});
map.addLayer(layer);