Search code examples
javascriptmathgeolocation

How to find the nearest 10 locations around me


How can I find the nearest 10 locations around me. Let's say I have my current latitude, longitude and the coordinates of the locations around me

I have:

 var myLatitude = 00000.0000;
 var myLongitude = 0000.0000;
 var worldAroundMe = [{ 'lat': something,'long': something, }, {'latitude': something,'longitude': something,}{more locations}];

Solution

  • You'll want to compute the distance from each coordinate to your latitude/longitude, then sort by that number:

    function sortByDistance(myLatitude, myLongitude, world) {
        var distances = []; // This will hold an array of objects. Each object will have two keys: distance, and place. The distance will be the distance of the place from the given latitude and longitude
        // Find the distance from each place in the world
        for (var i = 0; i < world.length; i++) {
            var place = world[i];
            var distance = Math.sqrt(Math.pow(myLatitude - place.latitude, 2) + Math.pow(myLongitude - place.longitude, 2)); // Uses Euclidean distance
            distances.push({distance: distance, place: place});
        }
        // Return the distances, sorted
        return distances.sort(function(a, b) {
            return a.distance - b.distance; // Switch the order of this subtraction to sort the other way
        })
        .slice(0, 10); // Gets the first ten places, according to their distance
    }
    

    Note that this is using the Euclidean distance https://en.wikipedia.org/wiki/Euclidean_distance. There are other methods of determining distance that might be more suitable to your application.

    Also note that this is performing a O(n) operation (assuming that your JavaScript engine is sorting the array with at most O(n) complexity; Google "Complexity Classes" to learn what O(?) means), so it'll be 1000 times slower for 1000 times the number of places. Ways to optimize in spite of this include:

    • Cache the results so that this computation doesn't have to be done more than once
    • Have the distance be part of the "place" object (e.g. {latitude: 123, longitude: 321, distance: 543} that is computed only when the object is created

    Here's an example of it being used (in Google Chrome's developers console): enter image description here