|
18 | 18 | </template> |
19 | 19 |
|
20 | 20 | <script setup> |
21 | | -import { getAdcode, getWeather, getOtherWeather } from "@/api"; |
| 21 | +import { getAdcode, getWeather, getOtherWeather, getRegeo } from "@/api"; |
22 | 22 | import { Error } from "@icon-park/vue-next"; |
23 | 23 |
|
24 | 24 | // 高德开发者 Key |
@@ -70,16 +70,61 @@ const getWeatherData = async () => { |
70 | 70 | windpower: data.condition.day_wind_power, |
71 | 71 | }; |
72 | 72 | } else { |
73 | | - // 获取 Adcode |
74 | | - const adCode = await getAdcode(mainKey); |
75 | | - console.log(adCode); |
76 | | - if (adCode.infocode !== "10000") { |
77 | | - throw "地区查询失败"; |
| 73 | + // 优先尝试浏览器定位(需要用户授权),若成功使用 regeo 获取 adcode;否则回退到 IP 定位 |
| 74 | + console.log("尝试使用浏览器定位获取经纬度"); |
| 75 | + const getPosition = (timeout = 8000) => |
| 76 | + new Promise((resolve, reject) => { |
| 77 | + if (!navigator.geolocation) return reject(new Error("浏览器不支持定位")); |
| 78 | + const timer = setTimeout(() => reject(new Error("定位超时")), timeout); |
| 79 | + navigator.geolocation.getCurrentPosition( |
| 80 | + (pos) => { |
| 81 | + clearTimeout(timer); |
| 82 | + resolve(pos.coords); |
| 83 | + }, |
| 84 | + (err) => { |
| 85 | + clearTimeout(timer); |
| 86 | + reject(err); |
| 87 | + }, |
| 88 | + { enableHighAccuracy: false, timeout: 8000, maximumAge: 0 }, |
| 89 | + ); |
| 90 | + }); |
| 91 | +
|
| 92 | + let adCodeFromGeo = null; |
| 93 | + try { |
| 94 | + const coords = await getPosition(8000); |
| 95 | + console.log("浏览器定位经纬度:", coords); |
| 96 | + const location = `${coords.longitude},${coords.latitude}`; |
| 97 | + const regeo = await getRegeo(mainKey, location); |
| 98 | + console.log("regeo 返回:", regeo); |
| 99 | + if (regeo && regeo.status === "1" && regeo.regeocode) { |
| 100 | + const comp = regeo.regeocode.addressComponent || {}; |
| 101 | + adCodeFromGeo = { |
| 102 | + city: comp.city || comp.province || comp.township || "未知地区", |
| 103 | + adcode: comp.adcode || null, |
| 104 | + }; |
| 105 | + } |
| 106 | + } catch (err) { |
| 107 | + console.warn("浏览器定位或 regeo 失败,回退到 IP 定位:", err); |
78 | 108 | } |
79 | | - weatherData.adCode = { |
80 | | - city: adCode.city, |
81 | | - adcode: adCode.adcode, |
82 | | - }; |
| 109 | +
|
| 110 | + if (adCodeFromGeo && adCodeFromGeo.adcode) { |
| 111 | + weatherData.adCode = { |
| 112 | + city: adCodeFromGeo.city, |
| 113 | + adcode: adCodeFromGeo.adcode, |
| 114 | + }; |
| 115 | + } else { |
| 116 | + // 回退到 IP 定位 |
| 117 | + const adCode = await getAdcode(mainKey); |
| 118 | + console.log("IP 定位返回:", adCode); |
| 119 | + if (adCode.infocode !== "10000") { |
| 120 | + throw "地区查询失败"; |
| 121 | + } |
| 122 | + weatherData.adCode = { |
| 123 | + city: adCode.city, |
| 124 | + adcode: adCode.adcode, |
| 125 | + }; |
| 126 | + } |
| 127 | +
|
83 | 128 | // 获取天气信息 |
84 | 129 | const result = await getWeather(mainKey, weatherData.adCode.adcode); |
85 | 130 | // 打印返回用于排查 |
|
0 commit comments