Geo-fence. Check if a point is inside a polygon.
-
We have the polygon = [[2,9],[8,6],[12,10],[15,2],[10,4],[5,1]]
-
Let's check if these points are inside or outside that polygon:
-
point = [6,5]
-
point = [7,8]
-
We will use the following algorithm in JavaScript, it is called even-odd rule.
-
The number of intersections for a ray passing from the exterior of the polygon to any point; if odd, it shows that the point lies inside the polygon. If it is even, the point lies outside the polygon. Point in polygon. Wikipedia.
- I will adapt this code:
https://www.algorithms-and-technologies.com/point_in_polygon/javascript
- JavaScript:
// var poligono = [[2,9],[8,6],[12,10],[15,2],[10,4],[5,1]];
// var punto = [6, 5];
function pointInPolygon(polygon, point) {
let odd = false;
for (let i = 0, j = polygon.length - 1; i < polygon.length; i++) {
if (((polygon[i][1] > point[1]) !== (polygon[j][1] > point[1]))
&& (point[0] < ((polygon[j][0] - polygon[i][0]) * (point[1] - polygon[i][1]) / (polygon[j][1] - polygon[i][1]) + polygon[i][0]))) {
odd = !odd;
}
j = i;
}
return odd;
};
result = pointInPolygon(poligono, punto);
AppInventor.setWebViewString(result);
-
- I have used poligono and punto as variable names.
-
This tutorial in Spanish:
App Inventor.Geofence. JavaScript. Extensión. Punto dentro o fuera de un polÃgono. Mapa. Coordenadas.