1

When bringing GeoJSON files into Leaflet maps, I learned to addOverlay the data to the control layer toggle, defined as a global variable, following this method by @iH8:

How to add two geoJSON feature collections in to two layer groups

But, I cannot make this method work with JSON flickr photo data. In my current code, all of the photo markers appear on the map, but the toggle only controls one marker. The problem is probably in lines 25-30 of my script.js:

$.getJSON(flickrURL, function (data){
for (var i = 0; i < data.photos.photo.length; i++){
  var photo_obj = data.photos.photo[i];
  marker = new L.marker([photo_obj.latitude, photo_obj.longitude])
  .bindPopup(popupHTML(photo_obj)).addTo(map);
}
controlLayers.addOverlay(marker, 'Flickr photos - broken button only toggles one image');
});

See demo of the problem in my Plunker: http://plnkr.co/edit/LyzCNdzWrIIQYDz4dpfJ?p=preview

Suggestions?

1 Answer 1

1

You've got to put all your markers into a L.LayerGroup then add that layergroup to the layerControl. Now you're adding the actual markers to your layerControl, with the same label, which gets used as the index so it gets overwritten with every marker, thus one marker gets added to the control and only that one will toggle. In code with comments to explain:

$.getJSON(flickrURL, function (data) {
  // Create new layerGroup and add it to your map
  var layerGroup = new L.LayerGroup().addTo(map);
  // Add layerGroup to your layerControl
  controlLayers.addOverlay(layerGroup, 'Flickr photos - broken button only toggles one image');
  for (var i = 0; i < data.photos.photo.length; i++) {
    var photo_obj = data.photos.photo[i];
    var marker = new L.marker([photo_obj.latitude, photo_obj.longitude]);
    marker.bindPopup(popupHTML(photo_obj));
    // Add the marker to the layerGroup
    marker.addTo(layerGroup);
  }
});

Updated Plunker: http://plnkr.co/edit/M1UG6CPGqbqfbk1BIiNH?p=preview

LayerGroup reference: http://leafletjs.com/reference.html#layergroup

Not the answer you're looking for? Browse other questions tagged or ask your own question.