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>
相关推荐
速盾cdn29 分钟前
速盾:网页游戏部署高防服务器有什么优势?
服务器·前端·web安全
小白求学130 分钟前
CSS浮动
前端·css·css3
什么鬼昵称31 分钟前
Pikachu-csrf-CSRF(POST)
前端·csrf
golitter.1 小时前
Vue组件库Element-ui
前端·vue.js·ui
儒雅的烤地瓜1 小时前
JS | JS中判断数组的6种方法,你知道几个?
javascript·instanceof·判断数组·数组方法·isarray·isprototypeof
道爷我悟了1 小时前
Vue入门-指令学习-v-on
javascript·vue.js·学习
27669582921 小时前
京东e卡滑块 分析
java·javascript·python·node.js·go·滑块·京东
golitter.1 小时前
Ajax和axios简单用法
前端·ajax·okhttp
PleaSure乐事1 小时前
【Node.js】内置模块FileSystem的保姆级入门讲解
javascript·node.js·es6·filesystem
雷特IT2 小时前
Uncaught TypeError: 0 is not a function的解决方法
前端·javascript