使用Google地图API计算两点之间的距离?

3

是否可以向Google发送两个经纬度点以计算它们之间的距离?


1
请直接查看@SunnyD的答案,获取Google Maps API V3的解决方案。 - Josh
8个回答

10

如果你想使用v3的谷歌地图API,这是我使用的一个函数:

注意:你必须将&libraries=geometry添加到你的脚本源代码中。

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=geometry"></script>

现在是这个函数:

//calculates distance between two points in km's
function calcDistance(p1, p2){
  return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}

我想要道路距离而不是几何距离? - codepk

7
你需要的是Haversine公式。你不需要使用Google地图来完成这个任务,可以单独计算它。有一个脚本(使用JavaScript编写)可以在这里找到。

3

是的,谷歌可以做到这一点

谷歌 API 文档

以下是一段 JavaScript 代码,用于获取两个点之间的距离(单位为千米)

function initialize() {
      if (GBrowserIsCompatible()) {
          map = new GMap2(document.getElementById("map_canvas"));
          map.setCenter(new GLatLng(52.6345701, -1.1294433), 13);
          map.addControl(new GLargeMapControl());          
          map.addControl(new GMapTypeControl());
          geocoder = new GClientGeocoder();
// NR14 7PZ var loc1 = new GLatLng(52.5773139, 1.3712427); // NR32 1TB var loc2 = new GLatLng(52.4788314, 1.7577444); alert(loc2.distanceFrom(loc1) / 1000); } }

3

还有在C#中的距离计算:

// this returns the distance in miles. for km multiply result: * 1.609344
public static double CalculateDistance(double lat1, double lon1, double lat2, double lon2)
{
    double t = lon1 - lon2;
    double distance = Math.Sin(Degree2Radius(lat1)) * Math.Sin(Degree2Radius(lat2)) + Math.Cos(Degree2Radius(lat1)) * Math.Cos(Degree2Radius(lat2)) * Math.Cos(Degree2Radius(t));
    distance = Math.Acos(distance);
    distance = Radius2Degree(distance);
    distance = distance * 60 * 1.1515;

    return distance;
}

private static double Degree2Radius(double deg)
{
    return (deg * Math.PI / 180.0);
}

private static double Radius2Degree(double rad)
{
    return rad / Math.PI * 180.0;
}

2
你可以使用Vincenty公式进行计算,该公式考虑了地球的形状。你可以在此处使用JavaScript:http://www.movable-type.co.uk/scripts/latlong-vincenty.html
以下网页易于解析,也可以用来计算距离(例如):http://boulter.com/gps/distance/?from=51.5329855+-0.1303506&to=40.757584+-73.985642&units=m 如果您只需要快速测量距离,请查看该小工具。然而,它只使用大圆计算。
正如Rob所指出的,Google已经加入了它,但他们仍然只使用大圆公式,可能会有1/300的误差。

0
如果你只想得到距离的数字,可以尝试类似这样的代码。
function InitDistances() {
    var startLocation = new GLatLng(startLat, startLon);
    var endLocation = new GLatLng(endLat, endLon);
    var dist = startLocation .distanceFrom(endLocation);

    // Convert distance to miles with two decimal points precision
    return (dist / 1609.344).toFixed(2);
}

0

这是针对API的第二个版本 - 你知道V3中是否存在类似的东西吗? - Rachel
我不知道有没有,但我猜最接近的方法是使用路线规划器并从中获取距离。 - thiswayup

0

虽然我已经很多年没有做过这个了,但你可以使用大圆距离


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接