Reputation: 1725
I load some lat / lon info, then use it to build a polyline. I then want to add a marker at each of the polyline vertices that will show when the polyline is clicked. The vertices should disappear if a different (or the same) polyline is clicked.
The code below creates the polyline and the vertex markers. But the vertex markers do not ever disappear.
I've tried to do this several ways with the same result. I've tried storing the vertex markers in an array and adding them directly to the map, then map.removeLayer'ing them. That doesn't work either. Nor does it work if I use an L.featureGroup instead of a layerGroup.
Clearly I've missed the point somewhere as to how markers can be removed. Could someone point me at the error in my methodology?
// trackMarkersVisible is a global L.layerGroup
// success is a callback from an ajax that fetches trackData, an array f lat/lon pairs
success: function (trackData) {
// build an array of latLng's
points = buildTrackPointSet(trackData, marker.deviceID);
var newTrack = L.polyline(
points, {
color: colors[colorIndex],
weight: 6,
clickable: true
}
);
$(newTrack).on("click", function () {
trackMarkersVisible.clearLayers();
$.each(points, function(idx, val) {
var tm = new L.Marker(val);
trackMarkersVisible.addLayer(tm);
});
map.addLayer(trackMarkersVisible);
});
}
Upvotes: 0
Views: 1225
Reputation: 28638
Without a JSFiddle or Plunker it's hard to say because i'm not sure what behaviour your getting but using the clearLayers()
method of L.LayerGroup
should remove all layers from that group. I would check in the onclick handler if the group already has layers: group.getLayers().length === 0
If the group is empty, add the markers, if the group has layers use clearLayers
. Example in code:
polyline.on('click', function (e) {
if (group.getLayers().length === 0) {
e.target._latlngs.forEach(function (latlng) {
group.addLayer(L.marker(latlng));
});
} else {
group.clearLayers();
}
});
This works for me, see the example on Plunker: http://plnkr.co/edit/7IPHrO?p=preview
FYI: an instance of L.Polyline is always clickable by default so you can leave out the clickable: true
Upvotes: 1