Leaflet GeoJSON Events – How to Make Polygon Unclickable After First Click

eventsgeojsonleaflet

I have added a GeoJSON file consisting of multiple polygons to a leaflet map. Now after clicking on any of those polygons I don't want Leaflet to accept any subsequent click events for this specific polygon anymore. This is what I have tried to no avail:

leafletGeoJsonLayer.on('click', function (e) {
  ...color clicked polygon red or green...
  e.layer.options.interactive = false; //don't accept further click events for this polygon
}

Any ideas how to achieve that?

enter image description here

Best Answer

One possible solution would be to use some custom polygon/layer property, like for example wasClicked (name can be any, as long is does not conflict with standard Leaflet layer properties), to mark the fact that polygon/layer was already clicked. If wasClicked is true, further processing is skipped.

Code could then look something like this:

leafletGeoJsonLayer.on('click', function (e) {
  var layer = e.target;
  if (layer.wasClicked) return;

  layer.wasClicked = true;
  ...
}

Other possible solution would be to cancel layer click event processing with the .off method. In this case code could look something like this:

function processGeoJsonClick(e) {
  var layer = e.target;
  layer.off('click', processGeoJsonClick);
  ...
}

leafletGeoJsonLayer.on('click', processGeoJsonClick);