Javascript 如何显示基于用户纬度和经度的最近位置列表
如何按距离升序显示最近的三个位置 我可以用下面的代码显示一个最近的位置,但是在显示第二个和第三个最近的位置时遇到了障碍Javascript 如何显示基于用户纬度和经度的最近位置列表,javascript,geolocation,Javascript,Geolocation,如何按距离升序显示最近的三个位置 我可以用下面的代码显示一个最近的位置,但是在显示第二个和第三个最近的位置时遇到了障碍 <div class="container p-3"> <button onclick="getLocation()" class="mb-2">Find city nearest you</button> <p id="closest"> </p> </div> var x = document.get
<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;
}
找到离你最近的城市
var x=document.getElementById(“最近”);
变量存储位置={
“亚特兰大”:{纬度:33.7489954,经度:-84.3879824},
“芝加哥”:{纬度:41.8781136,经度:-87.6297982},
“达拉斯”:{纬度:32.7766642,经度:-96.7969879},
“休斯顿”{纬度:29.7604267,经度:-95.3698028},
“洛杉矶”:{纬度:34.0522342,经度:-118.2436849},
“纽约”:{纬度:40.7127837,经度:-74.0059413},
“费城”:{纬度:39.9525839,经度:-75.1652215},
“凤凰城”{纬度:33.4483771,经度:-112.0740373},
“西雅图”:{纬度:47.6062095,经度:-122.3320708}
}
函数getLocation(){
if(导航器.地理位置){
navigator.geolocation.getCurrentPosition(findNearestStore);
}否则{
x、 innerHTML=“地点:华盛顿特区”;
}
}
功能findNearestStore(位置){
var nearestStore=geolib.findNearest({纬度:位置.坐标.纬度,经度:位置.坐标.经度},存储位置);
x、 innerHTML=“Location:”+nearestStore.key;
}
Codepen:使用
orderByDistance
功能,并结合数组。切片
,如下所示:
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 + " ";
})
这是一个显示结果的示例。不认为这是一个非常有效的方法,但是再次运行请求两次,每次都从存储列表中删除前一个最近的存储,怎么样?它是一个数组,您可以编写一个比较函数传递给array::sort以计算距离
位置的距离。一种优化方法是将以前的计算结果存储到每个城市,以加快以后的比较。第二个小优化是比较距离平方并保存平方根计算。请尝试下面的解决方案。我正在努力应用您的解决方案,但有些地方不对劲。