Determine if a point reside inside a leaflet polygon

前端 未结 3 1544
故里飘歌
故里飘歌 2020-12-05 05:10

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 ins

相关标签:
3条回答
  • 2020-12-05 06:00

    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

    0 讨论(0)
  • 2020-12-05 06:03

    Here is the modified(with @Sumit hints) version of @gusper answer that worked for me:(i had donuts)

    function isMarkerInsidePolygon(marker, poly) {
        var inside = false;
        var x = marker.getLatLng().lat, y = marker.getLatLng().lng;
        for (var ii=0;ii<poly.getLatLngs().length;ii++){
            var polyPoints = poly.getLatLngs()[ii];
            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;
    };
    
    0 讨论(0)
  • 2020-12-05 06:08

    I found that none of the above answers worked for counting markers within non-contiguous polygons. Here's an example polygon where the above functions returned 0 markers inside:

    For anyone who needs to do that, the Leaflet.PointInPolygon package worked for me: https://github.com/hayeswise/Leaflet.PointInPolygon

    It's a bit slow, but it seems to be accurate.

    0 讨论(0)
提交回复
热议问题