Mar*_*oma 3 go reverse-geocoding
如何使用 Go 从坐标(例如 49.014,8.4043)获取地理位置(例如最近的城市)?
\n\n我尝试使用golang-geo:
\n\npackage main\n\nimport (\n "log"\n\n "github.com/kellydunn/golang-geo"\n)\n\nfunc main() {\n p := geo.NewPoint(49.014, 8.4043)\n geocoder := new(geo.GoogleGeocoder)\n geo.HandleWithSQL()\n res, err := geocoder.ReverseGeocode(p)\n if err != nil {\n log.Println(err)\n }\n log.Println(string(res))\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n但它给出了Schlo\xc3\x9fplatz 23, 76131 Karlsruhe, Germany
. 我想要\n Karlsruhe
(所以:只有城市)。
如何只获取城市?
\n小智 5
您要提取的数据不会直接从库返回。但是,您可以执行请求并自行解析 JSON 响应以提取城市,而不是完整地址:
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)
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3858 次 |
最近记录: |