如何使用Go获取离地理坐标最近的城市? [英] How can I get the nearest city to geo-coordinates with Go?

查看:65
本文介绍了如何使用Go获取离地理坐标最近的城市?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Go从坐标(例如49.014,8.4043)获得地理位置(例如最近的城市)?

How do I get a geolocation (e.g. the nearest city) from coordinates (e.g. 49.014,8.4043) with Go?

我尝试使用 golang-geo :

package main

import (
    "log"

    "github.com/kellydunn/golang-geo"
)

func main() {
    p := geo.NewPoint(49.014, 8.4043)
    geocoder := new(geo.GoogleGeocoder)
    geo.HandleWithSQL()
    res, err := geocoder.ReverseGeocode(p)
    if err != nil {
        log.Println(err)
    }
    log.Println(string(res))
}

但给出的是德国卡尔斯鲁厄的Schloßplatz23,76131 .我想 Karlsruhe (所以:只有城市).

but it gives Schloßplatz 23, 76131 Karlsruhe, Germany. I would like Karlsruhe (so: only the city).

我怎么只去城市?

推荐答案

您要提取的数据不会直接从库中返回.但是,您可以执行请求并自己解析JSON响应以提取城市,而不是完整地址:

The data you are looking to extract is not returned directly from the library. You can, however, perform a request and parse the JSON response yourself to extract the city, rather than the full address:

package main

import (
    "encoding/json"
    "fmt"
    "log"

    "github.com/kellydunn/golang-geo"
)

type googleGeocodeResponse struct {
    Results []struct {
        AddressComponents []struct {
            LongName  string   `json:"long_name"`
            Types     []string `json:"types"`
        } `json:"address_components"`
    }
}

func main() {
    p := geo.NewPoint(49.014, 8.4043)
    geocoder := new(geo.GoogleGeocoder)
    geo.HandleWithSQL()
    data, err := geocoder.Request(fmt.Sprintf("latlng=%f,%f", p.Lat(), p.Lng()))
    if err != nil {
        log.Println(err)
    }
    var res googleGeocodeResponse
    if err := json.Unmarshal(data, &res); err != nil {
        log.Println(err)
    }
    var city string
    if len(res.Results) > 0 {
        r := res.Results[0]
    outer:
        for _, comp := range r.AddressComponents {
            // See https://developers.google.com/maps/documentation/geocoding/#Types
            // for address types
            for _, compType := range comp.Types {
                if compType == "locality" {
                    city = comp.LongName
                    break outer
                }
            }
        }
    }
    fmt.Printf("City: %s\n", city)
}

这篇关于如何使用Go获取离地理坐标最近的城市?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆