var map = L.map('map').setView([37.8, -96], 4); map.locate({setView: true, maxZoom: 6}); L.tileLayer('https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png', { maxZoom: 18, attribution: 'Map data © OpenStreetMap contributors, ' + 'CC-BY-SA, ' + 'Imagery © Mapbox', id: 'examples.map-20v6611k' }).addTo(map);
// control that shows state info on hover 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 = '
US Population Density
' + (props ?
'' + props.name + '
' + props.density + ' people / mi2'
: 'Hover over a state');
};
info.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) { return { weight: 2, opacity: 1, color: 'white', dashArray: '3', fillOpacity: 0.7, fillColor: getColor(feature.properties.density) }; }
function highlightFeature(e) { var layer = e.target;
layer.setStyle({ weight: 5, color: '#666', dashArray: '', fillOpacity: 0.7 });
if (!L.Browser.ie && !L.Browser.opera) { layer.bringToFront(); }
info.update(layer.feature.properties); }
var geojson;
function resetHighlight(e) { geojson.resetStyle(e.target); info.update(); } var zoomed; zoomed=0;
function zoomToFeature(e) { if(zoomed==0){ map.fitBounds(e.target.getBounds());
zoomed=e.target; } else if(zoomed==e.target){ map.setView([37.8, -96], 4); zoomed=0; } else { map.fitBounds(e.target.getBounds()); zoomed=e.target; }
}
function onEachFeature(feature, layer) { layer.on({ mouseover: highlightFeature, mouseout: resetHighlight, click: zoomToFeature }); }
geojson = L.geoJson(statesData, { style: style, onEachFeature: onEachFeature }).addTo(map);
map.attributionControl.addAttribution('Population data © US Census Bureau');
var legend = L.control({position: 'bottomright'});
legend.onAdd = function (map) {
var div = L.DomUtil.create('div', 'info legend'), grades = [0, 10, 20, 50, 100, 200, 500, 1000], labels = [], from, to;
for (var i = 0; i < grades.length; i++) { from = grades[i]; to = grades[i + 1]; labels.push( ' ' + from + (to ? '–' + to : '+')); }
div.innerHTML = labels.join('
');
return div;
};
legend.addTo(map);