0

I want to sort array/object of cities based on my location from nearest (to my location) to furthest

I have list of locations that i get from database How would i solve this using javascript and HTML5 geolocation?

I have something like this: example :

var locations= [{"name":"location1" "latitude" :"31.413165123" 
"longitude":"40.34215241"},{"name":"location2" "latitude" :"31.413775453" 
"longitude":"40.34675341"}]

and I want to sort those location by nearest to my location

StefanBRT
  • 43
  • 1
  • 6

2 Answers2

2

FIRST: The provided array is broken (i added commas between fields).

var locations = [{
    "name": "location1",
    "latitude": "31.413165123",
    "longitude": "40.34215241"
}, {
    "name": "location2",
    "latitude": "31.413775453",
    "longitude": "40.34675341"
}];

You'll need to leverage a custom sort function, which needs to return 1, -1, or 0 based on comparing 2 items.

var myLong = 42.0; // whatever your location is
var myLat = 3.16; // whatever your location is

locations.sort( function (a, b) {

    // This is untested example logic to 
    // help point you in the right direction.
    var diffA = (Number(a.latitude) - myLat) + (Number(a.longitude) - myLong);
    var diffB = (Number(b.latitude) - myLat) + (Number(b.longitude) - myLong);

    if(diffA > diffB){
        return 1;
    } else if(diffA < diffB){
        return -1;
    } else {
        return 0; // same
    }

} );
bob
  • 7,539
  • 2
  • 46
  • 42
1

Store your location, create a function that calculates the distance between two points and then use the sort method:

function dist({latitude: lat1, longitude: long1}, {latitude: lat2, longitude: long2}) {
   // I'm not very good at geography so I don't know how to calculate exactly the distance given latitudes and longitudes.
   // I hope you can figure it out
   // the function must return a number representing the distance
}
navigator.geolocation.getCurrentPosition(({coords}) => {
   coords.latitude = parseFloat(coords.latitude)
   corrds.longitude = parseFloat(coords.longitude)

   locations.sort((p1, p2) => dist(coords, {latitude: parseFloat(p1.latitude), longitude: parseFloat (p1.longitude)}) - 
    dist(coords, {latitude: parseFloat(p2.latitude), longitude: parseFloat(p2.longitude)}))
})

Hope it helps you

Stefan Octavian
  • 593
  • 6
  • 17