首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用go语言从google地图api获取纬度和经度?

如何使用go语言从google地图api获取纬度和经度?
EN

Stack Overflow用户
提问于 2018-06-09 20:40:49
回答 2查看 2.3K关注 0票数 1

如何使用go语言从几何中的location获取'lat''lng'

我正在尝试获取纬度和经度,以便在下一个api中使用它来获取特定位置的天气。

我在运行代码时遇到一个错误:

死机:运行时错误:索引超出范围

我的响应看起来像这样:https://developers.google.com/maps/documentation/geocoding/start

我的代码在这里。

代码语言:javascript
复制
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 ...")
}

enter image description here

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-06-09 21:26:09

尝试使用float64来统一纬度和经度。因为它们不是字符串。因此在解组时显示错误。将Coordinates结构更改为

代码语言:javascript
复制
type Coordinates struct {
    Latitude  float64 `json:"lat"`
    Longitude float64 `json:"lng"`
}

检查Go Playground上的工作代码

有关Umarshal以及可使用的类型的更多信息。通过适用于JSON unmarshal的Golang规范

如果你不知道你的结构的格式,你也可以使用interface{}

要将JSON解组为接口值,unmarshal会在接口值中存储以下内容之一:

代码语言:javascript
复制
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
票数 0
EN

Stack Overflow用户

发布于 2019-08-25 22:26:32

直接调用google-maps-services-go

代码语言:javascript
复制
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
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50774397

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档