如何使用go语言从几何中的location获取'lat'和'lng'?
我正在尝试获取纬度和经度,以便在下一个api中使用它来获取特定位置的天气。
我在运行代码时遇到一个错误:
死机:运行时错误:索引超出范围
我的响应看起来像这样:https://developers.google.com/maps/documentation/geocoding/start
我的代码在这里。
package main
import (
"os"
"fmt"
"net/http"
"log"
"encoding/json"
"io/ioutil"
)
const helloMessage = "Hello to the weather program. Please enter the name of the city and the weather will show."
const googleApiUri = "https://maps.googleapis.com/maps/api/geocode/json?key=MYKEY&address="
type googleApiResponse struct {
Results Results `json:"results"`
}
type Results []Geometry
type Geometry struct {
Geometry Location `json:"geometry"`
}
type Location struct {
Location Coordinates `json:"location"`
}
type Coordinates struct {
Latitude string `json:"lat"`
Longitude string `json:"lng"`
}
func main() {
fmt.Println(helloMessage)
args := os.Args
getCityCoordinates(args[0])
}
func getCityCoordinates(city string) {
fmt.Println("Fetching langitude and longitude of the city ...")
resp, err := http.Get(googleApiUri + city)
if err != nil {
log.Fatal("Fetching google api uri data error: ", err)
}
bytes, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
log.Fatal("Reading google api data error: ", err)
}
var data googleApiResponse
json.Unmarshal(bytes, &data)
fmt.Println(data.Results[0].Geometry.Location.Latitude)
fmt.Println("Fetching langitude and longitude ended successful ...")
}
发布于 2018-06-09 21:26:09
尝试使用float64
来统一纬度和经度。因为它们不是字符串。因此在解组时显示错误。将Coordinates
结构更改为
type Coordinates struct {
Latitude float64 `json:"lat"`
Longitude float64 `json:"lng"`
}
检查Go Playground上的工作代码
有关Umarshal以及可使用的类型的更多信息。通过适用于JSON unmarshal的Golang规范
如果你不知道你的结构的格式,你也可以使用interface{}
。
要将JSON解组为接口值,unmarshal会在接口值中存储以下内容之一:
bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null
发布于 2019-08-25 22:26:32
var clinetGCM *maps.Client
if clinetGCM == nil {
// Pre-declare an err variable to avoid shadowing client.
var err error
clinetGCM, err = maps.NewClient(maps.WithAPIKey("api-key"))
if err != nil {
log.Fatalf("maps.NewClient failed: %v", err)
}
}
//CM is a google cloud maps
type CM struct {
Client *maps.Client
}
// Location is a gps
type Location struct {
Lat float64 `json:"lat"`
Lng float64 `json:"lng"`
}
// GeocodeAdress provided Location data from gcp maps geocoder api
func (cm *CM) GeocodeAdress(address string) (Location, error) {
var loc Location
r := &maps.GeocodingRequest{
Address: address,
}
res, err := cm.Client.Geocode(context.Background(), r)
if err != nil || len(res) == 0 {
return loc, fmt.Errorf("res Geocode err: %v", err)
}
loc.Lat = res[0].Geometry.Location.Lat
loc.Lng = res[0].Geometry.Location.Lng
return loc, nil
}
https://stackoverflow.com/questions/50774397
复制相似问题