根据当前经纬度获取位置信息,并根据当前位置获取当前城市天气情况

这个当前位置的天气情况的功能我搞了两天,在此记录一下!

前提:Vue3+TS  

                用的是高德地图的 geocoder  API 和天气  -----  密钥部分自己去注册,很简单的!!

浏览器:Edge浏览器,谷歌不行(经纬度获取不到)

获取当前位置的天气情况步骤:-----(2、3步可以放一起)

1、获取用户位置: 使用 navigator.geolocation.getCurrentPosition 获取用户的经纬度。
2、反地理编码: 使用高德地图的 geocoder API 将经纬度转换为详细地址信息,包括省份、城市、区/县等。
3、获取区/县编码: 从反地理编码结果中提取区/县的编码(adcode)。
4、获取天气数据: 使用高德地图天气 API,将区/县编码作为参数,获取天气数据。

一、获取用户位置:使用navigator.geolocation.getCurrentPosition 获取用户的经纬度

代码实现:(TS代码)

const lng = ref<number>(0);  //经度
const lat = ref<number>(0);    //纬度

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
        (position) => {
          // 成功获取到位置信息
          console.log("纬度:", position.coords.latitude);
          console.log("经度:", position.coords.longitude);
          lat.value = position.coords.latitude;
          lng.value = position.coords.longitude
          // 使用获取到的经纬度进行其他操作
          // ...
        },
        (error) => {
          // 获取位置失败
          console.error("获取地理位置失败:", error);
        },
        {
          // 可选参数,设置获取位置的选项
          enableHighAccuracy: true, // 设置为高精度定位
          timeout: 10000, // 设置超时时间为 5 秒
          maximumAge: 0, // 设置缓存时间为 0,每次都获取最新的位置
        },

    );
  } else {
    // 浏览器不支持地理位置定位
    console.error("浏览器不支持地理位置定位");
  }
}

getLocation(); // 调用函数获取位置信息

二(三)、反地理编码: 使用高德地图的 geocoder API 将经纬度转换为详细地址信息,包括省份、城市、区/县等。

                获取区/县编码: 从反地理编码结果中提取区/县的编码(adcode)。

代码实现:(TS代码)

const apiKey ='你自己的密钥'
const longitude = 118.790804;   //经度
const latitude = 32.027675;   //纬度
const location = `${longitude},${latitude}`;

// 使用高德地图 API 获取经纬度对应的地址信息
async function getLocationByCoordinates(latitude: number, longitude: number): Promise<string> {
  try {
    const response = await fetch(`https://restapi.amap.com/v3/geocode/regeo?key=${apiKey}&location=${location}&poitype=商务写字楼&radius=1000&extensions=base&roadlevel=0`);
    const data = await response.json();
    console.log(data)

    if (data.status === '1') {
      const addressComponent = data.regeocode.addressComponent;
      const citycode = addressComponent.adcode;

      console.log("@@@@@@@@@",citycode)
      
      if (citycode) {
        return citycode;
      } else {
        return '无法获取城市信息';
      }
    } else {
      return '无法获取地址信息';
    }
  } catch (error) {
    console.error('获取地址信息失败', error);
    return '获取地址信息失败';
  }
}

// 示例用法

getLocationByCoordinates(longitude,latitude)
    .then(citycode => console.log(`城市:${citycode}`))
    .catch(error => console.error(error));

四、获取天气数据: 使用高德地图天气 API,将区/县编码作为参数,获取天气数据。

const apiKey ='你自己的密钥'

// 获取天气数据
async function getWeatherData(adcode: string) {
  try {
    const response = await axios.get(`https://restapi.amap.com/v3/weather/weatherInfo?key=${apiKey}&city=${adcode}`);
    const data = response.data;

    if (data.status === '1') {
      // 获取天气数据
      const weatherData = data.lives[0];

      // 打印天气数据
      console.log(`城市:${weatherData.city}`);
      console.log(`天气:${weatherData.weather}`);
      console.log(`温度:${weatherData.temperature}`);
      console.log(`风向:${weatherData.winddirection}`);
      console.log(`风力:${weatherData.windpower}`);

      console.log(weatherData)
      // 返回天气数据
      return weatherData;

    } else {
      return '无法获取天气信息';
    }
  } catch (error) {
    console.error('获取天气信息失败', error);
    return '获取天气信息失败';
  }
}

// 使用 getWeatherData 获取天气数据
getWeatherData(adcode)
  .then((weatherData: WeatherData) => {
    // 打印天气数据
    console.log(`城市:${weatherData.city}`);
    console.log(`天气:${weatherData.weather}`);
    // ... 其他天气数据
  })
  .catch(error => {
    console.error('获取天气信息失败', error);
  });

完整代码:(TS代码)

<script setup name="Test" lang="ts">
import { ref,onMounted } from 'vue'
import axios from 'axios';

const lat = ref<number>(0);
const lng = ref<number>(0);
const apiKey = '你自己的密钥';
const weatherData = ref<any>(null);

// 获取当前位置
function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
        (position) => {
          lat.value = position.coords.latitude;
          lng.value = position.coords.longitude;
          getWeatherByLocation(lat.value, lng.value);
        },
        (error) => {
          console.error('获取地理位置失败:', error);
        },
        {
          enableHighAccuracy: true,
          timeout: 10000,
          maximumAge: 0,
        }
    );
  } else {
    console.error('浏览器不支持地理位置定位');
  }
}

// 获取天气信息
async function getWeatherByLocation(latitude: number, longitude: number) {
  try {
    const location = `${longitude},${latitude}`;
    // 使用高德地图 API 获取经纬度对应的地址信息
    const response = await axios.get(
        `https://restapi.amap.com/v3/geocode/regeo?key=${apiKey}&location=${location}`
    );
    const data = response.data;

    if (data.status === '1') {
      const adcode = data.regeocode.addressComponent.adcode;
      if (adcode) {
        await getWeatherData(adcode);
      } else {
        console.error('无法获取城市信息');
      }
    } else {
      console.error('无法获取地址信息');
    }
  } catch (error) {
    console.error('获取天气信息失败', error);
  }
}

// 获取天气数据
async function getWeatherData(adcode: string) {
  try {
    const response = await axios.get(
        `https://restapi.amap.com/v3/weather/weatherInfo?key=${apiKey}&city=${adcode}`
    );
    const data = response.data;
    console.log("@@@@@@",data)

    if (data.status === '1') {
      // 获取天气数据
      weatherData.value = data.lives[0];
    } else {
      console.error('无法获取天气信息');
    }
  } catch (error) {
    console.error('获取天气信息失败', error);
  }
}


onMounted(() => {
  getLocation(); // 调用函数获取位置信息
});

</script>

展示

<template>
<div style="margin-top: 80px; margin-left: 10px">
   <div v-if="weatherData">
       <p>城市:{{ weatherData.city }}</p>
       <p>天气:{{ weatherData.weather }}</p>
       <p>温度:{{ weatherData.temperature }}℃</p>
       <p>风向:{{ weatherData.winddirection }}</p>
       <p>风力:{{ weatherData.windpower }}级</p>
   </div>
   <div v-else>
       <p>正在获取天气信息...</p>
   </div>
</div>
</template>

运行结果:

对你有帮助的话就点个赞吧!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

红豆豆by

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值