JQuery each largest

I am currently trying to create a storage locator. My current code grabs store information from xml file and then if it is in specified radius it will place it inside div.

My problem is that it just adds the stores in order of them inside the xml. So in my case it is in alphabetical order. Each store has 4 values: name, address, site, and then distance.

What I want to do is put them in a div in order from shortest distance to longest. How can i do this?

Here's the code

function searchxml(origin, rad) {
$(data).find("marker").each(function () {
    var $marker = $(this);
    var name = $marker.attr("name");
    var website = $marker.attr("website");
    var address = $marker.attr("address").replace('&lt;', '<').replace('&gt;', '>');
    var lat = $marker.attr("lat");
    var lng = $marker.attr("lng");
    var latlng = new google.maps.LatLng(lat, lng);
    var destination = new google.maps.LatLng(lat, lng);
    var distance = google.maps.geometry.spherical.computeDistanceBetween(origin, destination);

    var miles = Math.round(distance * 0.000621371192);
    if (miles <= rad) {
        $('#storeInfo').prepend('<div class="storeLocation"><div class="storeLeft"><span class="storeTitle">' + name + '</span></br><p class="storeAddress">' + address + '</p><a href="' + website + '">' + website + '</a></div><div class="storeRight"><span class="storeDistance">Distance: ' + miles + ' miles</span><a href="http://maps.google.com/maps?saddr=' + address + '&daddr=' + origin + '"  class="storeDirections">Map It</span></div><div class="clear"></div></div>').html();
        $('#map_canvas').gmap('addMarker', {
            'position': destination,
            'bounds': true
        }).click(function () {
            $('#map_canvas').gmap('openInfoWindow', {
                'content': name + '<br/>' + address
            }, this);
        });
    } else {}
});
}

      

+3


source to share


2 answers


Instead of adding new divs you create where you are (i.e. on the line $('#storeInfo').prepend(...

), you can store them in an array along with their distance from the location, then sort that array by distance, and finally add these new divs to the element storeInfo

in sorted order.

eg.



function searchxml(origin, rad) {
  var stores = []; //array which will store divs and the distances..
  $(data).find("marker").each(function () {
      ...
     if (miles <= rad) {
        var div = $('<div class="storeLocation"> ...');
        //don't just add this straight away..
        //store it in a simple object holding the new div
        //and the distance and push it onto the array.. 
        stores.push({ div: div, miles: miles });

       $('#map_canvas').gmap('addMarker', {
          ...
    } else {}
  });

  //sort to get the right order..
  stores.sort(function(a,b){
      return b.miles - a.miles; //smaller is better..
  });
  //now append them in the sorted order..
  var storeInfo = $('#storeInfo');
  $.each(stores, function(store){
      storeInfo.append(store.div);
  });
}

      

Note: I used here ...

to point out where you should put what you have in your code in an attempt to make the changes easier to see.

+2


source


What I would do is create a custom sort method (you can either extend jQuery or create an out-of-scope method, it doesn't matter) and then store your values ​​in an array, sort them, and then put them in your container.

function sortByDistance(a, b) {
    var x = a.distance;
    var y = b.distance;
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

      

So then you have your array of elements like var arr = [] and to call it:



var arr = [];
// add your items arr.push(..item..);
arr.sort(sortByDistance);

      

You obviously have two ways to do this. You can create a custom object with all your values ​​in it, put each one in an array and then run the sort method, or you can simply push all of your values ​​into the array, call the sort, and then execute complex logic inside the sort method.

Hope this helps! (I started writing the complete code, but then I realized that I was wasting too much time and you probably have your own way of writing the code.)

+2


source







All Articles