-
Notifications
You must be signed in to change notification settings - Fork 0
/
h3.go
120 lines (94 loc) · 2.39 KB
/
h3.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
// Copyright 2022 Stichting ThingsIX Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
package h3light
import (
"fmt"
"log"
"strconv"
"github.com/Kl1mn/h3-go"
)
type Cell uint64
func (c Cell) String() string {
return fmt.Sprintf("%x", uint64(c))
}
func (c Cell) Int64() int64 {
return int64(c)
}
func (c Cell) Parent(res int) Cell {
if c.Resolution() < res {
return 0
}
if c.Resolution() == res {
return c
}
u := uint64(c)
resfill := (^uint64(0)) >> (19 + res*3)
u |= resfill
mask := uint64(0b1111 << 52)
u &^= mask
u |= uint64(res) << 52
return Cell(u)
}
func (c Cell) LatLon() (float64, float64) {
geo := h3.ToGeo(h3.H3Index(c))
return geo.Latitude, geo.Longitude
}
func (c Cell) DatabaseCell() DatabaseCell {
return DatabaseCellFromCell(uint64(c))
}
func (c *Cell) DatabaseCellPtr() *DatabaseCell {
if c == nil {
return nil
}
ret := c.DatabaseCell()
return &ret
}
func (c Cell) Resolution() int {
return int((uint64(c) >> 52) & 0b1111)
}
func CellFromString(str string) (Cell, error) {
i, err := strconv.ParseUint(str, 16, 64)
if err != nil {
return 0, err
}
return Cell(i), nil
}
func MustCellFromString(str string) Cell {
c, err := CellFromString(str)
if err != nil {
log.Fatal(err)
}
return c
}
func LatLonToRes0ToCell(lat, lon float64) Cell {
return Cell(h3.FromGeo(h3.GeoCoord{Latitude: lat, Longitude: lon}, 0))
}
func LatLonToCell(lat, lon float64, res int) Cell {
return Cell(h3.FromGeo(h3.GeoCoord{Latitude: lat, Longitude: lon}, res))
}
// MarshalText implements the encoding.TextMarshaler interface.
func (c Cell) MarshalText() ([]byte, error) {
return []byte(c.String()), nil
}
// UnmarshalText implements the encoding.TextUnmarshaler interface.
func (c *Cell) UnmarshalText(text []byte) error {
var err error
*c, err = CellFromString(string(text))
if err != nil {
return err
}
return nil
}