uniapp定位距离
uniapp获取定位距离的方法
在uniapp中计算两个坐标点之间的距离,可以通过以下步骤实现:
获取用户当前位置
使用uniapp的uni.getLocationAPI获取当前设备的经纬度坐标:
uni.getLocation({
type: 'wgs84',
success: function(res) {
console.log('当前位置纬度:' + res.latitude);
console.log('当前位置经度:' + res.longitude);
}
});
计算两点间距离 使用Haversine公式计算两个坐标点之间的直线距离(单位:米):
function getDistance(lat1, lng1, lat2, lng2) {
const radLat1 = lat1 * Math.PI / 180.0;
const radLat2 = lat2 * Math.PI / 180.0;
const a = radLat1 - radLat2;
const b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
let 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) / 10; // 转为米
return s;
}
实际应用示例 计算当前位置到目标位置的距离:
// 假设目标位置坐标
const targetLat = 39.9042;
const targetLng = 116.4074;
uni.getLocation({
type: 'wgs84',
success: function(res) {
const distance = getDistance(res.latitude, res.longitude, targetLat, targetLng);
console.log('距离目标位置:' + distance + '米');
}
});
注意事项
需要在小程序或App的manifest.json中配置位置权限:
{
"permission": {
"scope.userLocation": {
"desc": "需要获取您的位置信息"
}
}
}
对于H5端,需要使用支持HTTPS的环境,部分浏览器可能会限制定位功能。计算结果为直线距离,实际路径距离可能更长。







