首页 > 解决方案 > Golang 从坐标列表创建 wkb.Polygon

问题描述

我在一个文件中有坐标列表,我想获取它们的多边形。我使用wkb库来加载坐标,但是当我尝试将它们设置到wkb.Polygon对象中时,出现错误:

panic: interface conversion: interface {} is [][][]float64, not [][]geom.Coord

这是我的代码:

var cc interface {} = collection.Features[0].Geometry.Polygon
c := cc.([][]geom.Coord)
po, err := wkb.Polygon{}.SetCoords(c)

我也试过:

c := collection.Features[0].Geometry.Polygon.([][]geom.Coord)

但我得到了:

Invalid type assertion: collection.Features[0].Geometry.Polygon.([][]geom.Coord) (non-interface type [][][]float64 on left)

标签: gocoordinatespolygonwkb

解决方案


首先,您需要像这样创建一个通用多边形:

package main

import (
        "fmt"

        "github.com/twpayne/go-geom"
)

func main() {
        unitSquare := geom.NewPolygon(geom.XY).MustSetCoords([][]geom.Coord{
                {{0, 0}, {1, 0}, {1, 1}, {0, 1}, {0, 0}},
        })
        fmt.Printf("unitSquare.Area() == %f", unitSquare.Area())
}

然后,您可以将其编组为wkb格式。

        // marshal into wkb with litten endian
        b, err := wkb.Marshal(unitSquare, wkb.NDR)
        if err != nil {
                fmt.Printf("wkb marshal error: %s\n", err.Error())
                return
        }
        fmt.Println(b)

推荐阅读