1

I'm working on a map that displays the trips I've taken. I've created many markers and lines to designate locations and the paths between them. I've created trips using the required markers/paths and added them as layerGroups to a layerControl. The problem is several locations and drive paths have been used in multiple trips. I'd like to have multiple layers render but the problem is unchecking one layer will turn off markers/paths that are common with other still active layers.

For example:

Trip 1 = Burlington, VT marker -> BurlingtonToAlbany path -> Albany, NY marker ->AlbanyToDC path -> Washington DC marker

Trip 2 = Boston, MA marker -> BostonToAlbany path -> Albany, NY marker -> AlbanyToSanDiego path

Both trip 1 and trip 2 display properly. However, when I turn off trip 1 all related markers/paths are removed. This includes the shared Albany, NY marker and Trip 2 is no longer rendered correctly. How can I best resolve this?

1

Sounds like you may need to clone the Leaflet objects before adding them to the layerGroups, otherwise they are passed by reference to the layerControl, and this turns off all the Albany, NY markers on the map, regardless of what trip they are part of.

var trip1 = L.layerGroup();
var albany = L.marker([lat, lng]);
// showing one way to clone object in javascript, this is itself a major topic
JSON.parse(JSON.stringify(albany)).addTo(trip1);
  • Thank you. I thought I may have to clone the object but it seemed redundant to create so many copies. Your method got me most of the way there! Leaflet's .addTo was not working on the clone using JSON because it was returning a type 'Object' and it only accepted 'o.Class.Extend.e'. I was able to work around it with jQuery.extend, like this: – cmartin616 Jul 9 '15 at 13:38
  • function addToFeatureGroup(featureGroup, group){ _.each(featureGroup, function(feature){ jQuery.extend(true, {}, feature).addTo(group); console.log(feature); }); – cmartin616 Jul 9 '15 at 13:43
  • interesting solution using jQuery and underscore.js. glad you were able to work it out – toms Jul 9 '15 at 16:24
  • @cmartin616 Isn't that will add Albany, NY marker twice to the map? – Waseem Abu Senjer Mar 14 '16 at 21:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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