前端用最简单的方式利用高德解决当前位置实时天气

30 阅读1分钟

1.获取高德key 根据图片进入高德控制台创建应用

image.png

2给刚才创建的应用添加key, 操作如下图

image.png

3得到的高德key填入相应位置

getWeatherFn = async () => {
        try {
          const res = await fetch('https://restapi.amap.com/v3/ip?key=高德key')
          const position = await res.json() // 如果数据是JSON格式
          const response = await fetch(`https://restapi.amap.com/v3/weather/weatherInfo?key=高德key&extensions=base&city=${position.city}`)
          const weather = await response.json()
          console.log('当前位置', position)
          console.log('当前天气', weather)
        } catch (error) {
          console.error(error)
        }
      }
      
getWeatherFn()

以上代码输出结果 就可以得到当前位置的市级实时天气