2
votes

I am trying to add markers from an array into a leaflet map. I am trying to get the popup info, layer and coordinates from the array. I must be missing something obvious because I can't pull the layer info.

markersArray[i][1] returns the value "layer1" but it does not work in the .addTo method.

EDIT: I HAVE CHANGED THE CODE TO SOLVE A PROBLEM WITH A MARKER APPEARING OUTSIDE THE CLUSTER:

My code is as follows:

var markersList = [];
var markersList = [
[41.15,-8.61,'popup1','layer1'],
[41.15,-8.61,'popup2','layer1'],
[41.15,-8.31,'popup3','layer2'],
[41.15,-8.31,'popup4','layer2']
];

var markers = new L.MarkerClusterGroup();

for (var i = 0; i < markersList.length; i++) {
markers.addLayer(new L.marker([markersList[i][0], markersList[i][1]]).bindPopup(markersList[i][2]));
markers.addTo(layer1); // working
markers.addTo(markersList[i][3]); // not working
map.addLayer(markers);
};

Thanks for helping.

2

2 Answers

2
votes

That's because markersArray[i][1] is has the type of string. If you want to use that to reference the layer1 object you could use this[markersArray[i][1]];

edit because of asker edit:

You're still making the same mistake. The addTo method expects an instance of a layer as parameter not a string with the name of the variable that contains your layerinstance. markersList[i][3] contains a string with the name of the variable of your layerinstance not an instance of that layer. If you want to grab the instance of that layer by string you should use: this[markersList[i][3]]. That would result in the following code:

markers.addTo(this[markersList[i][3]]);

Here 'this' represent your current scope, markersList[i][3] the string with your variable name so it would result in 'this["layer1"]' which is a reference to your layerinstance. I'm assuming you've declared variable layer1 in that scope and it contains the layerinstance:

var layer1 = new L.LayerGroup();

But i can't deduct that from your current code because you've deleted where you create the instances of the layergroups.

1
votes

addTo is used to add the marker to the map. Passing it markersArray wont work as you have found.

I'm going to guess that you plan to have multiple layers, each holding some features that you add to the map. You probably need to use a dictionary of layers, and map each layer name to a corresponding leaflet layer object.

var layerLookup {};
layerLookup["layer1"] = new L.LayerGroup().addTo(map);
layerLookup["layer2"] = new L.LayerGroup().addTo(map);

... // other code

for (var i = 0; i < markersArray.length; i++) {
    marker = new L.marker([markersArray[i][2],markersArray[i][3]])
    .bindPopup(markersArray[i][0]).addTo(layerLookup[markersArray[i][1]]);
};