簡體   English   中英

如何根據用戶緯度和經度顯示最近位置列表

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

如何按距離升序顯示最近的三個位置?

我可以使用下面的代碼顯示單個最近的位置,但是在顯示第二個第三個最近的位置時遇到了障礙。

<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;
}

代碼筆: https ://codepen.io/Codewalker/pen/LwWqrE

使用orderByDistance函數,結合Array.slice如下:

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

來源

編輯:您將使用上述方法獲得 3 個最近的位置,但要打印它們,您需要循環遍歷它們,因為您獲得了一個數組。 無需再次使用.slice() 像這樣:

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

這是一個顯示結果的代碼筆

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM