效果图
先拿到自己的经纬度
data:{
latitude2: 22.490548,
longitude2: 113.921921,
}
onLoad: function (options) {
wx.getLocation({
type: 'gcj02',
success: (res) => {
console.log("当前位置:", res)
const distance_new = this.getDistance(res.latitude, res.longitude, this.data.latitude2, this.data.longitude2);
console.log(distance_new);
this.setData({
distance_new
})
}
})
},
计算
Rad(d) {
return d * Math.PI / 180.0;
},
getDistance(lat1, lng1, lat2, lng2) {
console.log(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;
if (s < 1) {
s = s.toFixed(3) * 1000 + 'm'
console.log('经纬度计算的距离:' + s)
return s
} else {
s = s.toFixed(1) + 'km'
console.log('经纬度计算的距离:' + s)
return s
}
},