vue2 h5用微信打开高德地图获取当前位置和计算距离

需求:使用微信浏览器获取用户定位,并使用高德地图获取当前地址,并计算两点之间距离

1.先安装微信sdk

npm i weixin-js-sdk -S

在需要的页面引用:import wx from "weixin-js-sdk";

2. 获取timestamp和nonceStr,并始化微信JS-SDK配置

具体文档网页授权 | 微信开放文档

接口调用说明:概述 | 微信开放文档

 async getWxConfigConfig() {
      try {
        var url = window.location.href.split("#")[0];
        let axiosUrl = "接口地址";
        const data = {
          url: url,
        };
        const { data: res } = await axios.post(
          `${axiosUrl}`,
          qs.stringify(data)
        );
        const wxconfig = {
          appId: res.data.appid,
          timestamp: res.data.timestamp,
          nonceStr: res.data.nonceStr,
          signature: res.data.signature,
        };
        wx.config({
          debug: false,
          appId: wxconfig.appId,
          timestamp: wxconfig.timestamp,
          nonceStr: wxconfig.nonceStr,
          signature: wxconfig.signature,
          jsApiList: [
            "updateAppMessageShareData",
            "updateTimelineShareData",
            "checkJsApi",
            "openLocation",
            "getLocation",
          ],
          openTagList: ["wx-open-subscribe"],
        });
        wx.ready(() => {
          //获取用户当前位置
          wx.getLocation({
            type: "wgs84",
            success: (res) => {
              const { longitude, latitude } = res;
              this.userLocation = { longitude, latitude };
              this.getUserProvince();
            },
            cancel: () => {
              console.log("用户拒绝授权获取地理位置");
            },
            fail: (error) => {
              console.error("获取用户定位失败", error);
            },
          });
        });
      } catch (error) {
        console.error("微信配置失败", error);
      }
    }, 

3.根据经纬度用高德获取当前所在城市地址(首先先申请高德Key)

 async getUserProvince() {
      try {
        if (!this.userLocation) {
          console.error("用户位置不可用");
          return;
        }
        const { longitude, latitude } = this.userLocation;
        const amapApiKey = "高德API Key";
        const mapurl = `https://restapi.amap.com/v3/geocode/regeo?key=${amapApiKey}&location=${longitude},${latitude}&output=JSON&batch=false&roadlevel=0`;
        const response = await axios.get(mapurl);
        var rcd = response.data.regeocode;
        this.addr = rcd.addressComponent.district;
        console.error("找不到当前位置");
      } catch (error) {
        console.error("获取当前位置失败", error);
      }
    },

4.计算两点之间距离

 getDistance(item) {
      if (!this.userLocation) {
        return "计算中...";
      }
      // 将纬度和经度转换为地图。LngLat对象
      const point1 = new AMap.LngLat(
        this.userLocation.longitude,
        this.userLocation.latitude
      );
      const point2 = new AMap.LngLat(item.longitude, item.latitude);
      // 以米为单位计算距离
      const distance = AMap.GeometryUtil.distance(point1, point2);
      // 将距离转换为公里,四舍五入到小数点后一位
      const distanceInKm = Math.round(distance / 100) / 10;
      return `${distanceInKm} km`;
    },

5.打开地图

openMap() {
      wx.openLocation({
        latitude: parseFloat(latitude), // 纬度,浮点数,范围为90 ~ -90
        longitude: parseFloat(longitude), // 经度,浮点数,范围为180 ~ -180。
        name: title,
        address: site, // 地址详情说明
        scale: 15,
      });
    },

  • 7
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue2中,可以使用高德地图API来获取当前定位。首先,需要引入高德地图的SDK,并在Vue组件中使用AMap.Geolocation来获取当前位置的经纬度信息。以下是一个示例代码: 首先,在utils文件夹中创建一个名为getLocation.js的文件,用于封装获取经纬度的公用方法。该方法使用了Promise来确保在获取到经纬度信息后再进行后续操作。具体代码如下: ```javascript function loadSDK() { if (window.AMap) return; return new Promise((resolve, reject) => { const script = document.createElement('script'); script.src = 'http://webapi.amap.com/maps?v=1.4.6&key=*****************'; // ***为申请的高德key document.head.appendChild(script); script.onload = resolve; script.onerror = reject; }); } export default async () => { await loadSDK(); return new Promise((resolve) => { AMap.plugin('AMap.Geolocation', () => { const geolocation = new AMap.Geolocation({ enableHighAccuracy: false }); geolocation.getCurrentPosition((status, result) => { const res = status === 'complete' ? result.position : { lat: 39.909187, lng: 116.397451 }; // 默认北京 116.397451、39.909187 console.log('定位结果', res); resolve(res); }); }); }); } ``` 然后,在Vue组件中,可以通过调用上述封装的方法来获取当前定位的经纬度信息。具体代码如下: ```javascript import getLocation from '@/utils/getLocation'; export default { methods: { async getCurrentLocation() { try { const position = await getLocation(); // 在这里可以使用获取到的经纬度信息进行后续操作 console.log('当前定位经纬度', position); } catch (error) { console.error('获取定位失败', error); } }, }, mounted() { this.getCurrentLocation(); }, }; ``` 以上代码中,通过调用`getLocation`方法来获取当前定位的经纬度信息,并在`getCurrentLocation`方法中进行后续操作。在Vue组件的`mounted`钩子函数中调用`getCurrentLocation`方法来获取当前定位信息。 请注意,上述代码中的高德地图SDK的引入地址和申请的key需要根据实际情况进行修改。 #### 引用[.reference_title] - *1* *2* [(2023进阶版)vue+h5 通过高德地图(原生) 获取当前位置定位](https://blog.csdn.net/yangzixiansheng/article/details/131308415)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [vue使用高德地图获取当前经纬度](https://blog.csdn.net/V_AYA_V/article/details/105275063)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值