From bfc06bfbd2de72d79e59cfac0f1a908e80b9adc5 Mon Sep 17 00:00:00 2001 From: gazebo Date: Tue, 22 Jan 2019 14:50:04 +0800 Subject: [PATCH] - IsPointInPolygon added --- utils/utils_geo.go | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 utils/utils_geo.go diff --git a/utils/utils_geo.go b/utils/utils_geo.go new file mode 100644 index 00000000..ce6e174a --- /dev/null +++ b/utils/utils_geo.go @@ -0,0 +1,33 @@ +package utils + +// http://ju.outofmemory.cn/entry/130555 +func IsPointInPolygon(x float64, y float64, points [][2]float64) bool { + count := 0 + x1, y1 := points[0][0], points[0][1] + x1Part := (y1 > y) || ((x1-x > 0) && (y1 == y)) + var a = [2]float64{x1, y1} + p := append(points, a) + for i := range p { + if i == 0 { + continue + } + point := p[i] + x2, y2 := point[0], point[1] + x2Part := (y2 > y) || ((x2 > x) && (y2 == y)) + if x2Part == x1Part { + x1, y1 = x2, y2 + continue + } + mul := (x1-x)*(y2-y) - (x2-x)*(y1-y) + if mul > 0 { + count++ + } else { + if mul < 0 { + count-- + } + } + x1, y1 = x2, y2 + x1Part = x2Part + } + return count == 2 || count == -2 +}