张延森 3 anos atrás
pai
commit
84d8f6d3e3
2 arquivos alterados com 21 adições e 14 exclusões
  1. 18
    11
      src/components/AMap/weather.js
  2. 3
    3
      src/pages/MonitoringScreen/index.jsx

+ 18
- 11
src/components/AMap/weather.js Ver arquivo

1
 const SERVER_KEY = 'a30b66a26ea1890fd656cf11cb2647fb';
1
 const SERVER_KEY = 'a30b66a26ea1890fd656cf11cb2647fb';
2
 
2
 
3
-export default function getWeather(city) {
4
-  const url = `https://restapi.amap.com/v3/weather/weatherInfo?key=${SERVER_KEY}&city=${city}&extensions=all`;
5
-
6
-  return fetch(url)
3
+export default function getWeather() {
4
+  // 先获取当前位置
5
+  return fetch(`https://restapi.amap.com/v3/ip?key=${SERVER_KEY}`)
7
     .then((res) => res.json())
6
     .then((res) => res.json())
8
     .then((res) => {
7
     .then((res) => {
9
-      if (res.info === 'OK') {
10
-        return res.forecasts;
11
-      } else {
12
-        return Promise.reject(res.info);
8
+      if (res.adcode) {
9
+        const url = `https://restapi.amap.com/v3/weather/weatherInfo?key=${SERVER_KEY}&city=${res.adcode}&extensions=all`;
10
+
11
+        return fetch(url)
12
+          .then((res) => res.json())
13
+          .then((res) => {
14
+            if (res.info === 'OK') {
15
+              return res.forecasts;
16
+            } else {
17
+              return Promise.reject(res.info);
18
+            }
19
+          })
20
+          .catch((err) => {
21
+            console.log(err.message);
22
+          });
13
       }
23
       }
14
-    })
15
-    .catch((err) => {
16
-      console.log(err.message);
17
     });
24
     });
18
 }
25
 }

+ 3
- 3
src/pages/MonitoringScreen/index.jsx Ver arquivo

128
   ]);
128
   ]);
129
 
129
 
130
   useEffect(() => {
130
   useEffect(() => {
131
-    getWeather('邓州市')
131
+    getWeather()
132
       .then((res) => {
132
       .then((res) => {
133
         if (res && res.length) {
133
         if (res && res.length) {
134
-          const { casts } = res[0];
134
+          const { casts, city } = res[0];
135
           const { dayweather, nighttemp, daytemp } = casts[0];
135
           const { dayweather, nighttemp, daytemp } = casts[0];
136
           const [min, max] =
136
           const [min, max] =
137
             parseInt(nighttemp) > parseInt(daytemp) ? [daytemp, nighttemp] : [nighttemp, daytemp];
137
             parseInt(nighttemp) > parseInt(daytemp) ? [daytemp, nighttemp] : [nighttemp, daytemp];
138
-          setWeather(`${dayweather} ${min}-${max} °C`);
138
+          setWeather(`${city} ${dayweather} ${min}-${max} °C`);
139
         } else {
139
         } else {
140
           setWeather('暂无天气信息');
140
           setWeather('暂无天气信息');
141
         }
141
         }