移动应用开辟了定位与导航功能,而这个涉及到计算地球上两点(经纬度)之间的距离,比如在微信小程序上求当前位置与预定位置之间的距离的计算。下面给出微信小程序中代码如何计算,如下:
Page({
data: {
targetLatitude: xxx,
targetLongitude: xxx,
},
onLoad: function (options) {
getCurrentLocation();
},
getCurrentLocation: function() {
const { targetLatitude, targetLongitude } = this.data;
const that = this;
wx.getLocation({
type: 'wgs84',
success(res) {
const currentLatitude = res.latitude;
const currentLongitude = res.longitude;
const distance = that.calDistance(latitude, longitude, targetLatitude, targetLongitude);
that.setData({
latitude,
longitude,
distance
});
}
});
},
calDistance: function (latitude1, longitude1, latitude2, longitude2) {
var iLatitude1 = latitude1 * Math.PI / 180.0;
var iLatitude2 = latitude2 * Math.PI / 180.0;
var xLatitude = iLatitude1 - iLatitude2;
var xLongitude = longitude1 * Math.PI / 180.0 - longitude2 * Math.PI / 180.0;
//求地球上两点之间的距离
var iDistance = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(xLatitude / 2), 2) + Math.cos(iLatitude1) * Math.cos(iLatitude2) * Math.pow(Math.sin(xLongitude / 2), 2)));
//地球半径
iDistance = iDistance * 6378.137;
iDistance = Math.round(iDistance * 10000) / 10000;
iDistance = iDistance.toFixed(2);
return iDistance;
},
})在上述代码中,假定目标经纬度点是(targetLatitude, targetLongitude), 后通过wx.getLocation获取当前的经纬度点(currentLatitude, currentLongitude),最后通过calDistance计算出这两点之间的距离。