1. Register Tencent Map
- Application developer key (key): Application key
- Open webserviceAPI service: console -> key management -> settings (key to use this function) -> check webserviceAPI -> save
(small program SDK needs to use some services of webserviceAPI, so the key to use this function needs to have the corresponding Permissions) - Download WeChat Mini Program JavaScriptSDK, WeChat Mini Program JavaScriptSDK v1.2
Two, import SDK
After downloading, unzip, copy the qqmap-wx-jssdk.js file inside to the project.
Then import it on the required page.
import qqmapsdk from '../../sdk/qqmap-wx-jssdk.js'
Three, realize
Create an instance first.
const QQMapWX = new qqmapsdk({
key: '在腾讯位置服务申请的key'
});
Then call uni.getLocation to get the latitude and longitude, and then call the js method to resolve the address.
uni.getLocation({
type: 'wgs84',
geocode: true,
success: (res) => {
console.log("获取经纬度成功");
this.latitude = res.latitude;
this.longitude = res.longitude;
},
fail: () => {
console.log("获取经纬度失败");
},
complete: () => {
// 解析地址
QQMapWX.reverseGeocoder({
location: {
latitude: this.latitude,
longitude: this.longitude
},
success: function(res) {
console.log("解析地址成功");
console.log(res);
// 省
let province = res.result.ad_info.province;
// 市
let city = res.result.ad_info.city;
console.log(province);
console.log(city);
},
fail: function(res) {
uni.showToast({
title: '定位失败',
duration: 2000,
icon: "none"
})
console.log(res);
},
complete: function(res) {
console.log(res);
}
})
}
})
The console output is as follows:
If the positioning fails on the phone, add two lines of code to the specified place in the manifest.json :
"app-plus" : {
/* 模块配置 */
"distribute" : {
/* 应用发布信息 */
"android" : {
/* android打包配置 */
"permissions" : [
"<uses-permission android:name=\"android.permission.ACCESS_COARSE_LOCATION\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\"/>"
]
}
}
}
Get the location permission of the phone.
Welcome guidance! ! !
uni-app obtains Tencent map and calculates the actual distance between two latitudes and longitudes (batch available)
address
https://lbs.qq.com/service/webService/webServiceGuide/webServiceDistance
Code
getDistance() {
uni.request({
url: 'https://apis.map.qq.com/ws/distance/v1/matrix', //仅为示例,并非真实接口地址。
method: 'GET',
data: {
mode: 'walking',
from: '39.071510,117.190091',
to: '39.108951,117.279396',
key: '.....' //获取key
},
success: (res) => {
console.log(res);
let hw = res.data.result.rows[0].elements[0].distance; //拿到距离(米)
if (hw && hw !== -1) {
if (hw < 1000) {
hw = hw + 'm';
}
//转换成公里
else {
hw = (hw / 2 / 500).toFixed(2) + 'km'
}
} else {
hw = "距离太近或请刷新重试"
}
console.log(hw);
}
});
}
test