-
Notifications
You must be signed in to change notification settings - Fork 2
/
tools.go
310 lines (244 loc) · 7.13 KB
/
tools.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
package insideout
import (
"bytes"
"encoding/binary"
"fmt"
"strings"
"github.com/golang/geo/s2"
spb "github.com/golang/protobuf/ptypes/struct"
"github.com/pkg/errors"
"github.com/twpayne/go-geom"
"github.com/twpayne/go-geom/encoding/geojson"
)
const (
insidePrefix byte = 'I'
outsidePrefix byte = 'O'
featurePrefix byte = 'F'
cellPrefix byte = 'C'
infoKey byte = 'i'
mapKey byte = 'm'
// reserved T & t for tiles
TilesURLPrefix byte = 't'
TilesPrefix byte = 'T'
InsideTreeStrategy = "insidetree"
DBStrategy = "db"
ShapeIndexStrategy = "shapeindex"
PostgisIndexStrategy = "postgis"
)
// GeoJSONCoverCellUnion generates an s2 cover normalized
func GeoJSONCoverCellUnion(f *geojson.Feature, coverer *s2.RegionCoverer, interior bool) ([]s2.CellUnion, error) {
if f.Geometry == nil {
return nil, errors.New("invalid geometry")
}
var cu []s2.CellUnion
switch rg := f.Geometry.(type) {
case *geom.Polygon:
// only supports outer ring
cup, err := coverPolygon(rg.FlatCoords(), coverer, interior)
if err != nil {
return nil, fmt.Errorf("can't cover polygon: %w", err)
}
cu = append(cu, cup)
case *geom.MultiPolygon:
for i := 0; i < rg.NumPolygons(); i++ {
p := rg.Polygon(i)
cup, err := coverPolygon(p.FlatCoords(), coverer, interior)
if err != nil {
return nil, fmt.Errorf("can't cover multi polygon %d: %w", i, err)
}
cu = append(cu, cup)
}
default:
return nil, errors.New("unsupported data type")
}
return cu, nil
}
// GeoJSONEncodeLoops encodes all MultiPolygons and Polygons as loops []byte
func GeoJSONEncodeLoops(f *geojson.Feature) ([][]byte, error) {
if f.Geometry == nil {
return nil, errors.New("invalid geometry")
}
var b [][]byte
switch rg := f.Geometry.(type) {
case *geom.Polygon:
// only supports outer ring
lb := new(bytes.Buffer)
l := LoopFromCoordinates(rg.FlatCoords())
err := l.Encode(lb)
if err != nil {
return nil, fmt.Errorf("can't encode polygon: %w", err)
}
b = append(b, lb.Bytes())
case *geom.MultiPolygon:
for i := 0; i < rg.NumPolygons(); i++ {
lb := new(bytes.Buffer)
p := rg.Polygon(i)
l := LoopFromCoordinates(p.FlatCoords())
err := l.Encode(lb)
if err != nil {
return nil, fmt.Errorf("can't encode polygon: %w", err)
}
b = append(b, lb.Bytes())
}
default:
return nil, errors.New("unsupported data type")
}
return b, nil
}
// coverPolygon returns an s2 cover from a list of lng, lat forming a closed polygon
func coverPolygon(c []float64, coverer *s2.RegionCoverer, interior bool) (s2.CellUnion, error) {
if len(c) < 6 {
return nil, errors.New("invalid polygons not enough coordinates for a closed polygon")
}
if len(c)%2 != 0 {
return nil, errors.New("invalid polygons odd coordinates number")
}
l := LoopFromCoordinates(c)
if l.IsEmpty() || l.IsFull() || l.ContainsOrigin() {
return nil, errors.New("invalid polygons")
}
if interior {
return coverer.InteriorCovering(l), nil
}
return coverer.Covering(l), nil
}
// LoopFromCoordinates creates a LoopFence from a list of lng lat
func LoopFromCoordinates(c []float64) *s2.Loop {
if len(c)%2 != 0 || len(c) < 2*3 {
return nil
}
points := make([]s2.Point, len(c)/2)
for i := 0; i < len(c); i += 2 {
points[i/2] = s2.PointFromLatLng(s2.LatLngFromDegrees(c[i+1], c[i]))
}
if points[0] == points[len(points)-1] {
// remove last item if same as 1st
points = append(points[:len(points)-1], points[len(points)-1+1:]...)
}
loop := s2.LoopFromPoints(points)
return loop
}
// CoordinatesFromLoops returns []float64 as lng lat adding 1st as last suitable for GeoJSON
func CoordinatesFromLoops(l *s2.Loop) []float64 {
points := l.Vertices()
coords := make([]float64, len(points)*2+2)
for i := 0; i < len(points); i++ {
ll := s2.LatLngFromPoint(points[i])
coords[i*2] = ll.Lng.Degrees()
coords[i*2+1] = ll.Lat.Degrees()
}
coords[len(points)*2] = coords[0]
coords[len(points)*2+1] = coords[1]
return coords
}
func InsideKey(c s2.CellID) []byte {
k := make([]byte, 1+8)
k[0] = insidePrefix
binary.BigEndian.PutUint64(k[1:], uint64(c))
return k
}
// InsideRangeKeys returns the min and max range keys for c
func InsideRangeKeys(c s2.CellID) ([]byte, []byte) {
mink := make([]byte, 1+8)
mink[0] = insidePrefix
binary.BigEndian.PutUint64(mink[1:], uint64(c.RangeMin()))
maxk := make([]byte, 1+8)
maxk[0] = insidePrefix
binary.BigEndian.PutUint64(maxk[1:], uint64(c.RangeMax()))
return mink, maxk
}
func OutsideKey(c s2.CellID) []byte {
k := make([]byte, 1+8)
k[0] = outsidePrefix
binary.BigEndian.PutUint64(k[1:], uint64(c))
return k
}
// OutsideRangeKeys returns the min and max range keys for c
func OutsideRangeKeys(c s2.CellID) ([]byte, []byte) {
mink := make([]byte, 1+8)
mink[0] = outsidePrefix
binary.BigEndian.PutUint64(mink[1:], uint64(c.RangeMin()))
maxk := make([]byte, 1+8)
maxk[0] = outsidePrefix
binary.BigEndian.PutUint64(maxk[1:], uint64(c.RangeMax()))
return mink, maxk
}
// FeatureKey returns the key for the id
func FeatureKey(id uint32) []byte {
k := make([]byte, 1+4)
k[0] = featurePrefix
binary.BigEndian.PutUint32(k[1:], id)
return k
}
// CellKey returns the key for the cell id
func CellKey(id uint32) []byte {
k := make([]byte, 1+4)
k[0] = cellPrefix
binary.BigEndian.PutUint32(k[1:], id)
return k
}
// InfoKey returns the key for the info entry
func InfoKey() []byte {
return []byte{infoKey}
}
// MapKey returns the key for the map entry
func MapKey() []byte {
return []byte{mapKey}
}
// CellPrefix returns the key prefix for cells entry
func CellPrefix() byte {
return cellPrefix
}
// FeaturePrefix returns the key prefix for features entry
func FeaturePrefix() byte {
return featurePrefix
}
// PropertiesToValues converts feature's properties to protobuf Value
func PropertiesToValues(f *Feature) (map[string]*spb.Value, error) {
m := make(map[string]*spb.Value)
for k, vi := range f.Properties {
switch tv := vi.(type) {
case bool:
m[k] = &spb.Value{Kind: &spb.Value_BoolValue{BoolValue: tv}}
case int:
m[k] = &spb.Value{Kind: &spb.Value_NumberValue{NumberValue: float64(tv)}}
case string:
m[k] = &spb.Value{Kind: &spb.Value_StringValue{StringValue: tv}}
case float64:
m[k] = &spb.Value{Kind: &spb.Value_NumberValue{NumberValue: tv}}
case nil:
// pass
default:
return nil, fmt.Errorf("GeoJSON property %s unsupported type %T", k, tv)
}
}
return m, nil
}
// ValueToProperties converts a protobuf Value map to its JSON serializable map equivalent
func ValueToProperties(src map[string]*spb.Value) map[string]interface{} {
res := make(map[string]interface{})
for k, v := range src {
switch x := v.Kind.(type) {
case *spb.Value_NumberValue:
res[k] = x.NumberValue
case *spb.Value_StringValue:
res[k] = x.StringValue
case *spb.Value_BoolValue:
res[k] = x.BoolValue
}
}
return res
}
// CellUnionToTokens a cell union to a token string list
func CellUnionToTokens(cu s2.CellUnion) []string {
res := make([]string, len(cu))
for i, c := range cu {
res[i] = c.ToToken()
}
return res
}
// CellUnionToToken return a comma separated list of tokens
func CellUnionToToken(cu s2.CellUnion) string {
l := CellUnionToTokens(cu)
return strings.Join(l, ",")
}