微信小程序中使用 wx.getLocation获取当前详细位置并计算距离

前言

wx.getLocation只能够获取经纬度,不能够拿到详细地址;如果你的项目刚好也使用腾讯地图的api,那么可以通过腾讯地图的逆解析就能拿到详细地址了;

1,wx.getLocation()

先介绍一下wx.getLocation()方法的使用; 此方法可以获取当前的经纬度和速度、高度;官网链接

想要使用这个方法,先需要在小程序后台 《开发管理-接口设置》中开通接口权限,需要审核通过才能使用:

在这里插入图片描述

注意:自 2022 年 7 月 14 日后发布的小程序,若使用该接口,需要在 app.json 中进行声明,否则将无法正常使用该接口;如下:
app.json

 "requiredPrivateInfos": ["getLocation", "chooseLocation", "chooseAddress"],

开始使用:

wx.getLocation({
    
    
    type: 'gcj02', // 比较精确
    success: (res) => {
    
    
     console.log(res);
    }
  })

那么此接口只能获取到当前的经纬度 并不是当前的省市区街道等地址;下面我们会配合使用腾讯地图的api进行地址的逆解析获取详细地址;

2,获取详细地址

第一步:在腾讯位置服务注册获取key或公司里面已经获取过key: 腾讯地图官方链接

第二步:就是在小程序的《开发管理-域名服务器》中的request合法域名中添加一行:https://apis.map.qq.com

在这里插入图片描述
第三步:在app.json中添加:

  "permission": {
    
    
    "scope.userLocation": {
    
    
      "desc": "你的位置信息将用于小程序位置接口的效果展示"
    }
  }

第四步:我是在onLoad生命周期加载的代码,你可以根据具体情况把下面代码复制到其他相应位置;

先下载jssdk文件解压后放到相应位置

// 引入SDK核心类
let QQMap = require("../../utils/qqmap-wx-jssdk.min"); 
let QQMapSdk;
Page({
    
    
    
/**
 * 页面的初始数据
 */
data: {
    
    
  currentLat:"",
  currentLon:"",
},
})
  	/**
   * 生命周期函数--监听页面加载
   */
  	onLoad(query){
    
    
   		this.getLoaction()
	}
	// 获取位置的方法
	 getLoaction() {
    
    
        // 1.先开始定位
        wx.getLocation({
    
    
          type: 'gcj02', // 比较精确
          success: (res) => {
    
    
            // 2,地址逆解析  根据经纬度获取实际地址
            QQMapSdk.reverseGeocoder({
    
    
              location: {
    
    
                latitude: res.latitude,
                longitude: res.longitude
              },
              success: (data) => {
    
    
                console.log("当前地址信息:", data);
                // 存储 详细地址 和当前获取的经纬度
                let address = data.result.address + data.result.formatted_addresses.recommend;
                this.setData({
    
    
                  currentLoaction: address,
                  currentLat: data.result.location.lat,
                  currentLon: data.result.location.lng
                })
            
              },
              fail: (error) => {
    
    
                console.error("err:", error)
              },
            })
          }
        })
      }

3,计算距离

可以使用 calculateDistance 方法计算两地经纬度之间的距离;

   // 计算两个经纬度的直线距离 https://lbs.qq.com/miniProgram/jsSdk/jsSdkGuide/methodCalculatedistance
     calculateDistanceFun(){
    
    
        QQMapSdk.calculateDistance({
    
    
            mode: 'straight',//直线距离
            // 起点坐标
            from: {
    
    
              latitude: this.data.latlon.lat,
              longitude: this.data.latlon.lon
            },
            // 终点坐标 to是当前位置 注意是一个数组
            to: [{
    
    
              latitude: data.result.location.lat,
              longitude: data.result.location.lng
            }],
            success: (calc) => {
    
    
              // 计算结果输出为米
              let distance = calc.result.elements[0].distance;
              console.log("计算距离为:", distance + '米');
            },
            // 失败的情况
            fail: (error) => {
    
    
              console.error('error:', error);
            },
          })
     }

4,报错信息: getLocation:fail 频繁调用会增加电量损耗

如果出现以下报错信息说明:

在这里插入图片描述

我们在调用wx.getLocation()方法的回调里面又直接调用了腾讯地图的reverseGeocoder方法(腾讯地图api也可能也调用了wx.getLocation()方法 导致间隔不够30秒报频繁调用)

解决方法:调用 reverseGeocoder方法时 传入经纬度即可,什么都不传就会报这个错误;

 		qqmapsdk.reverseGeocoder({
    
    
 			//传入当前的经纬度
              location: {
    
    
                latitude: res.latitude,
                longitude: res.longitude
              },
              success: (data) => {
    
    
              },
              fail: (error) => {
    
    
                console.error("err:", error)
              },
            })

5,报错信息: 请求源未被授权

出现这个报错说明 你引用的key值 没有授权你当前电脑的ip地址;

在这里插入图片描述


解决方法:

需要在腾讯地图的后台配置一下你的ip;并把允许在小程序中使用勾选上;
在这里插入图片描述
WebServiceAPI Key配置中的授权IP

猜你喜欢

转载自blog.csdn.net/qq_43886365/article/details/130286822
今日推荐