将自定义类型转换为类型 [][]float64
Posted
技术标签:
【中文标题】将自定义类型转换为类型 [][]float64【英文标题】:Convert custom type to type [][]float64 【发布时间】:2022-01-22 01:35:43 【问题描述】:使用 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?
【问题讨论】:
【参考方案1】:-
使用与跟踪点相同数量的元素制作切片
循环遍历每个跟踪点
Convert decimal.Decimal types to float64
在切片中设置 float64 坐标
将新切片传递给
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))
【讨论】:
以上是关于将自定义类型转换为类型 [][]float64的主要内容,如果未能解决你的问题,请参考以下文章
将 numpy 数组类型和值从 Float64 转换为 Float32
Doctrine / Symfony:在使用 QueryBuilder 之前将自定义类型转换为数据库值