Как получить широту и долготу от API карты Google, используя язык Go? - PullRequest
0 голосов
/ 09 июня 2018

Как получить 'lat' и 'lng' из местоположения в геометрии, используя язык go?

Я пытаюсьполучить широту и долготу, чтобы использовать ее для следующего 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 ...")
}

введите описание изображения здесь

Ответы [ 2 ]

0 голосов
/ 25 августа 2019

позвоните на google-maps-services-go напрямую:

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
}
0 голосов
/ 09 июня 2018

Попробуйте использовать float64, чтобы уменьшить широту и долготу.Так как они не строки.Следовательно, показывая ошибку при демаршаллинге.Измените Coordinates struct на

type Coordinates struct {
    Latitude  float64 `json:"lat"`
    Longitude float64 `json:"lng"`
}

Проверьте рабочий код на Go Playground

Для получения дополнительной информации об Umarshal, а также о типах, которые можно использовать.Пройдите Golang Spec для JSON unmarshal

Вы также можете использовать 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...