Determine if a point reside inside a leaflet polygon

Majdi Taleb picture Majdi Taleb · Aug 3, 2015 · Viewed 19.8k times · Source

Suppose I Draw a polygan using leaflet like in the follow demo: http://leaflet.github.io/Leaflet.draw/

My question is how I can determine if a given point reside inside the polygon or not.

Answer

gusper picture gusper · Aug 4, 2015

Use the Ray Casting algorithm for checking if a point (marker) lies inside of a polygon:

function isMarkerInsidePolygon(marker, poly) {
    var polyPoints = poly.getLatLngs();       
    var x = marker.getLatLng().lat, y = marker.getLatLng().lng;

    var inside = false;
    for (var i = 0, j = polyPoints.length - 1; i < polyPoints.length; j = i++) {
        var xi = polyPoints[i].lat, yi = polyPoints[i].lng;
        var xj = polyPoints[j].lat, yj = polyPoints[j].lng;

        var intersect = ((yi > y) != (yj > y))
            && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
        if (intersect) inside = !inside;
    }

    return inside;
};

See jsfiddle for example.

Original source for the code: https://github.com/substack/point-in-polygon/blob/master/index.js


See also 2014's similar answer, https://stackoverflow.com/a/41138512/287948