I have found several solutions for crazy polygon detecting algorithms, however, my problem is a bit simpler. I have a line created by an array of indexed points. Each click on map creates a new point and appends it to the end of the array, and creates a new line from the previous end to the new one.

I would like to detect when you create a point in a way that the line folds on itself and creates a polygon. I currently create a polygon when you click the first point again. Then all the points inside get selected.

Detect this and select all points inside

Here the 4th point was created and the line closed creating a triangle. Is there a simple solution to detect this?

Edit: Using leaflet library

  • What software are you using? Make sure to include that in your question. – J.W. Powell Jul 14 '17 at 15:24
  • Question was tagged, but I added it to the Q itself, thanks. – Poody Jul 17 '17 at 5:11
  • I've never used it, so I'm not sure whether it's entirely suitable here - but it sounds like the type of problem that Turf.js was designed to solve. See turfjs.org – Stephen Lead Jul 17 '17 at 6:49

I used a modified version of an algorithm I found online. It takes line A-B, C-D and returns their intersection, if there is any that lies on both input lines. So I iterated over my point array and then if any of them created a line that intersected the last line, a polygon was created, as previously when clicked the first point.

Said algorithm

function getLineIntersection(ax, ay, bx, by, cx, cy, dx, dy) {
    var d, a, b, n1, n2, result = {
        x: null,
        y: null,
    d = ((dy - cy) * (bx - ax)) - ((dx - cx) * (by - ay));
    if (d != 0) {
        a = ay - cy;
        b = ax - cx;
        n1 = ((dx - cx) * a) - ((dy - cy) * b);
        n2 = ((bx - ax) * a) - ((by - ay) * b);
        a = n1 / d;
        b = n2 / d;
        if (a > 0 && a < 1 && b > 0 && b < 1) {
            result.x = ax + (a * (bx - ax));
            result.y = ay + (a * (by - ay));

    return result;
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.