Leaflet selector control for marker clusters
HTML
<script src="http://cdn.leafletjs.com/leaflet-0.7.5/leaflet.js"></script>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.5/leaflet.css">
<script src="http://leaflet.github.io/Leaflet.markercluster/dist/leaflet.markercluster-src.js"></script>
<link rel="stylesheet" href="http://leaflet.github.io/Leaflet.markercluster/dist/MarkerCluster.css">
<link rel="stylesheet" href="http://leaflet.github.io/Leaflet.markercluster/dist/MarkerCluster.Default.css">
<script src="http://dl.dropboxusercontent.com/u/23920803/infographics/2016/2016.01.14_the_growing_of_Minsk/GeoJSON/villagesGeoJson.js"></script>
<div id="map" style="width:600px; height:400px"></div>
JavaScript
var map = L.map('map', {
center: [53.905, 27.562],
zoom: 11
});
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
var markerClusterLayer = L.markerClusterGroup();
var markerLayer = L.geoJson(firstVillages, {
onEachFeature: function(feature, layer) {
var popup = '';
if (feature.properties.name) {
popup += '<b>' + feature.properties.name + '</b>';
}
if (feature.properties.size) {
popup += '<br/>' + 'Количество дворов: ' + feature.properties.size;
}
layer.bindPopup(popup);
}
});
var selector = L.control({
position: 'topleft'
});
selector.onAdd = function(map) {
var div = L.DomUtil.create('div', 'mySelector');
div.innerHTML = '<select id = "marker_select"><option value = "init">(деревни)</option></select>';
return div;
};
selector.addTo(map);
markerLayer.eachLayer(function(layer) {
var optionElement = document.createElement("option");
optionElement.innerHTML = layer.feature.properties.name;
optionElement.value = layer._leaflet_id;
L.DomUtil.get("marker_select").appendChild(optionElement);
});
var marker_select = L.DomUtil.get("marker_select");
L.DomEvent.addListener(marker_select, 'click', function(e) {
L.DomEvent.stopPropagation(e);
});
L.DomEvent.addListener(marker_select, 'change', changeHandler);
function changeHandler(e) {
if (e.target.value == "init") {
map.closePopup();
} else {
var selected = markerLayer.getLayer(e.target.value);
markerClusterLayer.zoomToShowLayer(selected, function() {
selected.openPopup();
})
}
}
markerClusterLayer.addLayer(markerLayer);
map.addLayer(markerClusterLayer);