2009-02-03 120 views
3

是否可以向谷歌发送两个经纬度长点来计算两者之间的距离?使用谷歌地图api工作两点之间的距离?

+1

直接前往[@ SunnyD的回答下面](http://stackoverflow.com/questions/506747/working-out-distances-between-two-points-using-google -maps-api/6419141#6419141)获取Google Maps API V3答案。 – Josh 2011-07-15 15:22:59

回答

7

你所追求的是Haversine formula。你不需要谷歌地图来做到这一点,你可以单独解决。有一个脚本来做到这一点(在JavaScript中)here

3

是谷歌能做到这一点

google api docs

这里是一片的Java脚本,得到的两分

 
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#中的距离CAL在千米的距离:

// 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; 
} 
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); 
} 
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); 
} 
相关问题