-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathh3_to_geojson.go
45 lines (41 loc) · 1.26 KB
/
h3_to_geojson.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
package geojson2h3
import (
"fmt"
"strconv"
"github.com/tidwall/geojson"
"github.com/tidwall/geojson/geometry"
"github.com/uber/h3-go/v3"
)
// ToFeatureCollection converts a set of hexagons to a GeoJSON `FeatureCollection`
// with the set outline(s). The feature's geometry type will be `Polygon`.
func ToFeatureCollection(indexes []h3.H3Index) (*geojson.FeatureCollection, error) {
if len(indexes) == 0 {
return nil, fmt.Errorf("uber h3 indexes are empty")
}
features := make([]geojson.Object, 0, len(indexes))
for _, index := range indexes {
boundary := h3.ToGeoBoundary(index)
points := make([]geometry.Point, 0, 6)
for _, b := range boundary {
points = append(points, geometry.Point{
X: b.Longitude,
Y: b.Latitude,
})
}
points = append(points, geometry.Point{
X: points[0].X,
Y: points[0].Y,
})
polygon := geojson.NewPolygon(
geometry.NewPoly(points, nil, &geometry.IndexOptions{
Kind: geometry.None,
}))
feature := geojson.NewFeature(polygon, toH3Props(index))
features = append(features, feature)
}
return geojson.NewFeatureCollection(features), nil
}
func toH3Props(index h3.H3Index) string {
res := strconv.Itoa(h3.Resolution(index))
return `{"h3index":"` + h3.ToString(index) + `", "h3resolution": ` + res + `}`
}