Search code examples
jsongostructgetunmarshalling

How to get latitude and longitude from google map api using go language?


How to get 'lat' and 'lng' from location in geometry using go language ?

I'm trying to get latitude and longitude to use it for next api to fetch weather of specific location.

I am getting an error when running the code:

panic: runtime error: index out of range

My response looks like this: https://developers.google.com/maps/documentation/geocoding/start

My code is here.

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


Solution

  • Try to use float64 to umarshal the latitude and longitude. Since they are not strings. Hence showing error when unmarshalling. Change Coordinates struct to

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

    Check working code on Go Playground

    For more information on Umarshal along with types that can be used. Go through Golang Spec for JSON unmarshal

    You can also use interface{} if you don't know the format of your struct.

    To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:

    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