-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpolygon.go
94 lines (71 loc) · 1.76 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
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 geo
import (
"errors"
"bytes"
"encoding/binary"
)
var (
ErrInvalidWkb = errors.New("geo: invalid WKB")
ErrUnsupportedDataType = errors.New("geo: scan value must be []byte")
ErrWrongGeometryType = errors.New("geo: wrong geometry type")
)
type Point [2]float64
type Polygon struct {
LinearRings []LinearRing
}
type LinearRing []Point
func (p *Polygon) SetLinearRings(rings []LinearRing) *Polygon {
p.LinearRings = rings
return p
}
func (p *Polygon) AddLinearRing(ring LinearRing) *Polygon {
p.LinearRings = append(p.LinearRings, ring)
return p
}
func (p *Polygon) ToGeoJson() (*Feature) {
geometry := Geometry{Type: "Polygon", Coordinates: p.LinearRings}
properties := make(map[string]interface{})
return &Feature{Type: "Feature", Geometry: geometry, Properties: properties}
}
func (p *Polygon) Scan(value interface{}) (err error) {
data, ok := value.([]byte)
if !ok {
return ErrUnsupportedDataType
}
if len(data) == 0 {
return
}
if len(data) < 9 {
return ErrInvalidWkb
}
buffer := bytes.NewBuffer(data)
var temp uint32
// First get the byte order. 0 for BigEndian, 1 for LittleEndian
first, err := buffer.ReadByte()
if err != nil {
return err
}
var order binary.ByteOrder = binary.BigEndian
if (first == 1) {
order = binary.LittleEndian
}
binary.Read(buffer, order, &temp)
typeCode := int(temp)
if typeCode != 3 {
return ErrWrongGeometryType
}
// Read the number of rings.
binary.Read(buffer, order, &temp)
ringCount := int(temp)
for j := 0; j < ringCount; j++ {
binary.Read(buffer, order, &temp)
length := int(temp)
points := make([]Point, length)
for i := 0; i < length; i++ {
binary.Read(buffer, order, &points[i][0])
binary.Read(buffer, order, &points[i][1])
}
p.AddLinearRing(points)
}
return
}