Search code examples
javascriptmapboxleaflet.drawself-intersection

Finding Self-Intersections in Leaflet polygons using JSTS Library


I'm using Mapbox with Leaflet Draw, and I would like to avoid self-intersecting polygons.

I can already specify to not allow intersections while creating the draw control, but it only works when I use the control to create a new polygon. However, if I try to edit an already existing polygon, it allows intersections over there.

I searched around and found the JSTS Library which does exactly what I want, and I also found this JSFiddle to use as an example, where it works based on the Google Maps API.

So I created my own JSFiddle with Mapbox based on the above two links. Here, the 'findSelfIntersects' function kicks in if it's a polygon edit, and it is not used if it is a new polygon. The idea is that, if there's an intersection, I'll show an alert to the user and cancel the edit. However, when I try to do this, I'm getting an uncaught exception: [object Object] error.

The error seems to be formed on this line of the findSelfIntersects function:

var shell = geometryFactory.createLinearRing(coordinates);

I checked out the coordinates returned by the Google Maps example, and that does seem similar to the coordinates I'm getting. But I'm not sure why I'm getting this error.


Solution

  • I just noticed that in the Google Maps example, the starting and ending points were the same in the coordinates array, whereas mine weren't. I had missed it initially. Now I've added the below code after the 'for' loop, and it works fine.

    coordinates.push(new jsts.geom.Coordinate(
        corners[0].lat, corners[0].lng));
    

    This is an updated JSFiddle in case anyone wants to use the JSTS library with Mapbox/Leaflet.