张延森 3 лет назад
Родитель
Сommit
84d8f6d3e3
2 измененных файлов: 21 добавлений и 14 удалений
  1. 18
    11
      src/components/AMap/weather.js
  2. 3
    3
      src/pages/MonitoringScreen/index.jsx

+ 18
- 11
src/components/AMap/weather.js Просмотреть файл

@@ -1,18 +1,25 @@
1 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 6
     .then((res) => res.json())
8 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 Просмотреть файл

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