如何计算Leaflet-ionic2中两个标记之间的距离?
无法弄清楚,我希望只要我选择一个标记就会有一个算法,它会显示我的位置和标记之间的距离。
谢谢..
答案 0 :(得分:6)
您可以使用此功能查找2个位置之间的距离。
function getDistance(origin, destination) {
// return distance in meters
var lon1 = toRadian(origin[1]),
lat1 = toRadian(origin[0]),
lon2 = toRadian(destination[1]),
lat2 = toRadian(destination[0]);
var deltaLat = lat2 - lat1;
var deltaLon = lon2 - lon1;
var a = Math.pow(Math.sin(deltaLat/2), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(deltaLon/2), 2);
var c = 2 * Math.asin(Math.sqrt(a));
var EARTH_RADIUS = 6371;
return c * EARTH_RADIUS * 1000;
}
function toRadian(degree) {
return degree*Math.PI/180;
}
var distance = getDistance([lat1, lng1], [lat2, lng2])
我们在我们的库time-aware-polyline中使用此函数来编码带有时间戳的lat lng信息。
答案 1 :(得分:4)
Leaflet manual提到distanceTo函数,该函数以米为单位计算距离。
Example窃Google Groups的示例:
function createMarker()
{
var markerFrom = L.circleMarker([28.6100,77.2300], { color: "#F00", radius: 10 });
var markerTo = L.circleMarker([18.9750,72.8258], { color: "#4AFF00", radius: 10 });
var from = markerFrom.getLatLng();
var to = markerTo.getLatLng();
markerFrom.bindPopup('Delhi ' + (from).toString());
markerTo.bindPopup('Mumbai ' + (to).toString());
map.addLayer(markerTo);
map.addLayer(markerFrom);
getDistance(from, to);
}
function getDistance(from, to)
{
var container = document.getElementById('distance');
container.innerHTML = ("New Delhi to Mumbai - " + (from.distanceTo(to)).toFixed(0)/1000) + ' km';
}