前言
该篇文章主要介绍了小程序中如何进行授权地理位置(经纬度信息),再通过经纬度调用插件获取当前的位置信息,以及如何计算两个点的距离
处理步骤
- 引入插件
- 申请开发者秘钥: https://lbs.qq.com/dev/console/application/mine
- 授权获取用户地址信息
- 利用插件获取地址信息
- 根据经纬度计算两点的距离
引入插件
参考文档: https://lbs.qq.com/miniProgram/jsSdk/jsSdkGuide/jsSdkOverview
config = {
plugins: {
routePlan: {
version: '1.0.12',
provider: '' //APPID
}
}
}
相关代码如下
qqmap-wx-jssdk.js 下载地址:mapapi.qq.com/web/minipro…
<template>
<view>
<van-button bindtap="getLocation">
获取地址
</van-button>
</view>
</template>
<script>
import wepy from 'wepy';
var QQMapWX = require('../utils/qqmap-wx-jssdk')
var qqmapsdk;
export default class Demo extends wepy.page {
components = {};
data = {
};
methods = {
/**
* 获取位置信息
*/
getLocation() {
var that = this;
wepy.getLocation({
type: 'wgs84', //默认为 wgs84 返回 gps 坐标,gcj02 返回可用于wepy.openLocation的坐标,
success: res => {
qqmapsdk.reverseGeocoder({
location: {
latitude: res.latitude,
longitude: res.longitude
},
success: function(res2) {
console.log(res2);
// 计算两点距离
let distance = this.getDistance(res.latitude, res.longitude, 39.924091,116.403414);
consloe.log(distance);
},
fail: function() {
},
complete: function() {}
});
}
});
}
};
onLoad() {
// 实例化API核心类
qqmapsdk = new QQMapWX({
key: '' // 申请的开发者秘钥
});
}
/**
* 计算距离
*/
getDistance(lat1, lng1, lat2, lng2) {
// lat1用户的纬度
// lng1用户的经度
// lat2商家的纬度
// lng2商家的经度
var radLat1 = this.Rad(lat1);
var radLat2 = this.Rad(lat2);
var a = radLat1 - radLat2;
var b = this.Rad(lng1) - this.Rad(lng2);
var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
s = s * 6378.137;
s = Math.round(s * 10000) / 10000;
s = s.toFixed(2) + 'km' //保留两位小数
console.log('经纬度计算的距离:' + s)
return s
}
}
</script>