How do I remove a Leaflet GeoJSON layer when a user clicks it?

2,395 views
Skip to first unread message

Tim Wisniewski

unread,
Sep 9, 2015, 11:03:41 AM9/9/15
to Leaflet

I've put together a test case that demonstrates what I'm attempting to do and the error that it causes: http://codepen.io/anon/pen/RWPyej?editors=001


To demonstrate, open the javascript console then click on one of the polygons. It will remove the geojson layer entirely (desired) but when you move your mouse outside of where the polygon you clicked used to be, you'll get a console error: Uncaught TypeError: Cannot read property 'mouseEventToContainerPoint' of null


layer = L.geoJson(geojson, {
    onEachFeature: function(feature, layer) {
      layer.on({
        click: onClick
      });
    }
  }).addTo(map)

function onClick(e) {
  map.removeLayer(layer);
}


When a user clicks on a polygon, I'd like to replace the geojson layer with other geojson data. I can either do this by removing the layer from the map or clearing the layer and adding new data; it seems either route produces the same error.


I assume this has to do with the listeners for each polygon remaining after I've removed the layer, so I've tried to use clearAllEventListeners() to no avail.


How should I remove/replace the GeoJSON layer without getting this error?

scott rivas

unread,
Sep 10, 2015, 12:11:27 PM9/10/15
to Leaflet
I am having a similar error with Polygon objects that are removed from the map upon click. I have had no luck resolving this so far.

Tim Wisniewski

unread,
Sep 10, 2015, 6:26:39 PM9/10/15
to Leaflet
I was directed to post a github issue from gitter: https://github.com/Leaflet/Leaflet/issues/3829
Reply all
Reply to author
Forward
0 new messages