사용자 위치와 상점 위치를 기반으로이 두 점 사이의 거리를 계산합니다. 이것은 작동하지만, 원하는 것은 모든 값을 가진 배열이며 두 점 사이의 거리를 정렬합니다.jQuery 정렬 함수가 제대로 작동하지 않습니다.
내 add_stores_to_array
기능이 있습니다. 모든 상점을 JSON 파일을 통해 반복 할 때 배열 stores
에 추가 할 수 있습니다.
add_stores_to_array = function(position) {
var user_latitude = position.coords.latitude;
var user_longitude = position.coords.longitude;
$.getJSON('/stores').done(function(data) {
$.each(data.features, function(i, item) {
var store_latitude = item.geometry.coordinates[1];
var store_longitude = item.geometry.coordinates[0];
var user = new google.maps.LatLng(user_latitude, user_longitude);
var store = new google.maps.LatLng(store_latitude, store_longitude);
var directionsService = new google.maps.DirectionsService();
var request = {
origin:user,
destination:store,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var response = Math.ceil(response.routes[0].legs[0].distance.value/1000);
// add distance and store id to the array stores
stores.push({distance: response, id: item.properties.Nid});
}
});
});
// call the sort function
sort_stores(stores);
console.log(stores);
});
};
$.each
이후에 나는 sort 함수를 호출합니다. 그러나 콘솔에 기록한 후에도 여전히 정렬되지 않습니다.
내 sort_stores
기능 :
if (i == Object.keys(data.features).pop()) {
sort_stores(stores);
}
:
sort_stores = function(stores){
stores.sort(function(a, b){
return a.distance - b.distance;
});
};
먼저 내가 $.each
이 계속 실행 되었기 때문에이 작동하지 않는,하지만이 코드를 추가 한 후, 그것은 여전히 작동하지 않는 생각 그래서 나는 다른 것을 시도했다. $.each
에있는 sort_stores(stores)
함수를 호출합니다.
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var response = Math.ceil(response.routes[0].legs[0].distance.value/1000);
stores.push({distance: response, id: item.properties.Nid});
sort_stores(stores);
}
});
하고 작동이 .. 어레이는 어레이 내의 값의 거리에 따라 정렬된다. 하지만 이제는 상점을 추가 한 후에 배열을 정렬합니다.별로 효과적이지 않습니다.
sort_stores(stores)
함수를 한 번 호출하여 모든 상점을 배열에 추가 할 때 정렬하는 적절한 방법이 있습니까?
편집 :
나는 그것이 작동하고 sort_stores(stores)
전에 alert()
을 배치하면 ..
if (status == google.maps.DirectionsStatus.OK) {
var response = Math.ceil(response.routes[0].legs[0].distance.value/1000);
stores.push({distance: response, id: item.properties.Nid});
}
});
});
alert('Call the sort_stores(stores) function after the $.each, with an alert.. it is working?');
sort_stores(stores);
});
};
편집 2 :
는 일반적으로 여기에서 기능 add_stores_to_array
를 호출?
get_user_location = function(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(add_stores_to_array);
}
};
try'a.distance> b.distance? 1 : a.distance
Rajesh
흠.'$ .each' 다음에'stores.sort (function (a, b)'가 실행되지 않는 것처럼 보입니다.)'alert()' –
콘솔에서 오류를 확인 했습니까? 편집 : 정렬 기능에 아무런 문제가 없습니다. 일단 함수를 작동 시키면 올바르게 작동합니다. –