Leaflet – How to Prevent User from Drawing a Feature with Leaflet.draw

javascriptleafletleaflet-draw

In my application using Leaflet.draw the user can set point markers on a map.

I would like to allow the setting only in a certain area.

The function isMarkerInsidePolygon(marker, polygon) returns true, if the marker is inside the polygone, false if outside.

For this purpose, I think I have to check after draw:drawstart, but before draw:created, if isMarkerInsidePolygon(marker, polygon) returns true or false.

If it returns false, I want to prevent setting the marker, but still keep the drawing mode active. Is there a posibility to prevent the setting of a marker in leaflet.draw?

There is a similar question asked by Ben, but no exactly the same case:

Leaflet draw: prevent drawing through a custom overlay

Best Answer

Since there seems to be no official hook to implement this, one has to resort to hack.

L.Draw.Marker class has internal _onClick method which is called when user clicks with mouse to create marker. This method can be replace with our own hacked method by modifying L.Draw.Marker class. We can check here if clicked point is within polygon and allow creation of marker or return immediately without creating it.

L.Draw.Marker.include({
  _onClick: function () {
    // our hack
    if (! isMarkerInsidePolygon(this._marker, polygon)) return;
    // original code
    this._fireCreatedEvent();
    this.disable();
    if (this.options.repeatMode) {
      this.enable();
    }
  }
});