gocoordinatespolygonwkb

Golang create wkb.Polygon from a list of coordinates


I have lists of coordinates in a file which I want to get their polygon. I used wkb library to load the coordinates, but when I try to set them into the wkb.Polygon object, I get an error:

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

This is my code:

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

I also tried:

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

But I got:

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

Solution

  • First of all, you need to create a general Polygon like this:

    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())
    }
    

    Then you can marshal it into wkb format.

            // 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)