Need a routine to determine if a lat/long is inside or outside a specific area?
Here’s a Golang routine for this, that can be easily adopted to any other language.
/*
* Free to use as you see fit.
*/
package GPS
type polygon [][]float64
// Enter the lat,long coordinates (min 3)
// poly := [][]float64{ { 1,1 }, { 1,2 }, { 2,2 }, { 2,1 } ... {1,1}}
// Make sure the polygon coordinates are specified in the correct order,
// typically in a counter-clockwise direction, and that the last vertex is
// the same as the first one to close the polygon.
// in := inside(1.5, 1.5, poly) --> True
// in := inside(2.5, 1.5, poly) --> False
// Test if a GPS coordinate is inside the bounding box
func Inside(latitude float64, longitude float64, boundary polygon) bool {
inside := false
j := len(boundary) - 1
for i := 0; i < len(boundary); i++ {
xi := boundary[i][0]
yi := boundary[i][1]
xj := boundary[j][0]
yj := boundary[j][1]
// Crossing the border of the polygon?
intersect := ((yi > latitude) != (yj > latitude)) &&
(longitude < (xj-xi)*(latitude-yi)/(yj-yi)+xi)
if intersect {
inside = !inside
}
j = i
}
return inside
}
