在距离方面,我无法获得与Google地图相同的精确度?

时间:2015-02-16 13:08:24

标签: javascript google-maps google-maps-api-3

我正在开发一个计算2点之间距离的应用程序。我无法使用Google Maps API。

我在下面的地图中找到了每个标记的坐标。

然后我使用hasrsine公式计算每个点之间的距离。 例如1 - > 2,2 - > 3,3-> 4 ...等到最后一点。 我将这些距离相加以检索路线的总距离。

问题是谷歌地图说它是950-1000米,但我的应用说长度是1150-1200米。我尝试添加更多坐标,删除坐标,但我仍然得到大约200米长的路线。

出于好奇,我计算了起点和终点(2颗绿色星星)之间的距离,这与Google地图距离(准确地说是998米)相匹配。

这是否意味着Google地图计算其距离时不考虑道路/路径等。

这是我的代码:

var coordinates = [
  [1,51.465097,-3.170893,1,0],
  [2,51.465526,-3.170714,0,0],
  [3,51.465853,-3.170526,0,0],
  [4,51.466168,-3.170338,0,0],
  [5,51.466305,-3.170236,0,0],
  [6,51.466534,-3.170157,0,0],
  [7,51.466798,-3.170159,0,0],
  [8,51.467042,-3.170232,0,0],
  [9,51.467506,-3.170580,0,0],
  [10,51.468076,-3.171532,0,0],
  [11,51.468863,-3.172170,0,0],
  [12,51.469284,-3.172841,0,0],
  [13,51.469910,-3.174732,0,0],
  [14,51.470037,-3.174930,0,0],
  [15,51.470350,-3.175091,0,0],
  [16,51.472447,-3.176151,1,0]
];

function distanceBetweenCoordinates() //calculates the distance between each of the coordinates
{
  for (var i=0; i<coordinates.length-1; i++)
  {
      var firstClosestPoint = [0,0,6371];
      var secondClosestPoint = [0,0,6371];
      var lng1 = (coordinates[i][1]);
      var lat1 = (coordinates[i][2]);
      var lng2 = (coordinates[i+1][2]);
      var lat2 = (coordinates[i+1][2]);
      var d = haversine(lat1, lng1, lat2, lng2);
      routeLength = routeLength + d;
 }

return distanceBetweenCoordinatesArray; //returns the array which stores the 2 points and the distance between the 2 points
}

修改

以下是我计算2点之间距离的讨论区:

来源:here

  Number.prototype.toRad = function() //to rad function which is used by the haversine formula
{
  return this * Math.PI / 180;
}

function haversine(lat1, lng1, lat2, lng2) {  //haversine foruma which is used to calculate the distance between 2 coordinates

  lon1 = lng1;
  lon2 = lng2;
  var R = 6371000; // metres
  var a = lat1.toRad();
  var b = lat2.toRad();
  var c = (lat2-lat1).toRad();
  var d = (lon2-lon1).toRad();

  var a = Math.sin(c/2) * Math.sin(c/2) +
          Math.cos(a) * Math.cos(b) *
          Math.sin(d/2) * Math.sin(d/2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

  var d = R * c;
  return d;
}

enter image description here

1 个答案:

答案 0 :(得分:4)

如果我已经正确输入了起点和终点,那么这个实施的半正式公式(我在现实世界中测试过)会产生895米的距离(直线)。

&#13;
&#13;
var lt = 51.472447;
var lt1 = 51.465097;
var ln = -3.176151;
var ln1 = -3.170893;
var dLat = (lt - lt1) * Math.PI / 180;
var dLon = (ln - ln1) * Math.PI / 180;
var a = 0.5 - Math.cos(dLat) / 2 + Math.cos(lt1 * Math.PI / 180) * Math.cos(lt * Math.PI / 180) * (1 - Math.cos(dLon)) / 2;
d = Math.round(6371000 * 2 * Math.asin(Math.sqrt(a)));

$('#distance').html(d);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="distance"></div>
&#13;
&#13;
&#13;