如何按距离升序显示最近的三个位置?我可以使用下面的代码显示单个最近的位置,但是在显示第二个第三个最近的位置时遇到了障碍。<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
1 回答
ITMISS
TA贡献1871条经验 获得超8个赞
使用该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 + " ";
})
这是一个显示结果的代码笔。
添加回答
举报
0/150
提交
取消