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);
맞습니다! 고맙습니다. –
할 수있을 때까지하겠습니다. 나는 7 분이 지날 때까지 그것을 받아 들일 수 없다. 그건 그렇고, 마지막 조각 코드의 두 번째 줄에 구문 오류가 있습니다. –
@ 티타늄 오타가 수정되었습니다. – Alnitak