Reputation: 710
I am trying to populate a leaflet map using a multidimensional array that contains latitude, longitude, popup information and layer definition. The problem is that 2 of the markers should go to layer1 and the other two to layer2. As it its, all four markers belong to both layers. Thanks for the help.
var layer1 = new L.LayerGroup();
var layer2 = new L.LayerGroup();
var map = L.map('map', {
minZoom: 3,
maxZoom: 9,
layers: [layer1, layer2]
});
L.tileLayer('http://{s}.www.toolserver.org/tiles/bw-mapnik/{z}/{x}/{y}.png', {
attribution: '© <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>'}).addTo(map);
var overlays = {
"layer1": layer1,
"layer2": layer2
};
L.control.layers(null, overlays).addTo(map);
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(this[markersList[i][3]]);
};
Upvotes: 2
Views: 2336
Reputation: 28638
MarkerClusterGroup only supports the adding of markers, not of layergroups. If you want to accomplish this with layercontrol, you should work with two MarkerClusters, so you can toggle those. Code:
var tileLayer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
'attribution': 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors'
});
var markersList = [
[41.15, -8.61, 'popup1', 'cluster1'],
[41.15, -8.61, 'popup2', 'cluster1'],
[41.15, -8.31, 'popup3', 'cluster2'],
[41.15, -8.31, 'popup4', 'cluster2']
];
var cluster1 = new L.MarkerClusterGroup();
var cluster2 = new L.MarkerClusterGroup();
for (var i = 0; i < markersList.length; i++) {
this[markersList[i][3]].addLayer(new L.marker([markersList[i][0], markersList[i][1]]).bindPopup(markersList[i][2]));
};
var map = new L.Map('map', {
'center': [0, 0],
'zoom': 1,
'layers': [tileLayer, cluster1, cluster2]
});
var overlays = {
"Cluster 1": cluster1,
"Cluster 2": cluster2
};
L.control.layers(null, overlays).addTo(map);
Example on Plunker: http://plnkr.co/edit/p7AgXAP9OjxVCYH0qczn?p=preview
Upvotes: 3