-
Notifications
You must be signed in to change notification settings - Fork 106
/
wkt.go
134 lines (119 loc) · 2.44 KB
/
wkt.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package wkt
import (
"bytes"
"fmt"
"github.com/paulmach/orb"
)
// Marshal returns a WKT representation of the geometry.
func Marshal(g orb.Geometry) []byte {
buf := bytes.NewBuffer(nil)
wkt(buf, g)
return buf.Bytes()
}
// MarshalString returns a WKT representation of the geometry as a string.
func MarshalString(g orb.Geometry) string {
buf := bytes.NewBuffer(nil)
wkt(buf, g)
return buf.String()
}
func wkt(buf *bytes.Buffer, geom orb.Geometry) {
switch g := geom.(type) {
case orb.Point:
fmt.Fprintf(buf, "POINT(%g %g)", g[0], g[1])
case orb.MultiPoint:
if len(g) == 0 {
buf.Write([]byte(`MULTIPOINT EMPTY`))
return
}
buf.Write([]byte(`MULTIPOINT(`))
for i, p := range g {
if i != 0 {
buf.WriteByte(',')
}
fmt.Fprintf(buf, "(%g %g)", p[0], p[1])
}
buf.WriteByte(')')
case orb.LineString:
if len(g) == 0 {
buf.Write([]byte(`LINESTRING EMPTY`))
return
}
buf.Write([]byte(`LINESTRING`))
writeLineString(buf, g)
case orb.MultiLineString:
if len(g) == 0 {
buf.Write([]byte(`MULTILINESTRING EMPTY`))
return
}
buf.Write([]byte(`MULTILINESTRING(`))
for i, ls := range g {
if i != 0 {
buf.WriteByte(',')
}
writeLineString(buf, ls)
}
buf.WriteByte(')')
case orb.Ring:
wkt(buf, orb.Polygon{g})
case orb.Polygon:
if len(g) == 0 {
buf.Write([]byte(`POLYGON EMPTY`))
return
}
buf.Write([]byte(`POLYGON(`))
for i, r := range g {
if i != 0 {
buf.WriteByte(',')
}
writeLineString(buf, orb.LineString(r))
}
buf.WriteByte(')')
case orb.MultiPolygon:
if len(g) == 0 {
buf.Write([]byte(`MULTIPOLYGON EMPTY`))
return
}
buf.Write([]byte(`MULTIPOLYGON(`))
for i, p := range g {
if i != 0 {
buf.WriteByte(',')
}
buf.WriteByte('(')
for j, r := range p {
if j != 0 {
buf.WriteByte(',')
}
writeLineString(buf, orb.LineString(r))
}
buf.WriteByte(')')
}
buf.WriteByte(')')
case orb.Collection:
if len(g) == 0 {
buf.Write([]byte(`GEOMETRYCOLLECTION EMPTY`))
return
}
buf.Write([]byte(`GEOMETRYCOLLECTION(`))
for i, c := range g {
if i != 0 {
buf.WriteByte(',')
}
wkt(buf, c)
}
buf.WriteByte(')')
case orb.Bound:
wkt(buf, g.ToPolygon())
default:
panic("unsupported type")
}
}
func writeLineString(buf *bytes.Buffer, ls orb.LineString) {
buf.WriteByte('(')
for i, p := range ls {
if i != 0 {
buf.WriteByte(',')
}
fmt.Fprintf(buf, "%g %g", p[0], p[1])
}
buf.WriteByte(')')
}