-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgeometry.go
66 lines (61 loc) · 1.58 KB
/
geometry.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
package geojson
import (
"encoding/json"
"fmt"
"log"
"regexp"
"strings"
)
type Geometry struct {
geoType string
coordinates interface{}
}
func NewGeometry(geoType string, coordinates interface{}) *Geometry {
return &Geometry{geoType, coordinates}
}
func NewGeometryFromWkt(wkt string) (*Geometry, error) {
geoTypes := []string{
"Point",
"MultiPoint",
"LineString",
"MultiLineString",
"Polygon",
"MultiPolygon",
//"GeometryCollection",
}
bracket := strings.Index(wkt, "(")
geoType := strings.ToUpper(strings.TrimSpace(wkt[0:bracket]))
supported := false
for _, typeName := range geoTypes {
if strings.ToUpper(typeName) == geoType {
geoType = typeName
supported = true
}
}
if !supported {
err := fmt.Errorf("Geometry type not supported: %s", geoType)
return nil, err
}
coordinates := wkt[bracket:]
if !strings.HasSuffix(geoType, "Point") || (geoType == "MultiPoint" && coordinates[1:2] != "(") {
re := regexp.MustCompile(`([0-9\-\.]+ )+([0-9\-\.]+)`)
coordinates = re.ReplaceAllString(coordinates, "[${1}${2}]")
}
re := strings.NewReplacer("(", "[", ")", "]", ", ", ",", " ", ",")
coordinates = re.Replace(coordinates)
var coord interface{}
if err := json.Unmarshal([]byte(coordinates), &coord); err != nil {
log.Printf("Could not decode WKT %s : %s", coordinates, err)
return nil, err
} else {
return &Geometry{geoType, coord}, nil
}
}
// json marshaling for struct Geometry
func (g *Geometry) MarshalJSON() ([]byte, error) {
return json.Marshal(
map[string]interface{}{
"type": g.geoType,
"coordinates": g.coordinates,
})
}