计算两个坐标之间的距离的功能 [英] Function to calculate distance between two coordinates

查看:138
本文介绍了计算两个坐标之间的距离的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在使用下面的功能,但无法正常使用。根据Google地图,或必应



顺便说一句,Google Maps API在其 google.maps.geometry.spherical 命名空间(查找 computeDistanceBetween )。这可能比自己动手做得更好(对于初学者而言,它使用更精确的地球半径值)。



对于我们中间的挑剔者,当我说直线距离,我指的是球体上的直线,当然,它实际上是一条曲线(即大圆距离)。


I'm currently using the function below and it doesn't work properly. According to Google Maps, the distance between these coordinates (from 59.3293371,13.4877472 to 59.3225525,13.4619422) are 2.2 kilometres while the function returns 1.6 kilometres. How can I make this function return the correct 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆