daHappy
daHappy

Reputation: 43

Leaflet - Add Layer on LayerAdd event

so i want to add a Layer if a other Layer is added .... i did make a small Example

var mymap = L.map('mymap').setView([51.505, -0.09], 13);

var baseLayer = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 18,
}).addTo(mymap);

var layer1 = L.marker([51.505,-0.10]);
var layer2 = L.marker([51.505,-0.09]);
var layer3 = L.marker([51.505,-0.8]);



var basemaps = {
    "OSM": baseLayer
};

var overlays = {
    "Layer1": layer1,
  "Layer2": layer2,
  "Layer3": layer3
}

L.control.layers(basemaps,overlays,{collapsed:false}).addTo(mymap);

layer1.on("add",function(){
    layer2.addTo(mymap);
});

and on

JSFiddle (Updated Version)

Like you (may) can see the second Marker is shortly added but instantly removed after the add-Event is finished ... Iam not sure how i can prefent it from doing that or more specific how i realy can add the second marker (since in the Layer Control the checkbox isnt even activated in that short moment) ....

Upvotes: 3

Views: 17569

Answers (1)

Mujtaba Kably
Mujtaba Kably

Reputation: 755

you can either use map.on('layeradd') and or try the layeradd event on your layer1 object.

leaflet's documentation link: http://leafletjs.com/reference-1.0.3.html#layerevent

EDIT... add the following code to js-fiddle code.

layer1.on('add',(e)=>{
  layer2.addTo(mymap);
});

layer1.addTo(mymap);

if that doesn't remove the addTo line from above and paste the following

setTimeout(()=>{
  layer1.addTo(mymap);
},500);

EDIT 2 :

var controlObj = L.control.layers(basemaps,overlays,{collapsed:false}).addTo(mymap);

layer1.on("add",function(){
 console.log(controlObj._form[2].click())
});

this code works... but its not how it should be dont... will have to figureout a better way to do this, but this will work temporarily.

Upvotes: 2

Related Questions