Skip to content

Instantly share code, notes, and snippets.

@mrmascott10
Created June 28, 2022 14:57
Show Gist options
  • Save mrmascott10/fcb97b9cd364c7abf72561793959b265 to your computer and use it in GitHub Desktop.
Save mrmascott10/fcb97b9cd364c7abf72561793959b265 to your computer and use it in GitHub Desktop.
Check for a lat/lng point inside a polygon or circle
<script>
// ****************************************
// Check if a point is within a circle.
// toFindX, toFindY, circleCentreX, circleCentreY, radius
// ****************************************
function pointInCircle(x, y, cx, cy, radius) {
var distancesquared = (x - cx) * (x - cx) + (y - cy) * (y - cy);
return distancesquared <= radius * radius;
}
// ****************************************
// ****************************************
// Check if a point is within a polygon
// ****************************************
// Check if a point is within a polygon.
// [1, 2], let polygon = [[0,0],[0,5],[4,3],[3,0],[0,0],];
function checkGeoFence(point, polygon) {
// Making sure start and end points are the same.
if (polygon[0] != polygon[polygon.length - 1]) {
polygon[polygon.length] = polygon[0];
}
let j = 0;
let oddNodes = false;
let x = point[1]; // Input Lat
let y = point[0]; // Input Long
let n = polygon.length;
for (let i = 0; i < n; i++) {
j++;
if (j == n) {
j = 0;
}
if (((polygon[i][0] < y) && (polygon[j][0] >= y)) || ((polygon[j][0] < y) && (polygon[i][0] >= y))) {
if (polygon[i][1] + (y - polygon[i][0]) / (polygon[j][0] - polygon[i][0]) * (polygon[j][1] - polygon[i][1]) < x) {
oddNodes = !oddNodes;
}
}
}
return oddNodes;
}
// ****************************************
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment