2013-01-02 132 views
0

我創造了這個腳本haversine公式的幫助下,問題是,它讓我引導到第一位置的陣列上,不管我有多少時間交換他們有關。有任何想法嗎?排序多個JavaScript陣列

var locations = new Array(
    Array("Brighton", 50.82253, -0.137163), 
    Array("Chichester", 50.83761, -0.774936), 
    Array("Portsmouth", 50.8166667, -1.0833333), 
    Array("Worthing", 50.81787, -0.372882) 
); 

function deg2rad(degrees){ 
    radians = degrees * (Math.PI/180); 
    return radians; 
} 

function haversine(lat1,lon1,lat2,lon2) { 
    deltaLat = lat2 - lat1; 
    deltaLon = lon2 - lon1; 
    earthRadius = 3959; // In miles (6371 in kilometers) 
    alpha = deltaLat/2; 
    beta = deltaLon/2; 
    a = Math.sin(deg2rad(alpha)) * Math.sin(deg2rad(alpha)) 
     + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) 
     * Math.sin(deg2rad(beta)) * Math.sin(deg2rad(beta)); 
    c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
    distance = earthRadius * c; 
    return distance.toFixed(2); 
} 

function locationSuccess(position) { 

    var places = new Array(); 
    var userLatitude = position.coords.latitude; 
    var userLongitude = position.coords.longitude; 

    for(var i=0;i<locations.length;i++) { 
     places.push(haversine(
      userLatitude, 
      userLongitude, 
      locations[i][1], 
      locations[i][2] 
     )); 
    } 

    var sorted = places.sort(); // Sort places from low to high 

    /* 
    alert(places); // Listed distances unordered 
    alert(sorted); // Listed distances in order 
    alert(sorted[0]); // Nearest city distance 
    */ 

} 

function locationFailed() { 
    // Change me to a better error message 
    alert("Ooops, we couldn't find you!"); 
} 

// Get user's physical location 
navigator.geolocation.getCurrentPosition(locationSuccess, locationFailed); 

回答

3

你不排序的位置陣列,只有距離的陣列。

你應該丟棄該距離進入locations陣列(即,作爲各元素的第四構件):

for(var i = 0; i < locations.length; ++i) { 
    var l = locations[i]; 
    l[3] = haversine(userLatitude, userLongitude, l[1], l[2]); 
} 

,然後使用「比較器」功能,着眼於該距離場:

locations.sort(function(a, b) { 
    return (a[3] < b[3]) ? -1 : ((a[3] > b[3]) ? 1 : 0); 
}); 
+0

你是對的!非常感謝你。 –

+0

我會盡我所能。直到7分鐘後,我才接受它。順便說一句,在你最後一段代碼的第二行有一個語法錯誤。 –

+1

@Titanium我修正了錯字,謝謝。 – Alnitak