forked from dewski/spatial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
encoding.go
94 lines (75 loc) · 1.52 KB
/
encoding.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
package spatial
import (
"bytes"
"io"
"math"
"github.com/pkg/errors"
)
func Decode(points string, precision int) ([]Point, error) {
var lat, lng int64
factor := math.Pow10(precision)
input := bytes.NewBufferString(points)
path := []Point{}
for {
dlat, _ := decodeInt(input)
dlng, err := decodeInt(input)
if err == io.EOF {
return path, nil
}
if err != nil {
return nil, errors.Wrap(err, "unexpected error decoding polyline")
}
lat, lng = lat+dlat, lng+dlng
path = append(path, Point{
Lat: float64(lat) / factor,
Lng: float64(lng) / factor,
})
}
}
func Encode(path []Point, precision int) string {
var prevLat, prevLng int64
factor := math.Pow10(precision)
out := new(bytes.Buffer)
out.Grow(len(path) * 4)
for _, p := range path {
lat := int64(math.Floor(p.Lat*factor + 0.5))
lng := int64(math.Floor(p.Lng*factor + 0.5))
encodeInt(lat-prevLat, out)
encodeInt(lng-prevLng, out)
prevLat, prevLng = lat, lng
}
return out.String()
}
func decodeInt(r io.ByteReader) (int64, error) {
var shift uint8
result := int64(0)
for {
raw, err := r.ReadByte()
if err != nil {
return 0, err
}
b := raw - 63
result += (int64(b) & 0x1f) << shift
shift += 5
if b < 0x1f {
bit := result & 1
result >>= 1
if bit != 0 {
result = ^result
}
return result, nil
}
}
}
func encodeInt(v int64, w io.ByteWriter) {
if v < 0 {
v = ^(v << 1)
} else {
v <<= 1
}
for v >= 0x20 {
w.WriteByte((0x20 | (byte(v) & 0x1f)) + 63)
v >>= 5
}
w.WriteByte(byte(v) + 63)
}