Skip to content

Commit 8e6537e

Browse files
committed
Fix incorrect Intersection algorithm
1 parent 7b9719a commit 8e6537e

File tree

2 files changed

+33
-5
lines changed

2 files changed

+33
-5
lines changed

geofence.go

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import (
44
"github.com/kellydunn/golang-geo"
55
)
66

7-
// Geofence represents a point on the Earth with an accuracy radius.
7+
// Geofence represents a point on the Earth with an accuracy radius in meters.
88
type Geofence struct {
99
Latitude, Longitude, Radius float64
1010
}
@@ -29,17 +29,19 @@ func (mi *Geofence) Intersection(tu *Geofence) (i SetIntersection) {
2929
tuPoint := geo.NewPoint(tu.Latitude, tu.Longitude)
3030
distance := miPoint.GreatCircleDistance(tuPoint) * 1000
3131

32-
ourRadius := mi.Radius + tu.Radius
33-
if ourRadius > distance {
32+
radiusSum := mi.Radius + tu.Radius
33+
radiusDiff := mi.Radius - tu.Radius
34+
35+
if distance-radiusSum > 0 {
3436
i = IsDisjoint
3537
return
3638
}
3739

38-
if mi.Radius-tu.Radius > distance {
40+
if -distance+radiusDiff >= 0 {
3941
i |= IsSuperset
4042
}
4143

42-
if tu.Radius-mi.Radius > distance {
44+
if -distance-radiusDiff >= 0 {
4345
i |= IsSubset
4446
}
4547

geofence_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package main
2+
3+
import "testing"
4+
5+
func TestIntersection(t *testing.T) {
6+
tests := []struct {
7+
Mi Geofence
8+
Tu Geofence
9+
Result SetIntersection
10+
}{
11+
{Geofence{36.1699, -115.1398, 1000.0}, Geofence{36.1699, -115.1398, 10.0}, IsSuperset},
12+
{Geofence{36.1699, -115.1398, 10.0}, Geofence{36.1699, -115.1398, 1000.0}, IsSubset},
13+
{Geofence{36.1699, -115.1398, 10.0}, Geofence{37.7749, -122.4194, 1000.0}, IsDisjoint},
14+
{Geofence{36.1699, -115.1398, 10.0}, Geofence{36.1699, -115.1398, 10.0}, IsSubset | IsSuperset},
15+
{Geofence{36.1699, -115.13983, 100.0}, Geofence{36.1699, -115.1398, 100.0}, 0},
16+
}
17+
18+
for _, test := range tests {
19+
got := test.Mi.Intersection(&test.Tu)
20+
want := test.Result
21+
if want != got {
22+
t.Errorf("With %s and %s: expected intersection code %b, got %b",
23+
BlacklistRule{Geofence: &test.Mi}, BlacklistRule{Geofence: &test.Tu}, want, got)
24+
}
25+
}
26+
}

0 commit comments

Comments
 (0)