JSFiddle - React, Tailwind, and code Playground
by slead
HTML
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css">
<script src="https://leafletjs.com/examples/choropleth/us-states.js"></script>
<div id='map'></div>
<p>
Zoom in and out to see the polygon style change based on the zoom level
</p>
CSS
#map { width: 800px; height: 500px; }
.info { padding: 6px 8px; font: 14px/16px Arial, Helvetica, sans-serif; background: white; background: rgba(255,255,255,0.8); box-shadow: 0 0 15px rgba(0,0,0,0.2); border-radius: 5px; } .info h4 { margin: 0 0 5px; color: #777; }
.legend { text-align: left; line-height: 18px; color: #555; } .legend i { width: 18px; height: 18px; float: left; margin-right: 8px; opacity: 0.7; }
JavaScript
var map = L.map('map').setView([37.8, -96], 6);
var geojson;
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
maxZoom: 18,
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
'<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="http://mapbox.com">Mapbox</a>',
id: 'mapbox.light'
}).addTo(map);
// get color depending on population density value
function getColor(d) {
return d > 1000 ? '#800026' :
d > 500 ? '#BD0026' :
d > 200 ? '#E31A1C' :
d > 100 ? '#FC4E2A' :
d > 50 ? '#FD8D3C' :
d > 20 ? '#FEB24C' :
d > 10 ? '#FED976' :
'#FFEDA0';
}
function style(feature) {
// the weight is a function of the current map scale
var wt;
if (map.getZoom() <= 6) {
wt = 1;
} else {
wt = 20;
}
return {
weight: wt,
opacity: 1,
color: 'white',
dashArray: '3',
fillOpacity: 0.7,
fillColor: getColor(feature.properties.density)
};
}
function addStates() {
// this function adds the states layer with the style's weight determined
// by the current zoom level
geojson = L.geoJson(statesData, {
style: style
}).addTo(map);
}
// Add the states when the map first loads, using the current scale to
// set the style's width
addStates();
// whenever the zoom level changes, remove the layer and re-add it to
// force the style to update based on the current map scale
map.on("zoomend", function(){
geojson.removeFrom(map);
addStates();
});