Compare commits

...

4 Commits

Author SHA1 Message Date
JNG
b1e1d317ed 添加ip获取位置 2026-03-13 09:56:15 +08:00
JNG
469b0313ce 添加ip获取位置 2026-03-13 09:53:34 +08:00
JNG
c33fa06382 11 2026-03-12 16:31:35 +08:00
JNG
c982910bfb 11 2026-03-12 16:27:20 +08:00
2 changed files with 75 additions and 5 deletions

View File

@ -65,15 +65,21 @@ func QuestionnaireSurveyCreate(c *gin.Context) {
service.Error(c, err)
return
}
if req.Longitude == "" || req.Latitude == "" {
service.Error(c, errors.New("获取定位失败"))
return
}
address, err := utils.ReverseGeo(req.Longitude, req.Latitude, "ZhCN")
ip := c.ClientIP()
address, err := utils.GetAddressByIP(ip)
if err != nil {
service.Error(c, errors.New("获取地址失败"))
return
}
//if req.Longitude == "" || req.Latitude == "" {
// service.Error(c, errors.New("获取定位失败"))
// return
//}
//address, err := utils.ReverseGeo(req.Longitude, req.Latitude, "ZhCN")
//if err != nil {
// service.Error(c, errors.New("获取地址失败"))
// return
//}
surveyInfo, err := service.BundleProvider.GetQuestionnaireSurveyInfo(c, &bundle.GetQuestionnaireSurveyInfoRequest{UserTel: req.UserTel})
if err != nil {
service.Error(c, err)

View File

@ -2,11 +2,28 @@ package utils
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
)
const baiduIPLocationAPI = "https://api.map.baidu.com/location/ip"
// 建议把 ak 放配置;这里先保留你给的 key后续可改为从配置读取。
const baiduMapAK = "T8DGBYxbZ1iAeXx1J57McKigyHJHulPQ"
type baiduIPResp struct {
Status int `json:"status"`
Address string `json:"address"`
Content struct {
Address string `json:"address"`
} `json:"content"`
Message string `json:"message"`
}
type ReverseGeocodingReq struct {
Ak string `json:"ak"`
Coordtype string `json:"coordtype"`
@ -86,3 +103,50 @@ func ReverseGeo(longitude, latitude string, language string) (address string, er
return address, nil
}
func GetAddressByIP(ip string) (string, error) {
ip = strings.TrimSpace(ip)
if ip == "" {
return "", fmt.Errorf("ip is empty")
}
q := url.Values{}
q.Set("ip", ip)
q.Set("coor", "bd09ll")
q.Set("ak", baiduMapAK)
reqURL := baiduIPLocationAPI + "?" + q.Encode()
client := &http.Client{Timeout: 5 * time.Second}
resp, err := client.Get(reqURL)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("baidu api status: %d", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
var r baiduIPResp
if err := json.Unmarshal(body, &r); err != nil {
return "", err
}
if r.Status != 0 {
if r.Message == "" {
r.Message = "baidu api error"
}
return "", fmt.Errorf("%s", r.Message)
}
if strings.TrimSpace(r.Content.Address) != "" {
return r.Content.Address, nil
}
if strings.TrimSpace(r.Address) != "" {
return r.Address, nil
}
return "", nil
}