首页
学习
活动
专区
工具
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

我的代码在这里。

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
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50774397

复制
相关文章

相似问题

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