引入腾讯地图api
import QQMapWX from '../../static/js/qqmap-wx-jssdk.js' //官网下载保存到static文件夹引入
1.定位当前位置
uni.getLocation({
type: 'gcj02',
success: res => {
this.covers[0].latitude = res.latitude;
this.covers[0].longitude = res.longitude;
this.latitude = res.latitude;
this.longitude = res.longitude; // 当前地址的经纬度赋值给view里的map
}
});
2.获取商家地址转换经纬度计算距离
getcompany() {
var _this = this
uni.request({
url: 'api',
method: 'GET',
data: {
page: page,
limit:5
},
success: res => {
this.companyList = res.data.data //获取到商家信息
//取出地址的字段
this.cAddress = res.data.data.map(obj => {
return obj.ccity + obj.caddress
})
//实例化api核心类
let qqmapsdk = new QQMapWX({
key: '密钥'
});
let promiseArr = []
const addressArr = this.cAddress
//把所有商家的地址放到数组里去循环换算成经纬度
for (let i = 0; i < addressArr.length; ++i) {
promiseArr.push(new Promise((resolve) => {
qqmapsdk.geocoder({
address: addressArr[i],
success(res) {
resolve({
latitude: res.result.location.lat,
longitude: res.result.location.lng
})
}
})
}))
}
Promise.all(promiseArr)
.then(res => {
//腾讯地图api里计算距离的方法
qqmapsdk.calculateDistance({
from: "", //为空默认当前位置
to: res, //商家的位置
success(res) {
var addressKm = []
for (var i = 0; i < res.result.elements.length; i++) {
//米转换成km
res.result.elements[i].distance = res.result.elements[i].distance / 1000
res.result.elements[i].distance = Math.round(res.result.elements[i].distance)
addressKm.push(res.result.elements[i].distance); //将返回数据存入数组,
}
for (var j = 0; j < _this.companyList.length; j++) {
_this.companyList[j].distance = res.result.elements[j].distance //往渲染的商家地址数据里添加新的字段 - 距离
}
}
})
})
},
fail: () => {},
complete: () => {}
});
},
3.导航
//点击某个商家跳转导航
companyAddress(item) {
var self = this
uni.request({
url: ‘api’,
method: 'GET',
data: {},
success: res => {
//获取所点击商家的地址 转换经纬度
this.city = res.data.ccity
this.address = res.data.caddress
let qqmapsdk = new QQMapWX({
key: '密钥'
});
qqmapsdk.geocoder({
address: self.city + self.address,
success(res) {
//uni.openLocation查看位置
uni.openLocation({
latitude: res.result.location.lat,
longitude: res.result.location.lng,
success: function() {
console.log('success');
}
});
},
fail: function(error) {
console.error(error);
},
});
},
fail: () => {},
complete: () => {}
});
}
效果图