如何根据位置打印出某些元素



我有一个javascript函数,它可以获取用户的当前位置,另一个函数可以在一些特定坐标之间的随机位置生成自行车。

我想在控制台日志中打印出最近的5(例如,所有长度和宽度小于0.05的自行车。我不知道从哪里开始,有人知道吗?

这是我的javascript代码

底部的for each循环是我尝试的方法,但我不确定如何访问位置常量。

if(navigator.geolocation){
//Location is supported by the browser
const locationElement = document.getElementById("location")
navigator.geolocation.getCurrentPosition((position) => {
console.log(position)
locationElement.innerText = `${position.coords.latitude},${position.coords.longitude}`
})
}

class Bike{
constructor(name, location){
this.name = name;
this.location = location;
}
}

class Location {
constructor(lat, lon) {
this.lat = lat;
this.lon = lon
}
}
const bikes = [];
for(let i= 1; i<30; i++) {
const name = `CityBike${i}`
const location = new Location(Math.random()/10 + 55.5, Math.random()/10 + 12.5)

const bike = new Bike(name, location)

bikes.push(bike)
}

bikes.forEach((bike) => {

if((bike.location - position) < 0.1) {
console.log(bike)
}
})


由于获取位置是一个异步操作,您需要在getCurrentPosition的回调方法内检查位置是否在范围内。此外,我认为最好使用当前位置作为圆圈的中心坐标,根据你想走的距离选择半径,画一个圆圈,并检查其他自行车的位置是否在圆圈内。现在,我刚刚更改了代码,使其适用于经度和纬度的比较。

if (navigator.geolocation) {
//Location is supported by the browser
//const locationElement = document.getElementById("location")
navigator.geolocation.getCurrentPosition((position) => {
console.log(`${position.coords.latitude},${position.coords.longitude}`);
const myLocation = new Location(position.coords.latitude, position.coords.longitutde);
bikes.forEach((bike) => {

if ((myLocation.lat - bike.location.lat) < 0.1 && (myLocation.lon - bike.location.lon) < 0.1) {
console.log(bike);
}
})
//locationElement.innerText = `${position.coords.latitude},${position.coords.longitude}`
})
}

class Bike {
constructor(name, location) {
this.name = name;
this.location = location;
}

}
var bikes = [];
class Location {
constructor(lat, lon) {
this.lat = lat;
this.lon = lon
}
}

for (let i = 1; i < 3; i++) {
const name = `CityBike${i}`
const location = new Location(Math.random() / 10 + 55.5, Math.random() / 10 + 12.5)
console.log(location);
const bike = new Bike(name, location)

bikes.push(bike)
}

最新更新