vue PC项目 使用高德API 获取位置和天气信息

本文介绍了如何在Vue PC项目中结合高德API获取当前位置及天气信息的步骤。首先,你需要在高德地图注册成为开发者并创建web应用获取key和安全秘钥。然后,在项目的index.html中引入相关脚本。接着,在需要获取位置信息的页面中调用citySearch和weather插件来实现定位和天气查询。查询到的天气信息可以存储在本地缓存,以备其他页面使用。最后,文章提供了获取天气信息的代码示例。

问题描述

vue PC项目 使用高德API 获取位置和天气信息


解决方案:

1.在高德地图上申请一个开发者,并且创建一个key 选择web端应用

在这里插入图片描述

2.在vue项目中的index.html中 使用script标签 引入生成的key和秘钥

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <title>你的项目名称</title>
</head>

<body>
  <script type="text/javascript">
    window._AMapSecurityConfig = {
      securityJsCode:'你申请的安全秘钥',
    }
  </script>
  <script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=你申请的key"></script>
  <div id="app"></div>
  <!-- built files will be auto injected -->
</body>

</html>

3.在需要获取位置的页面中定义方法 使用citySearch和weather插件
4.可将获取到的天气信息保存至本地缓存再其他页面拉取渲染,注意要JSON.stringify 转化为JSON字符串,拉取的时候再用JSON.parse将JSON字符串转化为对象

  getLngLatLocation() {
      let that = this;
      AMap.plugin("AMap.CitySearch", function () {
        var citySearch = new AMap.CitySearch();
        citySearch.getLocalCity(function (status, result) {
          if (status === "complete" && result.info === "OK") {
            // 查询成功,result即为当前所在城市信息
            console.log("通过ip获取当前城市:", result);
            AMap.plugin("AMap.Weather", function () {
              //创建天气查询实例
              var weather = new AMap.Weather();
              //执行实时天气信息查询
              weather.getLive(result.city, function (err, data) {
                console.log("天气", data);
                if (data) {
                  that.weather = data.weather;
                  that.temperature = data.temperature;
                  that.city = data.city;
                  let weatherObj = {
                    weather: data.weather,
                    temperature: data.temperature,
                    city: data.city,
                  };
                  localStorage.setItem(
                    "WEATHER_INFO",
                    JSON.stringify(weatherObj)
                  );
                }else{
                  console.log(err);
                }
              });
            });
          }
        });
      });
    },
使用 Vue3 开发 PC 应用时,获取用户的地理位置信息可以通过浏览器原生的 `Geolocation API` 或者结合第三方地图服务(如百度地图、高德地图)实现更复杂的地址解析地理信息获取功能。以下是几种常见方法的详细说明: ### 使用浏览器原生 Geolocation API 浏览器提供的 `navigator.geolocation` 接口可以用于获取用户的经纬度信息,适用于基础定位需求。 ```javascript function getUserLocation() { if (!navigator.geolocation) { console.log("当前浏览器不支持地理位置功能"); return; } navigator.geolocation.getCurrentPosition( (position) => { const latitude = position.coords.latitude; const longitude = position.coords.longitude; const accuracy = position.coords.accuracy; console.log(`纬度: ${latitude}, 经度: ${longitude}, 精确度: ${accuracy} 米`); }, (error) => { switch (error.code) { case error.PERMISSION_DENIED: console.error("用户拒绝了地理位置请求"); break; case error.POSITION_UNAVAILABLE: console.error("位置信息不可用"); break; case error.TIMEOUT: console.error("获取位置信息超时"); break; default: console.error("未知错误"); break; } }, { enableHighAccuracy: true, // 高精度模式 timeout: 10000, // 超时时间(毫秒) maximumAge: 60000, // 缓存有效期(毫秒) } ); } ``` 上述代码实现了基本的地理位置获取,并对可能发生的错误进行了分类处理。 ### 使用百度地图 API 实现逆地址解析 若需要将经纬度转换为具体的省市区街道等信息,可使用百度地图的 `Geolocation` `Geocoder` 接口进行逆地址解析。 首先,在项目中引入百度地图 SDK: ```html <script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=你的AK密钥"></script> ``` 然后在 Vue3 的组件中调用相关 API: ```javascript import { onMounted } from 'vue'; export default { setup() { const getBaiduLocation = () => { const geolocation = new BMap.Geolocation(); geolocation.getCurrentPosition((result) => { if (this.getStatus() === BMAP_STATUS_SUCCESS) { const address = result.address; console.log(`国家: ${address.country}, 省: ${address.province}, 城市: ${address.city}`); console.log(`经纬度: ${result.point.lng}, ${result.point.lat}`); } else { console.error("定位失败,请检查网络或权限设置"); } }, { provider: "baidu" }); }; onMounted(() => { getBaiduLocation(); }); return {}; } }; ``` 通过百度地图 API 可以直接获取到城市名称、街道等结构化地址数据[^2]。 ### 使用 Promise 封装方式提升可维护性 为了在 Vue3 中更好地管理异步操作,可以将 `Geolocation API` 封装为一个返回 Promise 的函数,方便在 Composition API使用: ```javascript export const getCurrentPosition = () => { return new Promise((resolve, reject) => { if (!navigator.geolocation) { reject(new Error("浏览器不支持地理位置功能")); } navigator.geolocation.getCurrentPosition( (position) => { resolve({ latitude: position.coords.latitude, longitude: position.coords.longitude, accuracy: position.coords.accuracy, }); }, (error) => { reject(error); }, { enableHighAccuracy: true, timeout: 10000, maximumAge: 60000, } ); }); }; ``` 在 Vue3 的 `setup()` 函数中调用该封装函数: ```javascript import { onMounted } from 'vue'; import { getCurrentPosition } from '@/utils/geolocation'; export default { setup() { const fetchLocation = async () => { try { const location = await getCurrentPosition(); console.log("当前位置:", location); } catch (error) { console.error("获取位置失败:", error.message); } }; onMounted(() => { fetchLocation(); }); return {}; } }; ``` 这种方式提高了代码的可读性复用性,尤其适合大型项目使用。 ### 支持“主动提示”与“静默获取”交互效果 对于用户体验要求较高的场景,可以设计两种交互模式: - **主动提示**:在首次加载页面时弹出提示框,询问用户是否允许获取位置信息。 - **静默获取**:在后台悄悄获取位置信息,不对用户造成干扰,通常用于非关键路径的业务逻辑中。 实现“主动提示”可以在用户点击按钮后触发定位操作,而“静默获取”则可在页面加载时自动执行定位逻辑并隐藏 UI 提示。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值