我目前正在使用下面的功能,它不能正常工作。根据谷歌Maps,这些坐标之间的距离(从59.3293371,13.4877472到59.3225525,13.4619422)是2.2公里,而函数返回1.6公里。我怎样才能使这个函数返回正确的距离?
function getDistanceFromLatLonInKm(lat1, lon1, lat2, lon2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1); // deg2rad below
var dLon = deg2rad(lon2-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}
function deg2rad(deg) {
return deg * (Math.PI/180)
}
jsFiddle: http://jsfiddle.net/edgren/gAHJB/
我在typescript和ES6中实现了这个算法
export type Coordinate = {
lat: number;
lon: number;
};
求两点之间的距离:
function getDistanceBetweenTwoPoints(cord1: Coordinate, cord2: Coordinate) {
if (cord1.lat == cord2.lat && cord1.lon == cord2.lon) {
return 0;
}
const radlat1 = (Math.PI * cord1.lat) / 180;
const radlat2 = (Math.PI * cord2.lat) / 180;
const theta = cord1.lon - cord2.lon;
const radtheta = (Math.PI * theta) / 180;
let dist =
Math.sin(radlat1) * Math.sin(radlat2) +
Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
if (dist > 1) {
dist = 1;
}
dist = Math.acos(dist);
dist = (dist * 180) / Math.PI;
dist = dist * 60 * 1.1515;
dist = dist * 1.609344; //convert miles to km
return dist;
}
获取坐标数组之间的距离
export function getTotalDistance(coordinates: Coordinate[]) {
coordinates = coordinates.filter((cord) => {
if (cord.lat && cord.lon) {
return true;
}
});
let totalDistance = 0;
if (!coordinates) {
return 0;
}
if (coordinates.length < 2) {
return 0;
}
for (let i = 0; i < coordinates.length - 2; i++) {
if (
!coordinates[i].lon ||
!coordinates[i].lat ||
!coordinates[i + 1].lon ||
!coordinates[i + 1].lat
) {
totalDistance = totalDistance;
}
totalDistance =
totalDistance +
getDistanceBetweenTwoPoints(coordinates[i], coordinates[i + 1]);
}
return totalDistance.toFixed(2);
}
我以前写过一个类似的方程-测试了它,也得到了1.6 km。
你的谷歌地图显示了驾驶距离。
你的函数是按照直线距离计算的。
alert(calcCrow(59.3293371,13.4877472,59.3225525,13.4619422).toFixed(1));
//This function takes in latitude and longitude of two location and returns the distance between them as the crow flies (in km)
function calcCrow(lat1, lon1, lat2, lon2)
{
var R = 6371; // km
var dLat = toRad(lat2-lat1);
var dLon = toRad(lon2-lon1);
var lat1 = toRad(lat1);
var lat2 = toRad(lat2);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return d;
}
// Converts numeric degrees to radians
function toRad(Value)
{
return Value * Math.PI / 180;
}