-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpolygon.go
64 lines (52 loc) · 1.34 KB
/
polygon.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
package joejson
import (
"encoding/json"
"fmt"
)
// GeometryTypePolygon is the value for a Polygon's 'type' member.
const GeometryTypePolygon = "Polygon"
// LinearRing is a closed LineString with four or more positions.
type LinearRing []Position
// Raw exposes the data for this geometry as primitive types.
func (l LinearRing) Raw() [][]float64 {
out := make([][]float64, len(l))
for i, pos := range l {
out[i] = pos
}
return out
}
// Polygon is a slice of LinearRing.
type Polygon []LinearRing
// Raw exposes the data for this geometry as primitive types.
func (p Polygon) Raw() [][][]float64 {
out := make([][][]float64, len(p))
for i, lr := range p {
out[i] = lr.Raw()
}
return out
}
// MarshalJSON is a custom JSON marshaller.
func (p Polygon) MarshalJSON() ([]byte, error) {
return json.Marshal(&struct {
Rings []LinearRing `json:"coordinates"`
Type string `json:"type"`
}{
p,
GeometryTypePolygon,
})
}
// UnmarshalJSON is a custom JSON unmarshaller.
func (p *Polygon) UnmarshalJSON(b []byte) error {
var tmp struct {
Rings []LinearRing `json:"coordinates"`
Type string `json:"type"`
}
if err := json.Unmarshal(b, &tmp); err != nil {
return err
}
if tmp.Type != GeometryTypePolygon {
return fmt.Errorf("invalid type %q, expected %q", tmp.Type, GeometryTypePolygon)
}
*p = tmp.Rings
return nil
}