Home > database >  Convert custom type to type [][]float64
Convert custom type to type [][]float64

Time:12-21

With Golang I would like to get these trackpoints (latitude, longitude) out of the database to generate a GeoJSON file like this:

{"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"LineString","coordinates":[[-122.271154,37.804348],[-122.272057,37.80295],[-122.272057,37.80295],[-122.278011,37.805288]]},"properties":null}]}

This is my code:

package main

import (
    "fmt"
    "log"
    "net/http"
    "time"

    "github.com/gorilla/mux"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql"
    geojson "github.com/paulmach/go.geojson"
    "github.com/shopspring/decimal"
)

var db *gorm.DB
var err error

type Trackpoint struct {
    Id        int             `json:"-"`
    Latitude  decimal.Decimal `json:"lat" sql:"type:decimal(10,8);"`
    Longitude decimal.Decimal `json:"long" sql:"type:decimal(11,8);"`
    Elevation uint
    Timestamp time.Time
}

func returnTrackpoints(w http.ResponseWriter, r *http.Request) {
    trackpoints := []Trackpoint{}
    db.Find(&trackpoints)
    coordinates := [][]float64{{-122.271154, 37.804348}, {-122.272057, 37.80295}, {-122.272057, 37.80295}, {-122.278011, 37.805288}}
    fc := geojson.NewFeatureCollection()
    fmt.Println(coordinates)
    fc.AddFeature(geojson.NewLineStringFeature(coordinates))
    rawJSON, err := fc.MarshalJSON()
    if err != nil {
        fmt.Println(err)
    }
    fmt.Fprintf(w, "%s", string(rawJSON))
}

func handleRequests() {
    log.Println("Starting development server at http://127.0.0.1:10000/")
    myRouter := mux.NewRouter().StrictSlash(true)
    myRouter.HandleFunc("/trackpoints", returnTrackpoints)
    log.Fatal(http.ListenAndServe(":10000", myRouter))
}

func main() {
    db, err = gorm.Open("mysql", "user:password&@tcp(127.0.0.1:3306)/database?charset=utf8&parseTime=True")

    if err != nil {
        log.Println("Connection Failed to Open")
    } else {
        log.Println("Connection Established")
    }

    db.AutoMigrate(&Trackpoint{})
    handleRequests()
}

If I use

fc.AddFeature(geojson.NewLineStringFeature(coordinates)) GeoJSON output looks fine.

But I would like to use the coordinates out of my database like

fc.AddFeature(geojson.NewLineStringFeature(trackpoints))

to use my GPS data stored in the database, but I'm getting the error

./main.go:33:44: cannot use trackpoint (type []Trackpoint) as type [][]float64 in argument to geojson.NewLineStringFeature

How can I convert the []Trackpoint type to [][]float64?

CodePudding user response:

  1. make a slice with the same amount of elements as your trackpoints
  2. Loop over each track point
  3. Convert decimal.Decimal types to float64
  4. Set float64 coordinates in the slice
  5. pass new slice to fc.AddFeature
func returnTrackpoints(w http.ResponseWriter, r *http.Request) {
    trackpoints := []Trackpoint{}
    db.Find(&trackpoints)
    
    coordinates := make([][]float64, len(trackpoints))
    for i, trackpoint := range trackpoints {
        lat, _ := trackpoint.Latitude.Float64()
        long, _ := trackpoint.Longitude.Float64()
        coordinates[i] = []float64{
            lat,
            long,
        }
    }
    fc := geojson.NewFeatureCollection()
    fmt.Println(coordinates)
    fc.AddFeature(geojson.NewLineStringFeature(coordinates))
    rawJSON, err := fc.MarshalJSON()
    if err != nil {
        fmt.Println(err)
    }
    fmt.Fprintf(w, "%s", string(rawJSON))
}
  • Related