Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trygve-lie/5412277 to your computer and use it in GitHub Desktop.
Save trygve-lie/5412277 to your computer and use it in GitHub Desktop.
<div id="map-buttons" class="btn-group" data-toggle="buttons-checkbox">
<button id="layer1" class="btn active">Layer 1</button>
<button id="layer2" class="btn active">Layer 2</button>
<button id="layer3" class="btn active">Layer 3</button>
</div>
<script type="text/javascript">
// Setup "layer" arrays
layer1Array = new Array();
layer2Array = new Array();
layer3Array = new Array();
layers_visible = ["layer1Array", "layer2Array", "layer3Array"];
var markers = new L.MarkerClusterGroup({ disableClusteringAtZoom: 17 });
// Example of creating a marker and putting in a layer. These steps are repeated for all markers.
var marker1 = new L.Marker(new L.LatLng(LAT_HERE, LONG_HERE)).bindPopup("You clicked on the marker.");
// Put marker in appropriate layers
layer1Array.push(marker1);
layer3Array.push(marker1);
// Get marker on the map
markers.addLayer(marker1);
// Add all markers to map
map.addLayer(markers);
// Functions that make layering work
Array.prototype.unique = function() {
var arr = [];
for(var i = 0; i < this.length; i++) {
if(!arr.contains(this[i])) {
arr.push(this[i]);
}
}
return arr;
}
refreshLayers = function() {
markers_visible = [];
for(i = 0; i < layers_visible.length; i++) {
markers_array = window[layers_visible[i]]; // select the array
markers_visible = markers_visible.concat(markers_array); // add contents to markers_visible
}
markers_visible = markers_visible.unique(); // remove duplications from array caused when marker is in multiple visible layers
markers.clearLayers(); // remove all markers from map
markers.addLayers(markers_visible); // add back markers currently visible
}
$("div#map-buttons").delegate("button", "click", function() {
layer_array = $(this).attr("id") + "Array";
// update layers_visible array
if($(this).hasClass("active")) { // Note: I was using Twitter Bootstrap, which toggles the "active" class, but this delegated click is triggered first
// remove from array
layers_visible.splice(layers_visible.indexOf(layer_array), 1);
} else {
// add to array
layers_visible.push(layer_array);
}
refreshLayers();
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment