2016-11-11 1 views
1

사용자 위치와 상점 위치를 기반으로이 두 점 사이의 거리를 계산합니다. 이것은 작동하지만, 원하는 것은 모든 값을 가진 배열이며 두 점 사이의 거리를 정렬합니다.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); 
    } 
}; 
+0

try'a.distance> b.distance? 1 : a.distance Rajesh

+0

흠.'$ .each' 다음에'stores.sort (function (a, b)'가 실행되지 않는 것처럼 보입니다.)'alert()' –

+0

콘솔에서 오류를 확인 했습니까? 편집 : 정렬 기능에 아무런 문제가 없습니다. 일단 함수를 작동 시키면 올바르게 작동합니다. –

답변

1

정렬 기능에는 아무런 문제가 없습니다. 문제는 directionsService.route이 비동기 호출이며 모든 호출이 아직 완료되지 않은 경우에도 나머지 코드가 실행된다는 것입니다.

jQuery.when()을 사용할 수 있습니다. 여기에 새로운 기능 add_stores_to_array()

add_stores_to_array = function(position) { 
    var promises = []; //ADDED promise array 
    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 
      }; 

      var dfd = 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}); 
       } 
      }); 

      promises.push(dfd); //ADDED store each object in array 
     }); 

     //Now you can do the following without having any async issue. 
     $.when.apply(null, promises).done(function() { 
      /* sort & do stuff here */ 
      sort_stores(stores); 
      console.log(stores); 
     }); 
    }); 
}; 

EDIT

여기

다른 접근 방식이다. 모든 응답이 리턴 될 때까지 기다려야하므로, 응답 함수를 점검하기 위해 정렬 함수를 사용자 정의 할 수 있습니다. 전체 (모든 호출이 성공적으로 완료되었음을 의미)와 같으면 배열을 정렬합니다.

sort_stores = function(stores, responseCount, totalCount) { 
    if (responseCount == totalCount) { 
     stores.sort(function(a, b){ 
      return a.distance - b.distance; 
     }); 
    } 
}; 

그런 다음 add_stores_to_array 기능을 다음과 같이 변경하십시오.

add_stores_to_array = function(position) { 
    var user_latitude = position.coords.latitude; 
    var user_longitude = position.coords.longitude; 

    $.getJSON('/stores').done(function(data) { 
     var totalCount = data.features.length; //ADDED Get total count 
     var responseCount = 0; //ADDED 
     $.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}); 
        responseCount++; //ADDED 
        sort_stores(stores, responseCount, totalCount); //ADDED Call sort function here 
       } 
      }); 
     }); 
    }); 
}; 
+0

'add_stores_to_array(). done (function() {'어디서든'.done()'으로 인해 가능합니까? –

+0

그래, 코드를 조금 바꿔야 겠어. 작동하지 않는 것 같아. . –

+0

아, 고마워, 내가 기다릴께. –

관련 문제