将自定义类型转换为类型[][]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?

  1. 制作一个与轨迹点元素数量相同的切片
  2. 在每个轨道点上循环
  3. 转换小数。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))
}

相关内容

  • 没有找到相关文章

最新更新