Determine if a point is inside the leaf polygon.

Suppose I draw a polygon using a booklet, as in the following demo: http://leaflet.imtqy.com/Leaflet.draw/

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

+12
source share
3 answers

Use the ray conversion algorithm to check if a point (marker) is inside the polyangular box:

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 for example jsfiddle .

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


See also 2014 similar answer, fooobar.com/questions/629916 / ...

+31
source

Here is a modified (with @Sumit hints) version of @gusper's 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; }; 
+13
source

I found that none of the answers above work for counting markers in non-adjacent polygons. Here is an example of a polyangular box in which the above functions return 0 markers inside:

Non-contiguous Polygon

For those who need to do this, the Leaflet.PointInPolygon package worked for me: https://github.com/hayeswise/Leaflet.PointInPolygon

This is a bit slow, but seems accurate.

0
source

All Articles