开发者

Sort computed areas

开发者 https://www.devze.com 2023-03-30 20:38 出处:网络
I have a google maps and I get all markers that are close a locaton (lat, lng). This point is OK. Now i want to sort theses markers, like in SQL we can do a \"order by distance ASC\" for example.

I have a google maps and I get all markers that are close a locaton (lat, lng). This point is OK.

Now i want to sort theses markers, like in SQL we can do a "order by distance ASC" for example.

I saw in javascript have a method call sort() which开发者_开发百科 can sort some numbers asc or desc for example.

markers have some informations: name, title, gender, city, postcode ...

my code:

 var nbMeters = 50000;  

for (var i = 0; i < markers.length; i++) {
        var myMarker = markers[i];

         coord2 = new google.maps.LatLng(myMarker.lat, myMarker.lng);
        var distance = google.maps.geometry.spherical.computeDistanceBetween(coords, coords2);


  if(distance <= nbMeters) {   

     alert(myMarker.name);
    //OK my marker is close the variable coords, good !
    //But how to know which marker is the closer, which is the second, the third ... and the less closer ??

  }

}

Have you an idea?


Maybe try sth like this:

for (var i = 0; i < markers.length; i++) {
    var myMarker = markers[i];

    coord2 = new google.maps.LatLng(myMarker.lat, myMarker.lng);
    var distance = google.maps.geometry.spherical.computeDistanceBetween(coords, coords2);
    markers[i].distance = distance;
}

function sortMarkers(marker1, marker2) {
    return marker1.distance - marker2.distance;
}

markers.sort(sortMarkers);

It's untested and based on http://www.w3schools.com/jsref/jsref_sort.asp

0

精彩评论

暂无评论...
验证码 换一张
取 消