大自然的CV搬运工 2025-09-05 11:53 采纳率: 22.2%
浏览 8
已结题

获取IP地址拿到温度湿度海拔数据

前端如何获取当前位置的IP地址,再通过IP地址调用高德官方API拿到温度湿度海拔

  • 写回答

5条回答 默认 最新

  • 码农阿豪@新空间 新星创作者: 前端开发技术领域 2025-09-05 12:02
    关注
    让阿豪来帮你解答,本回答参考chatgpt3.5编写提供,如果还有疑问可以评论或留言
    1. 前端获取当前位置的IP地址的方法: 前端无法直接获取IP地址,但可以通过调用第三方服务获取用户的IP地址。可以使用免费的IP定位服务,如ip-api.com、ipvigilante.com等。通过发送HTTP请求至这些服务,获取用户的IP地址信息。 示例代码:
    function getIPAddress() {
      fetch('http://ip-api.com/json/')
        .then(response => response.json())
        .then(data => {
          const ipAddress = data.query;
          console.log(ipAddress);
        })
        .catch(error => console.error(error));
    }
    getIPAddress();
    
    1. 使用IP地址调用高德官方API获取温度、湿度、海拔等信息: 高德官方提供了逆地理位置编码接口(geocode.regeo),可以通过IP地址获取当前位置的经纬度,然后再通过天气查询接口(weather)获取该地点的天气信息,包括温度、湿度等。 示例代码:
    function getWeatherByIP(ipAddress) {
      fetch(`https://restapi.amap.com/v3/ip?key=your_amap_api_key&ip=${ipAddress}`)
        .then(response => response.json())
        .then(data => {
          const location = data.rectangle.split(';')[0].split(',');
          const latitude = location[1];
          const longitude = location[0];
          
          fetch(`https://restapi.amap.com/v3/weather/weatherInfo?key=your_amap_api_key&city=${longitude},${latitude}`)
            .then(response => response.json())
            .then(weatherData => {
              const temperature = weatherData.lives[0].temperature;
              const humidity = weatherData.lives[0].humidity;
              const altitude = weatherData.lives[0].altitude;
              console.log(`Temperature: ${temperature}°C, Humidity: ${humidity}%, Altitude: ${altitude}m`);
            })
            .catch(error => console.error(error));
        })
        .catch(error => console.error(error));
    }
    getIPAddress().then(ipAddress => getWeatherByIP(ipAddress));
    

    以上代码中,需要替换掉 your_amap_api_key 为自己的高德官方API密钥。将这两个函数结合起来,可以实现从获取IP地址到调用高德API获取温度、湿度、海拔等信息的操作。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

问题事件

  • 系统已结题 9月17日
  • 已采纳回答 9月9日
  • 创建了问题 9月5日