59 lines
1.2 KiB
Go
59 lines
1.2 KiB
Go
package utils
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"strconv"
|
|
)
|
|
|
|
var ak = "ji0v0JfOZDlXHmICe93NFMEN67AxMSxN"
|
|
var host = "https://api.map.baidu.com"
|
|
var uri = "/geocoding/v3"
|
|
|
|
type Location struct {
|
|
Lng float64
|
|
Lat float64
|
|
}
|
|
type GeocodingResponse struct {
|
|
Status int
|
|
Result struct {
|
|
Location Location
|
|
Precise int
|
|
Confidence int
|
|
Comprehension int
|
|
Level string
|
|
}
|
|
}
|
|
|
|
type BmapGeoCodingRequest struct {
|
|
Address string
|
|
}
|
|
|
|
type BmapGeoCodingResponse struct {
|
|
Longitude string
|
|
Latitude string
|
|
}
|
|
|
|
func GetAddrGeocoding(request BmapGeoCodingRequest) *BmapGeoCodingResponse {
|
|
// 设置请求参数
|
|
params := url.Values{
|
|
"address": []string{request.Address},
|
|
"output": []string{"json"},
|
|
"ak": []string{ak},
|
|
}
|
|
|
|
// 发起请求
|
|
requestStr, _ := url.Parse(host + uri + "?" + params.Encode())
|
|
resp, err := http.Get(requestStr.String())
|
|
if err != nil || resp.StatusCode != 200 {
|
|
return nil
|
|
}
|
|
r, _ := io.ReadAll(resp.Body)
|
|
var response GeocodingResponse
|
|
json.Unmarshal(r, &response)
|
|
bmapGeoCodingResponse := BmapGeoCodingResponse{strconv.FormatFloat(response.Result.Location.Lng, 'f', -1, 64), strconv.FormatFloat(response.Result.Location.Lat, 'f', -1, 64)}
|
|
return &bmapGeoCodingResponse
|
|
}
|