totalnoob totalnoob - 1 month ago 18
Javascript Question

Leaflet Layergroups in loop

Hi i have this code that from txt file create markers on image map. And i want to add layer control to hide or show different markers with L.control.layers now with this code it hide all markers. Is it possible to split markers by coordinates into groups ? Thanks

var stringData = $.ajax({
url: "a.txt",
async: false
}).responseText;
//Split values of string data
var stringArray = stringData.split("\n");
var arrayLength = stringArray.length ;

var layerGroup = L.layerGroup().addTo(map);

for(var i = 0; i < arrayLength; i++) {
var x = $.trim(stringArray[i].split(",")[0]);
var y = $.trim(stringArray[i].split(",")[1]);
var img2 = $.trim(stringArray[i].split(",")[2]);

var circle = L.circle([x,y], {
color: 'red',
fillColor: '#f03',
fillOpacity: 0.3,
radius: 2,
}).addTo(map);
circle.url = img2
circle.on('click', function(){
window.location = (this.url);
});
layerGroup.addLayer(circle);
}
var overlayMaps = {
"Normal": layerGroup,
"Elite": layerGroup,
"Ultimate": layerGroup
};
L.control.layers(null, overlayMaps).addTo(map);


a.txt

-146.4375, 183.0625, img/img1.png
-104.5, 182.75, img/img2.png,

Answer

Yes of course. Just create 3 layerGroups. In your loop, you have to add a condition to add your circles to either of them.

var layerGroup1 = L.layerGroup().addTo(map);
var layerGroup2 = L.layerGroup().addTo(map);
var layerGroup3 = L.layerGroup().addTo(map);


for(var i = 0; i < arrayLength; i++) {
    var x = $.trim(stringArray[i].split(",")[0]);
    var y = $.trim(stringArray[i].split(",")[1]);
    var img2 = $.trim(stringArray[i].split(",")[2]);

    var circle = L.circle([x,y], {
        color: 'red',
        fillColor: '#f03',
        fillOpacity: 0.3,
        radius: 2,
    });
    circle.url = img2
    circle.on('click', function(){
    window.location = (this.url);
    });


    switch(img2) {
       case "img/img1.png":
           circle.addTo(layerGroup1);
           break;
       case "img/img2.png":
           circle.addTo(layerGroup2);
           break;
       case "img/img3.png":
           circle.addTo(layerGroup3);
           break;
       default:
           break;
    }
  }

var overlayMaps = {
    "Normal": layerGroup1,
    "Elite": layerGroup2,
    "Ultimate": layerGroup3
};

Example: http://plnkr.co/edit/f8azOmaz1ITLZiKgfHWt?p=preview

Comments