Vue使用高德地图定位到当前位置,并显示天气信息

首先得去高德控制台申请两个 key,一个天气key和一个定位key

获取天气信息的函数:

复制代码
const getWeather = function (city) {
  // 使用 fetch 发送请求获取天气信息
  fetch(`https://restapi.amap.com/v3/weather/weatherInfo?city=${city}&key=eefd36557b0250d19d243aea0f62d499`)
    .then((response) => response.json())
    .then((data) => {
      const { lives } = data;
      // 更新响应式数据
      weather.city = lives[0].city;
      weather.weather = lives[0].weather;
      weather.temperature = lives[0].temperature;
      weather.winddirection = lives[0].winddirection;
      weather.windpower = lives[0].windpower;
      weather.reporttime = lives[0].reporttime;
    });
};

使用Geolocation API获取当前位置:

复制代码
onMounted(() => {
  let latitude = 0;
  let longitude = 0;

  if ("geolocation" in navigator) {
    navigator.geolocation.getCurrentPosition(
      function (position) {
        latitude = position.coords.latitude;
        longitude = position.coords.longitude;
      },
      function (error) {
        console.error("获取位置失败:", error.message);
      }
    );
  } else {
    console.error("浏览器不支持Geolocation");
  }
});

加载高德地图API并在地图上显示标记和天气信息:

复制代码
AMapLoader.load({
  // 加载高德地图API
}).then((AMap) => {
  // 在地图上显示当前位置的标记
  const marker = new AMap.Marker({
    position: new AMap.LngLat(longitude, latitude),
    title: "当前位置",
  });

  // 其他地图初始化和相关操作

  // 在地图上显示信息窗体
  watch(weather, (newVal, oldVal) => {
    // 创建信息窗体
    var content = [
      "<div><b>天气</b>",
      `城市:${weather.city}`,
      // 其他天气信息...
      "</div>",
    ];

    var infoWindow = new AMap.InfoWindow({
      content: content.join("<br>"),
      anchor: "top-left",
    });

    infoWindow.open(map, [longitude, latitude]);
  });

  // 添加标记到地图
  map.add(marker);

  // 标记点击事件
  marker.on('click', function (e) {
    // 打开信息窗体
    infoWindow.open(map, [longitude, latitude]);
  });
}).catch(e => {
  console.error(e);
});

全部代码

复制代码
<template>
  <div id="container">
  </div>
  <!--  -->
</template>
<script setup lang="ts">
import {onMounted, reactive, ref, watch} from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import {computed} from "vue-demi";

// 如果是在 ts 的项目中,这一步会有类型错误,解决方案请移步 2.1.1
window._AMapSecurityConfig = {
  securityJsCode: 'd6a5157a0b06c55bcee22c7b69a4uu2c5a'// 你的安全密钥
};
// 定义当前经纬度
/** 初始化地图函数 */
// IP定位获取当前城市信息
const weather = reactive({
  city: '',
  weather: '',
  temperature: '',
  winddirection: '',
  windpower: '',
  reporttime: ''
})
const weatheritem = computed(() => {
  // 回调函数必须return,结果就是计算的结果
  // 如果计算属性依赖的数据发生变化,那么会重新计算
  return weather
})


const getWeather = function (city) {
  fetch(
      `https://restapi.amap.com/v3/weather/weatherInfo?city=${city}&key=eefd36557b0250duu19d243aea0f62d499` //天气key
  )
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        const {lives} = data
        console.log(lives[0])
        weather.city = lives[0].city
        weather.weather = lives[0].weather
        weather.temperature = lives[0].temperature
        weather.winddirection = lives[0].winddirection
        weather.windpower = lives[0].windpower
        weather.reporttime = lives[0].reporttime
      });
}
onMounted(() => {
  let latitude = 0;
  let longitude = 0;
  // 获取当前位置的经纬度
// 检查浏览器是否支持Geolocation
  if ("geolocation" in navigator) {
    // 获取当前位置
    navigator.geolocation.getCurrentPosition(
        function (position) {
          // 获取经纬度
          latitude = position.coords.latitude;
          longitude = position.coords.longitude;
          // 在这里使用经纬度数据进行其他操作
          console.log("纬度:" + latitude + ", 经度:" + longitude);
        },
        function (error) {
          // 处理获取位置失败的情况
          console.error("获取位置失败:", error.message);
        }
    );
  } else {
    // 浏览器不支持Geolocation
    console.error("浏览器不支持Geolocation");
  }
  // AMapLoader => 加载器
  // 资源加载完成后就会触发 then
  AMapLoader.load({
    "key": "34b7b1e632fcf24d30be5cuu5825f8043d", // 申请好的Web端开发者定位Key,首次调用 load 时必填
    "version": "2.0",   // 指定要加载的 JS API 的版本,缺省时默认为 1.4.15
    "plugins": [],           // 需要使用的的插件列表,如比例尺'AMap.Scale'等
  }).then((AMap) => {
    AMap.plugin('AMap.CitySearch', function () {
      var citySearch = new AMap.CitySearch()
      citySearch.getLocalCity(function (status, result) {
        if (status === 'complete' && result.info === 'OK') {
          // 查询成功,result即为当前所在城市信息
          console.log(result.city)
          getWeather(result.city)
        }
      })
    })
    const marker = new AMap.Marker({
      position: new AMap.LngLat(longitude, latitude), //经纬度对象,也可以是经纬度构成的一维数组[116.39, 39.9]
      title: "当前位置",
    });


//打开信息窗体
    // 初始化地图
    const map = new AMap.Map('container', {
      center: [longitude, latitude], //地图中心点
      zoom: 10
      // 配置对象 - 配置地图的风格和缩放比例,请移步 2.2
    });
    //获取当前城市信息
    //信息窗体的内容
    watch(weather, (newVal, oldVal) => {
      console.log(newVal, oldVal)
      var content = [
        "<div><b>天气</b>",
        `城市:${weather.city}`,
        `时间:${weather.reporttime}`,
        `天气:${weather.weather}`,
        `温度:${weather.temperature}℃`,
        `风向:${weather.winddirection}`,
        `风速:${weather.windpower}`,
        "</div>",
      ];
//创建 infoWindow 实例
      var infoWindow = new AMap.InfoWindow({
        content: content.join("<br>"), //传入字符串拼接的 DOM 元素
        anchor: "top-left",
      });
      infoWindow.open(map, [longitude, latitude]); //map 为当前地图的实例,map.getCenter() 用于获取地图中心点坐标。
    })
    map.add(
        marker
    )
    marker.on('click', function (e) {
      // 打开信息窗体,显示信息
      console.log(e)
      infoWindow.open(map, [longitude, latitude]);
    });

  }).catch(e => {
    console.log(e);
  });
});

</script>

<style scoped>
#container {
  width: 100vw;
  height: 100vh;
}
</style>
相关推荐
passerby606114 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了14 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅14 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅15 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅15 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment15 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅15 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊15 小时前
jwt介绍
前端
爱敲代码的小鱼15 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax
吹牛不交税16 小时前
admin.net-v2 框架使用笔记-netcore8.0/10.0版
vue.js·.netcore