2012-11-08 132 views
0

我目前正在使用一個使用google maps API的Javascript程序。 需要做什麼:Google Maps API搜索

  1. 允許用戶輸入一個位置。
  2. 一旦用戶點擊「查找」按鈕,它將用戶輸入的位置轉換爲經度和緯度座標。
  3. 然後它運行一個算法來計算用戶輸入的位置和硬編碼的lng和lat座標之間的距離。
  4. 它將以KM輸出距離。
  5. 然後它將不得不循環並找到最低距離並抓住lng和lat id,以便知道最短距離的位置。

我已經管理得到步驟1和2完成,但我找不到存儲位置索引(一種方法來識別它)和lng和lat點,以便我可以循環並將它們與用戶輸入的位置進行比較。我也不能找出一種方法來找到最短的距離將所有的點找到最接近的lng和lat。

任何幫助,將不勝感激,

謝謝!

+0

嗨!歡迎來到SO。向我們展示一些代碼,以便我們可以分享一個共同的起點。 –

回答

0

我認爲你應該能夠適應你的目的這個答案。

//forumla for calculating distances between points 
var getDistance = function(p1, p2) { 
    var rad = function(x) {return x*Math.PI/180;} 
    var R = 6371; // earth's mean radius in km 
    var dLat = rad(p2.lat() - p1.lat()); 
    var dLong = rad(p2.lng() - p1.lng()); 

    var a = Math.sin(dLat/2) * Math.sin(dLat/2) + 
      Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) * Math.sin(dLong/2) * Math.sin(dLong/2); 
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
    var d = R * c; 

    return d.toFixed(3); 
} 

// LatLng object with your current coordinates 
var yourLocation = new google.maps.LatLng(yourlat, yourlng); 

// populate an array of hard coded LatLng objects 
var twentypoints = {}; 
twentypoints['hardcodedName1'] = new google.maps.LatLng(lat1, lng1); 
twentypoints['hardcodedName2'] = new google.maps.LatLng(lat2, lng2); 
twentypoints['hardcodedName3'] = new google.maps.LatLng(lat3, lng3); 
    ... 

// calculate the minimum distance 
var closestLocName, minDist; 
for (var hardcodedName in twentypoints) { 
    tempMinDist = getDistance(twentypoints[hardcodedName], yourLocation)); 
    if (minDist === undefined || tempMinDist < minDist) { 
    minDist = tempMinDist; 
    closestLocName = hardcodedName; 
    } 
} 

console.log('Closest location is called ' + closestLocName + '.'); 
console.log('Closest location is ' + minDist + 'km away.');