计算两点之间距离
一、 在小程序中获取两点之间的距离 要首先明确哪俩点的位置
在页面的js中先写出 经纬度 以此来计算
这里是计算当前位置和目的地的位置
二 、通过函数来计算俩点之间的距离 需要写在js里面写方法
直接复制即可
// 计算距离函数
Rad(d) {
//根据经纬度判断距离
return d * Math.PI / 180.0;
},
getDistance(lat1, lng1, lat2, lng2) {
// 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;
s = s.toFixed(1) + 'km' //保留两位小数
console.log('经纬度计算的距离:' + s)
return s
},
三 、 页面显示 :需要获取当前位置的经纬度 并且在将计算的距离返回到自己所需要的数组里
1.要在onload 里面写 wx.getLocation来获取当前位置
2.调用外层写好的getDistance函数来计算 得到的当前位置经纬度 和在data定义的目的地经纬度 俩点的距离
将计算得到的距离放到一个常量里面
3.定义一个新数组 使用map方法 映射 将原数组被映射成对应的新数组
① this.data.productAll – productAll是原数组也是需要将数据映射到的数组
②distance --原数组需要距离的字段 将新数组赋值给原数组字段
4.用this.setData进行数据更新
onLoad: function (options) {
//获取当前位置
wx.getLocation({
type: 'gcj02',
success: (res) => {
console.log("当前位置:", res)
// this.setData({
// latitude: res.latitude,
// longitude: res.longitude
// })
//调用外层写好函数this函数 当前系统经纬度 获取定义的目的地经纬度
const distance_new = this.getDistance(res.latitude, res.longitude,this.data.latitude2,this.data.longitude2);
console.log(distance_new);
//map方法: 映射 将原数组被映射成对应的新数组
let distances = this.data.productAll.map((item)=>{
for(let i = 0;i<item.length;i++){//循环每个页面里面的子项
console.log(i);
item[i].distance = distance_new; //新数组
console.log(item[i].distance)
}
return item;//获得的值在返回 返回到新的数组distances里面
})
this.setData({
productAll:distances //将获取到的新的数组映射返回到productAll中
})
}
})
},