user3120861
user3120861

Reputation: 185

How to display list of closest locations based on user latitude and longitude

How can I display the closest three locations in ascending order of distance?

I'm able to display the single closest location with the code below, but am running into a roadblock when it comes to displaying the second the third closest locations.

<div class="container p-3">
<button onclick="getLocation()" class="mb-2">Find city nearest you</button>
<p id="closest">
</p>
</div>

var x = document.getElementById("closest");

var storeLocations = {
    "Atlanta": {latitude: 33.7489954, longitude: -84.3879824},
  "Chicago": {latitude: 41.8781136, longitude: -87.6297982},
    "Dallas": {latitude: 32.7766642, longitude: -96.7969879},
  "Houston": {latitude: 29.7604267, longitude: -95.3698028},
    "Los Angeles": {latitude: 34.0522342, longitude: -118.2436849},
    "New York": {latitude: 40.7127837, longitude: -74.0059413},
    "Philadelphia": {latitude: 39.9525839, longitude: -75.1652215},
    "Phoenix": {latitude: 33.4483771, longitude: -112.0740373},
    "Seattle": {latitude: 47.6062095, longitude: -122.3320708}
}

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(findNearestStore);
    } else {
        x.innerHTML = "Location: Washington, D.C.";
    }
}

function findNearestStore(position) {
        var nearestStore = geolib.findNearest({latitude: position.coords.latitude, longitude: position.coords.longitude}, storeLocations);
        x.innerHTML = "Location: " + nearestStore.key;
}

Codepen: https://codepen.io/Codewalker/pen/LwWqrE

Upvotes: 2

Views: 1239

Answers (1)

Anurag Srivastava
Anurag Srivastava

Reputation: 14413

Use the orderByDistance function, combined with Array.slice as below:

var nearest3Stores = 
geolib
  .orderByDistance({
    latitude: position.coords.latitude, 
    longitude: position.coords.longitude
  }, storeLocations)
  .slice(0, 3);

Source

Edit: You will get the 3 nearest locations using the above method,but to print them you need to loop over them since you get an array. No need to use .slice() again. Like this:

y.innerHTML = "Locations: ";
nearest3Stores.forEach(function(store){
  y.innerHTML+= store.key + " ";
})

Here is a codepen showing the results.

Upvotes: 2

Related Questions