0

I want to build my custom layers control with JQuery.

My JS is like:

$(document).ready(function() {
 var map = L.map('map', {
 center: [39.73, -104.99],
 zoom: 10
 });
 var littleton = L.marker([39.61, -105.02]).bindPopup('This is Littleton, CO.'),
 denver = L.marker([39.74, -104.99]).bindPopup('This is Denver, CO.'),
 aurora = L.marker([39.73, -104.8]).bindPopup('This is Aurora, CO.'),
 golden = L.marker([39.77, -105.23]).bindPopup('This is Golden, CO.');
 var cities = L.layerGroup([littleton, denver, aurora, golden]);
 cities.addTo(map);
 // use jQuery to listen for checkbox change event
 $('div#layercontrol input[type="checkbox"]').on('change', function() { 
 var checkbox = $(this);
 var layer = checkbox.data("layer");
 // toggle the layer
 if (checkbox.prop('checked')) {
 map.addLayer(layer);
 } else {
 map.removeLayer(layer);
 }
 })
});

My html is like:

<body>
 <div id="layercontrol">
 <label><input type="checkbox" data-layer="cities">Cities</label>
 </div>
 <div id="map" style="height: 100%; width: 100%"></div>
</body>

Here the map.addLayer and map.removeLayer failed due to Error: The provided object is not a Layer..

How can the layergroup be referenced by the "data-layer" attribute associated with the checkbox for it?

NettaB
1,9761 gold badge11 silver badges19 bronze badges
asked Feb 16, 2018 at 1:11

1 Answer 1

3

You can use window[object name] in javascript to get the layer object as they were initialized before:

HTML:

<body>
 <div id="layercontrol">
 <label><input type="checkbox" data-city="denver">denver </label>
 <label><input type="checkbox" data-city="aurora"> aurora </label>
 <label><input type="checkbox" data-city="golden">golden</label>
 </div>
 <div id="map" style="height: 100%; width: 100%"></div>
</body>

Javascript:

........
 // use jQuery to listen for checkbox change event
 $('div#layercontrol input[type="checkbox"]').on('change', function() { 
 var checkbox = $(this);
 // window used to get the object by name
 var layer = window[checkbox.attr("data-city")];
 // toggle the layer
 if (checkbox.prop('checked')) {
 map.addLayer(layer);
 } else {
 map.removeLayer(layer);
 }
 })
.......
answered Feb 16, 2018 at 3:05

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.