gpt4 book ai didi

javascript - 如何使用传单在 openstreetmap 上移动标记?

转载 作者:行者123 更新时间:2023-11-30 06:19:13 33 4
gpt4 key购买 nike

我正在使用一个提供实时飞机位置的 API。

在传单中,我使用纬度和经度在 map 上显示每个平面的标记。我想在每次刷新脚本时创建一个新标记时移动标记。

setInterval(() => {
fetch("https://opensky-network.org/api/states/all")
.then((res) => {
return res.json();
})
.then((res) => {

for (let i = 0; i < res.states.length; i++) {
if (res.states[i][2] == 'France') {
if (res.states[i][5] != null || res.states[i][6] != null) {
posA = res.states[i][5];
posB = res.states[i][6];
marker = L.marker([posB, posA]);
marker.addTo(mymap);
}
}

}


})
.catch((err) => {
if (err) throw err
})
}, 3000);

我试过了但是没用:

var newLatLng = new L.LatLng(posB, posA);
marker.setLatLng(newLatLng);

最佳答案

如果给定 ICAO 的标记已经存在,您可以保留一个散列来查找,必要时创建一个标记或更新其位置。像这样的东西:

function fetchData() {
return fetch("https://opensky-network.org/api/states/all")
.then((res) => {
return res.json();
})
.then((res) => {
return res.states.filter((state) => {
return (state[2] === 'France') && (state[5]) && (state[6]);
});
})
.catch((err) => {
if (err) throw err
});
}

function plotStates(map, markers) {
fetchData().then(function(states) {
states.forEach((state) => {
const lat = state[6],
lng = state[5],
icao24 = state[0];

if (markers[icao24]) {
markers[icao24].setLatLng([lat, lng]);
} else {
markers[icao24] = L.marker([lat, lng]);
markers[icao24].addTo(map);
}
});
setTimeout(() => plotStates(map, markers), 3000);
});
}

const markers = {};
plotStates(map, markers);

还有一个演示

function fetchData() {
return fetch("https://opensky-network.org/api/states/all")
.then((res) => {
return res.json();
})
.then((res) => {
return res.states.filter((state) => {
return (state[2] === 'France')
&& (state[5]) && (state[6]);
});
})
.catch((err) => {
if (err) throw err
})
}

function plotStates(map, markers) {
fetchData().then(function(states) {
states.forEach((state) => {
const lat = state[6],
lng = state[5],
icao24 = state[0];

if (markers[icao24]) {
markers[icao24].setLatLng([lat, lng]);
} else {
markers[icao24] = L.marker([lat, lng]);
markers[icao24].addTo(map);
}
});
setTimeout(() => plotStates(map, markers), 3000);
});
}

var map = L.map(document.getElementById('map')).setView([48.8583736, 2.2922926], 4);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

L.marker([48.8583736, 2.2922926]).addTo(map);

const markers = {};
plotStates(map, markers);
html, body {
height: 100%;
margin: 0;
}
#map {
width: 100%;
height: 100%;
}
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.4/dist/leaflet.css"/>
<script src="https://unpkg.com/leaflet@1.3.4/dist/leaflet.js"></script>

<div id='map'></div>

关于javascript - 如何使用传单在 openstreetmap 上移动标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54234262/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com