Sanjay Goswami
Sanjay Goswami

Reputation: 858

Sorting list of addresses by nearest distance through latitude and longitude

I have a list of addresses with latitude and longitude, I want to sort them by nearest distance to one address. Can anyone help?

Upvotes: 1

Views: 1059

Answers (1)

zeachco
zeachco

Reputation: 780

let's say your addresses looks like this

{
   restaurant: 'Moe\'s la Patate'
   longitude: 12345,
   latitude: -1234
}

and are placed in an array named addresses

var addresses = [{
   restaurant: 'Moe\'s la Patate'
   longitude: 12345,
   latitude: -1234
},{
   restaurant: 'Mc Donalds'
   longitude: -531,
   latitude: 235
}// ...
];

and that your position is in the same format (I will use the position variable)

you could do the √(a^2 + b^2) calcul

var position = {
   longitude: 2231,
   latitude: -4211
}
var addressesByDistance = addresses.map(function(data){
    var distX = position.longitude - data.longitude;
    var distY = position.latitude - data.latitude;
    var distance = Math.sqrt(Math.pow(distX, 2) + Math.pow(distY, 2));
    return distance;
}).sort();

This doesnt take in consideration the round up of the earth but having only 10 restaurants, I suppose they are all in the same city?

Anyways, hope it helps

Upvotes: 4

Related Questions