首先在页面中定义好自身返回的经纬度数据,然后储存起来
// 存放当前经纬度数据
data(){
latitude: 0, // 纬度
longitude: 0, // 经度
distance: 0, // 距离
}
uni.getLocation({
success:(res) => {
console.log(res)
this.latitude = res.latitude // 将纬度存起来
this.longitude = res.longitude // 将经度存起来
}
})
然后获取到后端返回的数据,把返回的数据进行计算
这是封装好的公式函数,调用的时候传入自身经纬度和需要计算的经纬度
// 计算距离
getDistance(la1, lo1, la2, lo2) { // 当前的纬度,当前的经度,接口拿到的纬度,接口拿到的经度
let La1 = la1 * Math.PI / 180.0;
let La2 = la2 * Math.PI / 180.0;
let La3 = La1 - La2;
let Lb3 = lo1 * Math.PI / 180.0 - lo2 * Math.PI / 180.0;
let distance = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)));
distance = distance * 6378.137;
distance = Math.round(distance * 10000) / 10000;
return distance;
},
调用封装函数
// 当前的纬度,当前的经度,接口拿到的纬度,接口拿到的经度
this.distance = this.$t.getDistance(this.latitude,this.longitude, lat, lng)
//进行取整
this.distance = Number(this.distance).toFixed(2)
本文介绍了在uni-app中如何利用后端返回的经纬度数据与自身位置经纬度来计算两者之间的距离。首先存储自身经纬度,接着获取并处理后端返回的经纬度,然后使用封装的计算公式函数进行距离计算。
3016

被折叠的 条评论
为什么被折叠?



