2009-02-03 164 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); 
} 
相關問題