计算两个坐标之间距离的函数显示错误 [英] Function to calculate distance between two coordinates shows wrong
问题描述
我目前正在使用下面的功能,它显示有点错误。根据谷歌地图,或 Bing 获得适当的路线,其中包括距离。
顺便提一下,Google Maps API提供了一种用于球形距离的打包方法,其中 href =https://developers.google.com/maps/documentation/javascript/reference#spherical\"rel =noreferrer> google.maps.geometry.spherical
名称空间(查找 computeDistanceBetween
)。它可能比滚动你自己更好(对于初学者来说,它使用更精确的地球半径值)。
对于我们中的挑剔,当我说直接线距离,我指的是球体上的直线,当然是一条曲线(即大圆距离)。
I'm currently using the function below and it shows a little wrong. According to Google Maps, the distance between these coordinates (from 59.3293371,13.4877472 to 59.3225525,13.4619422) are 2,2 kilometers while the function shows 1,6 kilometers. How can I make Chuck's function show the right distance?
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/
What you're using is called the haversine formula, which calculates the distance between two points on a sphere as the crow flies. The Google Maps link you provided shows the distance as 2.2 km because it's not a straight line.
Wolphram Alpha is a great resource for doing geographic calculations, and also shows a distance of 1.652 km between these two points.
If you're looking for straight-line distance (as the crow files), your function is working correctly. If what you want is driving distance (or biking distance or public transportation distance or walking distance), you'll have to use a mapping API (Google or Bing being the most popular) to get the appropriate route, which will include the distance.
Incidentally, the Google Maps API provides a packaged method for spherical distance, in its google.maps.geometry.spherical
namespace (look for computeDistanceBetween
). It's probably better than rolling your own (for starters, it uses a more precise value for the Earth's radius).
For the picky among us, when I say "straight-line distance", I'm referring to a "straight line on a sphere", which is actually a curved line (i.e. the great-circle distance), of course.
这篇关于计算两个坐标之间距离的函数显示错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!