将自定义类型转换为类型[][]float64

huangapple go评论74阅读模式
英文:

Convert custom type to type [][]float64

问题

使用Golang,我想从数据库中获取这些轨迹点(纬度、经度),以生成一个类似于以下的GeoJSON文件:

{"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}]}

这是我的代码:

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

如果我使用

fc.AddFeature(geojson.NewLineStringFeature(coordinates))

GeoJSON输出看起来很好。

但是我想使用从数据库中获取的坐标,像这样:

fc.AddFeature(geojson.NewLineStringFeature(trackpoints))

以使用存储在数据库中的GPS数据,但是我得到了错误:

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

如何将[]Trackpoint类型转换为[][]float64类型?

英文:

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?

答案1

得分: 0

  1. 使用与您的轨迹点相同数量的元素创建一个切片。
  2. 循环遍历每个轨迹点。
  3. 将 decimal.Decimal 类型转换为 float64 类型。
  4. 在切片中设置 float64 坐标。
  5. 将新切片传递给 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))
}
英文:
  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))
}

huangapple
  • 本文由 发表于 2021年12月20日 20:23:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/70421752.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定