function LeafletHelper() {
var map = L.map('map').setView([39.5, -0.5], 4);
var baseLayer = L.tileLayer(
'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
this.LayersControl = L.control.layers(baseLayers).addTo(map);
this.AddOverlay = function (layerOptions, markers) {
var zIndex = this.Overlays.length;
var layerGroup = L.layerGroup(markers).addTo(map);
this.LayersControl.addOverlay(layerGroup, layerOptions.title);
LeafletLayer: layerGroup,
Title: layerOptions.title
this.RemoveOverlays = function () {
for (var i = 0, len = this.Overlays.length; i < len; i++) {
var layer = this.Overlays[i].LeafletLayer;
this.map.removeLayer(layer);
this.LayersControl.removeLayer(layer);
this.SetZIndexByTitle = function (title, zIndex) {
var overlays = this.Overlays;
this.Overlays = overlays;
overlays.forEach(function (item, idx, arr) {
if (item.Title === title) {
overlays.sort(function (a, b) {
return a.zIndex - b.zIndex;
overlays.forEach(function (item, idx, arr) {
item.LeafletLayer.addTo(_this.map);
_this.LayersControl.addOverlay(item.LeafletLayer, item.Title);
window.helper = new LeafletHelper();
AddOverlays = function () {
}, [L.marker([36.83711, -2.464459]).bindPopup("Marker A")]);
}, [L.marker([36.83711, -3.464459]).bindPopup("Marker B")]);
}, [L.marker([36.83711, -4.464459]).bindPopup("Marker c")]);
}, [L.marker([36.83711, -5.464459]).bindPopup("Marker D")]);
var z = helper.Overlays.length;
ChangeZIndex = function () {
helper.SetZIndexByTitle(helper.Overlays[0].Title, z++);
ChangeZIndexAnim = function () {
var stuff = ['A', 'B', 'C', 'D'];
window.tt = setInterval(function () {
var title = "Marker " + stuff[idx++ % stuff.length];
helper.SetZIndexByTitle(title, z++);
if (window.tt) clearInterval(window.tt);