计算两个经纬度的实际距离
使用场景
本例介绍如何在宜搭中如何通过两个经纬度计算实际距离。
实现功能
创建页面




计算距离函数

// 根据经纬度计算距离,参数分别为起点的纬度,经度;终的纬度,经度
export function getDistance(startLatitude, startLongitude, endLatitude, endLongitude) {
const radLat1 = this.rad(startLatitude);
const radLat2 = this.rad(endLatitude);
const a = radLat1 - radLat2;
const b = this.rad(startLongitude) - this.rad(endLongitude);
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; // EARTH_RADIUS;
s = Math.round(s * 10000) / 10000; // 输出为公里
return s;
}
// 处理经纬度
export function rad(d) {
return (d * Math.PI) / 180.0; /* 经纬度转换成三角函数中度分表形式。 */
}
计算按钮绑定事件

// 计算距离
export function onGetDistance() {
this.$('locationField_lgosgdmj').validate(); // 起点校验
this.$('locationField_lgosgdmk').validate(); // 终点校验
const start = this.$('locationField_lgosgdmj').getValue(); // 起点
const end = this.$('locationField_lgosgdmk').getValue(); // 终点
if (!start || !end) {
return;
};
const startLatitude = start.latitude; // 起点纬度
const startLongitude = start.longitude; // 起点经度
const endLatitude = end.latitude; // 终点纬度
const endLongitude = end.longitude; // 终点经度
this.$('numberField_lgosgdmo').setValue(this.getDistance(startLatitude, startLongitude, endLatitude, endLongitude));
}
实现效果

在线试玩
本文档对您是否有帮助?