Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a point reside inside a leaflet polygon

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.

like image 626
Majdi Taleb Avatar asked Aug 03 '15 14:08

Majdi Taleb


People also ask

How do you know if a point is inside a polygon leaflet?

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.

How do you know if the point is inside the polygon?

One simple way of finding whether the point is inside or outside a simple polygon is to test how many times a ray, starting from the point and going in any fixed direction, intersects the edges of the polygon. If the point is on the outside of the polygon the ray will intersect its edge an even number of times.

How do you check if a point is inside a polygon in Python?

How to check if a point is inside a polygon in Python. To perform a Point in Polygon (PIP) query in Python, we can resort to the Shapely library's functions . within(), to check if a point is within a polygon, or . contains(), to check if a polygon contains a point.

How do you check if a given point lies inside or outside a polygon Javascript?

Pick a point outside the polygon check and see if a line from that point to your point intersects an odd number of lines that define the perimeter of the polygon. poly[i]. y should be poly[i][1] at the end of line 3. Also that function checks if the point is inside the polygon not if the point belongs to the polygon.


1 Answers

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

like image 148
gusjap Avatar answered Oct 21 '22 13:10

gusjap