2013-11-21 64 views
0

我無法找到一個簡單的答案,因此它就在這裏。只需在兩點之間顯示KM的距離

我取緯度和經度從WordPress郵寄座標。我把它們放在一個數組初始化我的標誌物本身(忽略超時和東西,我只是想通過標記1滴1 ..):

function initMarkers(){ 
    for (i = 0; i < locations.length; i++) { 
     setTimeout(function(y){ 
      marker = new google.maps.Marker({ 
       position: new google.maps.LatLng(locations[y][2], locations[y][1]), 
       map: map, 
       animation: google.maps.Animation.DROP, 
       icon: iconMarker 
      }) 
      gmarkers.push(marker);//Adds the marker object to array 

      //console.log(gmarkers[i].getPosition()); 

     },500 * i, i);// end setTimeout 

    }// end for 
} 

這工作沒有問題。請注意,我將標記對象添加到「gmarkkers」以最終能夠使用其參數。

在這一點上,顯示的地圖,標記下降,沒有錯誤。

我還存儲用戶的地理位置在「userPos」。

 if(navigator.geolocation) { 
      navigator.geolocation.getCurrentPosition(function(position) { 
      /*var userPos = new google.maps.LatLng(position.coords.latitude, 
              position.coords.longitude);*/ 
      userPos = google.maps.LatLng(position.coords.latitude, 
      position.coords.longitude); 

      }, function() { 
      handleNoGeolocation(true); 
      }); 
     } else { 
      // Browser doesn't support Geolocation 
      handleNoGeolocation(false); 
     } 

現在來了我的問題。我如何獲得用戶位置到每個標記的距離?

我試過各種像ascynchronous「computeDistanceBetween」這樣的東西,但它給我未定義的變量錯誤,顯然可能有一個同步問題和whatnot ...(這將解釋未定義的變量)。

有沒有簡單的解決方案?計算兩個點之間的大圓距離

+0

'ascynchronous 「computeDistanceBetween」' - computeDistanceBetween是_not_異步的。但是,您的地理定位和initMarkers功能都需要時間才能完成。 – geocodezip

回答

0

的一種方式是使用haversine公式。

您可以通過執行獲得的距離(在腳本d變量):

Number.prototype.toRad = function() { 
    return this * Math.PI/180; 
} 

var R = 6371; // km 
var dLat = (lat2-lat1).toRad(); 
var dLon = (lon2-lon1).toRad(); 
var lat1 = lat1.toRad(); 
var lat2 = lat2.toRad(); 

var a = Math.sin(dLat/2) * Math.sin(dLat/2) + 
     Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); 
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
var d = R * c; 
+0

謝謝,我會試試這個。 – user3018079