2011-11-03 85 views

回答

101

如果你正在尋找使用v3的谷歌地圖API,這裏是一個功能的使用方法: 注意:您必須添加&libraries=geometry到腳本源

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

<script> 
var p1 = new google.maps.LatLng(45.463688, 9.18814); 
var p2 = new google.maps.LatLng(46.0438317, 9.75936230000002); 

alert(calcDistance(p1, p2)); 

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

</script> 
+0

我添加了使用示例,您需要傳遞2個座標。它爲我工作,返回78.35 –

+3

請不要忘記標記問題的答案,以幫助人們在未來找到正確的答案。 –

+1

這是否以英里或公里爲單位返回值? – Zabs

4

我認爲你可以沒有任何特定的API做的,用簡單的Javascript計算距離:

This網站有關於地理計算和JavaScript樣本距離計算的很好的信息。

好吧,在谷歌API網頁快速瀏覽一下,似乎,你可以通過做:

  1. 呼叫爲DirectionsService()路線(),以獲得DirectionsResult與路線
  2. 對於一個或每個路由走通過它的腿特性,算出距離
+3

是的,但距離正在開闢道路:)這就是爲什麼谷歌API ... – markzzz

+0

謝謝你的第一個鏈接。近距離計算可以使用近似公式進行優化 – Dan

1

這主要與數學做谷歌的API之外,所以你不應該需要使用API​​比找到正確的座標以外的任何其他的總和。

知道了,這裏有一個鏈接到一個以前回答與Javascript有關的問題。

Calculate distance between 2 GPS coordinates

1

試試這個

CLLocationCoordinate2D coord1; 
coord1.latitude = 45.463688; 
coord1.longitude = 9.18814; 
CLLocation *loc1 = [[[CLLocation alloc] initWithLatitude:coord1.latitude longitude:coord1.longitude] autorelease]; 

CLLocationCoordinate2D coord2; 
coord2.latitude = 46.0438317; 
coord2.longitude = 9.75936230000002; 
CLLocation *loc2 = [[[CLLocation alloc] initWithLatitude:46.0438317 longitude:9.75936230000002] autorelease]; 

CLLocationDistance d1 = [loc1 distanceFromLocation:loc2]; 
+0

如何獲得2點之間的路線距離,這只是給出了直接距離(在物理學文獻中:位移),如何獲得路徑距離 –

+0

這就是目標C :)問題是關於Javascript API谷歌地圖 –

+0

請提供解釋,而不是「試試這個」。 –

0

試試這個:

const const toRadians = (val) => { 
    return val * Math.PI/180; 
} 
const toDegrees = (val) => { 
    return val * 180/Math.PI; 
} 
// Calculate a point winthin a circle 
// circle ={center:LatLong, radius: number} // in metres 
const pointInsideCircle = (point, circle) => { 
    let center = circle.center; 
    let distance = distanceBetween(point, center); 

    //alert(distance); 
    return distance < circle.radius; 
}; 

const distanceBetween = (point1, point2) => { 
    //debugger; 
    var R = 6371e3; // metres 
    var φ1 = toRadians(point1.latitude); 
    var φ2 = toRadians(point2.latitude); 
    var Δφ = toRadians(point2.latitude - point1.latitude); 
    var Δλ = toRadians(point2.longitude - point1.longitude); 

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

    return R * c; 
} 

參考文獻:http://www.movable-type.co.uk/scripts/latlong.html

+0

請改善您的答案。爲什麼它更好,它是如何工作的等等。「試試這個」是不夠的。 Stackoverflow不是關於盲目嘗試,而是閱讀和理解事物的工作方式。還是謝謝你的貢獻:) –