Professional Documents
Culture Documents
If youve been struggling with the problem of determining whether a point lies
inside or outside a polygon, perhaps in google maps, read on. This post is
specific to Android and Node.js but the algorithm can easily be implemented in
any other language/platform as the algorithm itself is a piece of cake once
understood.
To further elaborate the problem, take a look at the diagram below:
earths curvature and the fact that earth is a skewed sphere. Great! But the
precision thats lost during patching a super-rectangle over our innocent
irregular polygon would leave you in tears. Diagram below shows the superrectangle in gray.
Now you do see the problem, right? Point b and c will be considered inside
the polygon while they are not.
It shows that rays from point b and c are having 0 or even number of
intersections, no matter in which direction you draw a line starting from it,
concluding that they lie outside the polygon.
My Implementations of RayCast
Android
https://github.com/Infernus666/RayCast-android
In the above github repository, RaycastHelper.java contains the
implementation of RayCast Algorithm. You have to provide LatLngs or points
as vertices of the polygon in correct clockwise or anticlockwise sequence. The
solution also assumes that the LatLngs or points you provide form a closed
polygon. It exposes following 2 static methods:
by GitHub
Nodejs
https://www.npmjs.com/package/raycast
npm install raycast
This npm package provides the same two methods described in the Android
section above. The package also provides two helper
classes LatLng and Point to deal with the corresponding methods.
1. isLatLngInside(latlngs, latlng)
2. isPointInside(points, point)
var polygonVertices = [];
by GitHub
intersections count: 1
Sequence: EXIT
conclusion: Point A is inside the polygon
Point B
intersections count: 0
Sequence:
conclusion: Point B is out the polygon
Point C
intersections count: 2
Sequence: ENTER EXIT
conclusion: Point C is outside the polygon
Point D
intersections count: 3
Sequence: EXIT ENTER EXIT
conclusion: Point D is inside the polygon
It works!
If you find this algorithm useful and interesting, it goes very well with another
computational geometry concept called Voronoi. You might want to take a
look at myblogpost on Voronoi and this npm package.
Source http://vinsol.com/blog/2016/08/04/ray-casting-algorithm/