console
var map = L.map('map').setView([37.8, -96], 4);
var mapboxAccessToken = 'pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw';
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=' + mapboxAccessToken, {
id: 'mapbox.light'
}).addTo(map);
var info = L.control();
info.onAdd = function(map) {
this._div = L.DomUtil.create('div', 'info');
this.update();
return this._div;
}
info.update = function(props) {
this._div.innerHTML = '<h4>US Population Density</h4>' + (props ? '<b>' + props.name + '</b><br>' + props.density + 'people / mi<sup>2</sup>': 'Hover over a state');
}
info.addTo(map);
var getColor = function(d) {
return d > 1000 ? '#800026': d > 500 ? '#BD0026': d > 200 ? '#E31A1C': d > 100 ? '#FC4E2A': d > 50 ? '#FD8D3C': d > 20 ? '#FEB24C': d > 10 ? '#FED976': '#FFEDA0';
}
var style = function(feature) {
return {
weight: 2,
opacity: 1,
color: 'white',
dashArray: '3',
fillOpacity: 0.7,
fillColor: getColor(feature.properties.density)
}
}
var geojson;
var highlightFeature = function(e) {
var layer = e.target;
layer.setStyle({
weight: 5,
color: '#666',
dashArray: '',
fillOpacity: 0.7
});
info.update(layer.feature.properties);
}
var resetHighlight = function(e) {
geojson.resetStyle(e.target);
info.update();
}
var zoomToFeature = function(e) {
map.fitBounds(e.target.getBounds());
}
var onEachFeature = function(feature, layer) {
layer.on({
mouseover: highlightFeature,
mouseout: resetHighlight,
click: zoomToFeature
})
}
geojson = L.geoJSON(statesData, {
style: style,
onEachFeature: onEachFeature
}).addTo(map);
var legend = L.control({
position: 'bottomright'
});
legend.onAdd = function() {
this._div = L.DomUtil.create('div', 'info legend');
var grades = [0, 10, 20, 50, 100, 200, 500, 1000],
labels = [],
from,
to;
for (let i = 0; i < grades.length; i++) {
from = grades[i];
to = grades[i + 1];
labels.push('<i style="background:' + getColor(from + 1) + '"></i>' + from + (to ? '–' + to: '+'));
}
this._div.innerHTML = labels.join('<br>');
return this._div;
}
legend.addTo(map);
<div id="map">
</div>
#map {
height: 500px;
width: 800px;
}
.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;
}