-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlookups.go
74 lines (59 loc) · 1.58 KB
/
lookups.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package lookups
import (
"github.com/golang/geo/s2"
)
const (
// Default level of s2 cells.
DefaultS2CellLevel = 15
)
//nolint:gochecknoglobals
var (
// Default value for geo indexer.
DefaultGeoIndexer = NewS2Index(DefaultS2CellLevel)
)
type (
// Lookuper is an interface for lookup services.
Lookuper interface {
Lookup(coordinates []Coordinate) []CoordinateProps
}
// lookups is an engine of lookups.
lookups struct {
geoIndex GeoIndex
geoPolygons map[string][]PolyProps
}
)
// New returns a new lookups engine instance.
func New(polyProps []PolyProps, geoIndex GeoIndex) Lookuper {
geoPolygons := make(map[string][]PolyProps)
for _, polyProp := range polyProps {
ids := geoIndex.Cover(polyProp.Polygon)
for _, id := range ids {
geoPolygons[id] = append(geoPolygons[id], polyProp)
}
}
return &lookups{
geoIndex: geoIndex,
geoPolygons: geoPolygons,
}
}
// Lookup returns list of properties of given coordinates.
func (l lookups) Lookup(coordinates []Coordinate) []CoordinateProps {
result := make([]CoordinateProps, 0, len(coordinates))
for _, coordinate := range coordinates {
cell := l.geoIndex.Find(coordinate)
candidates := l.geoPolygons[cell]
props := make([]Props, 0, len(candidates))
for _, candidate := range candidates {
ll := s2.LatLngFromDegrees(coordinate.Latitude, coordinate.Longitude)
point := s2.PointFromLatLng(ll)
if candidate.Polygon.ContainsPoint(point) {
props = append(props, candidate.Props)
}
}
result = append(result, CoordinateProps{
Props: props,
Coordinate: coordinate,
})
}
return result
}