Last active
September 26, 2019 16:14
-
-
Save ChaseIngebritson/b9775c966cd4e614758220a81c9b8fc5 to your computer and use it in GitHub Desktop.
Check to see if a coordinate is within a given fence.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fence = [ | |
[44.969886109093, -93.21685776103517], | |
[44.98627907084557, -93.28243240703127], | |
[44.9667284078666, -93.28208908427736], | |
[44.93611398841498, -93.20192322124025], | |
[44.93605322928645, -93.18498107787336], | |
[44.956282465359436, -93.18510040629884], | |
]; | |
// Outside of the fence | |
const point1 = [45.126606, -93.2065048]; | |
console.log(isPointInFence(point1, fence)); // false | |
// On a fence point | |
const point2 = [44.9667284078666, -93.28208908427736]; | |
console.log(isPointInFence(point2, fence)); // false | |
/* | |
Regarding Point 2: | |
If the test point is on the border of the polygon, this algorithm will deliver unpredictable results; i.e. the result may be | |
“inside” or “outside” depending on arbitrary factors such as how the polygon is oriented with respect to the coordinate system. | |
(That is not generally a problem, since the edge of the polygon is infinitely thin anyway, and points that fall right on the | |
edge can go either way without hurting the look of the polygon.) | |
*/ | |
// In the fence | |
const point3 = [44.9698, -93.2441]; | |
console.log(isPointInFence(point3, fence)); // true | |
// Formula explination: http://alienryderflex.com/polygon/ | |
// Adapted from: https://stackoverflow.com/a/42460157/5026438 | |
function isPointInFence(point, fence) { | |
// [y, x] = [latitude, longitude] | |
const [y, x] = point; | |
let isInFence = false; | |
for (let i = 0; i < (fence.length - 1); i++) { | |
const [p1_y, p1_x] = fence[i]; | |
const [p2_y, p2_x] = fence[i + 1]; | |
if ((p1_y < y && p2_y >= y) || (p2_y < y && p1_y >= y)) { // this edge is crossing the horizontal ray of testpoint | |
if ((p1_x + (y - p1_y) / (p2_y - p1_y) * (p2_x - p1_x)) < x) { // checking special cases (holes, self-crossings, self-overlapping, horizontal edges, etc.) | |
isInFence = !isInFence; | |
} | |
} | |
} | |
return isInFence; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment