-
用到了小程序自带的属性方法wx.chooseLocation() 【这方法是用来唤醒腾讯地图】
-
wx.getLocation() 【这个方法获取当前的位置】
- 根据项目的需要有两种写法
- 第一种,使用点事件
moveToLocation(){
const that = this //这个是为了防止this指向的丢失
wx.chooseLocation({//吊起腾讯地图的方法
success:function(res){ //成功的时候执行的方法
that.setData({
mapName:res.name // 在点击确定的时候 将获取的地址展示出来
})
const {latitude,longitude} =res //利用es6的解构赋值
console.log(latitude,longitude);
that.data.latitude2= latitude
that.data.longitude2=longitude// 将经度纬度赋值给相应的属性
wx.getLocation({ // 这个是获取当前位置的方法
type: 'gcj02',
success: (res) => {
console.log(res);
// console.log("当前位置:", res)
//带哦用一个自定义的函数进行传参
const distance_new = that.getLocation(res.latitude, res.longitude,
that.data.latitude2,that.data.longitude2);
console.log(distance_new);
}
})
},
})
},
- 第二就是写在onLoad: function (){}方法中 【】
onLoad: function(){
const that = this //这个是为了防止this指向的丢失
wx.chooseLocation({//吊起腾讯地图的方法
success:function(res){ //成功的时候执行的方法
that.setData({
mapName:res.name // 在点击确定的时候 将获取的地址展示出来
})
const {latitude,longitude} =res //利用es6的解构赋值
console.log(latitude,longitude);
that.data.latitude2= latitude
that.data.longitude2=longitude// 将经度纬度赋值给相应的属性
wx.getLocation({ // 这个是获取当前位置的方法
type: 'gcj02',
success: (res) => {
console.log(res);
// console.log("当前位置:", res)
//带哦用一个自定义的函数进行传参
const distance_new = that.getLocation(res.latitude, res.longitude,
that.data.latitude2,that.data.longitude2);
console.log(distance_new);
}
})
},
})
},
2.一下是计算的方法
// 计算距离函数
Rad(d) {
// console.log(d,'这里是D');
//根据经纬度判断距离
return d * Math.PI / 180.0;
},
getLocation(weidu1, jingdu1, weidu2, jingdu2) {
console.log(weidu1, jingdu1 ,'我是当前定位', weidu2, jingdu2,'我是目标的');
// weidu1当前的纬度
// jingdu1当前的经度
// weidu2目标的纬度
// jingdu2目标的经度
var radweidu1 = this.Rad(weidu1);
var radweidu2 = this.Rad(weidu2);
var a = radweidu1 - radweidu2;
// console.log(a);
var b = this.Rad(jingdu1) - this.Rad(jingdu2);
// console.log(b);
var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radweidu1) * Math.cos(radweidu2) * Math.pow(Math.sin(b / 2), 2)));
// console.log(s);
s = s * 6378.137;
s = Math.round(s * 10000) / 10000;
s = s.toFixed(1) + 'km' //保留两位小数
// console.log('经纬度计算的距离:' + s)
return s
},
3.成品入下