package utils import ( "encoding/json" "io" "net/http" "net/url" "strconv" ) var ak = "ji0v0JfOZDlXHmICe93NFMEN67AxMSxN" var host = "https://api.map.baidu.com" var geoUrl = "/geocoding/v3" var recogUrl = "/api_recog_address/v1/recog" 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 } type BmapRecogRequest struct { Address string } type BmapRecogResponse struct { Province string City string County string Town string } type RecogResponse struct { Status int Admin_info struct { Province string City string County string Town string } } func GetAddrGeocoding(request BmapGeoCodingRequest) *BmapGeoCodingResponse { // 设置请求参数 params := url.Values{ "address": []string{request.Address}, "output": []string{"json"}, "ak": []string{ak}, } // 发起请求 requestStr, _ := url.Parse(host + geoUrl + "?" + 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 } func GetAddrRecog(request BmapRecogRequest) *BmapRecogResponse { // 设置请求参数 params := url.Values{ "address": []string{request.Address}, "ak": []string{ak}, } // 发起请求 requestStr, _ := url.Parse(host + recogUrl + "?" + params.Encode()) resp, err := http.Get(requestStr.String()) if err != nil || resp.StatusCode != 200 { return nil } r, _ := io.ReadAll(resp.Body) var response RecogResponse json.Unmarshal(r, &response) bmapRecogResponse := BmapRecogResponse{ Province: response.Admin_info.Province, City: response.Admin_info.City, County: response.Admin_info.County, Town: response.Admin_info.Town, } return &bmapRecogResponse }