-
Notifications
You must be signed in to change notification settings - Fork 1
/
position.go
82 lines (70 loc) · 1.82 KB
/
position.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
package geojson
import (
"encoding/json"
"fmt"
"github.com/golang/geo/s2"
)
// Position represents a longitude and latitude with optional elevation/altitude.
type Position struct {
pos s2.LatLng
elevation *float64
}
// MakePosition from longitude and latitude.
func MakePosition(lat, lng float64) Position {
return Position{
pos: s2.LatLngFromDegrees(lat, lng),
}
}
// MakePositionWithElevation from longitude, latitude and elevation.
func MakePositionWithElevation(lat, lng, elevation float64) Position {
return Position{
pos: s2.LatLngFromDegrees(lat, lng),
elevation: &elevation,
}
}
func (p Position) String() string {
if p.elevation != nil {
return fmt.Sprintf("[%G, %G, %G]", p.pos.Lng.Degrees(), p.pos.Lat.Degrees(), *p.elevation)
}
return fmt.Sprintf("[%G, %G]", p.pos.Lng.Degrees(), p.pos.Lat.Degrees())
}
// Validate the position.
func (p Position) Validate() error {
if !p.pos.IsValid() {
return fmt.Errorf("invalid latlng")
}
return nil
}
// MarshalJSON returns the JSON encoding of the Position.
// The JSON encoding is an array of numbers with the longitude followed by the latitude, and optional elevation.
func (p Position) MarshalJSON() ([]byte, error) {
if p.elevation != nil {
return json.Marshal(&position{
p.pos.Lng.Degrees(),
p.pos.Lat.Degrees(),
*p.elevation,
})
}
return json.Marshal(&position{
p.pos.Lng.Degrees(),
p.pos.Lat.Degrees(),
})
}
// UnmarshalJSON parses the JSON-encoded data and stores the results.
func (p *Position) UnmarshalJSON(data []byte) error {
pos := position{}
if err := json.Unmarshal(data, &pos); err != nil {
return err
}
switch len(pos) {
case 3:
p.elevation = &pos[2]
fallthrough
case 2:
p.pos = s2.LatLngFromDegrees(pos[1], pos[0])
default:
return fmt.Errorf("invalid position")
}
return nil
}
type position []float64