实时更新地图要素
通过更新数据来实时更改地图上的现有要素;
<!DOCTYPE html>
<html lang="en">
<head>
<title>实时更新地图要素</title>
<meta property="og:description" content="通过更新数据来实时更改地图上的现有要素" />
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel='stylesheet' href='https://unpkg.com/maplibre-gl@5.5.0/dist/maplibre-gl.css' />
<script src='https://unpkg.com/maplibre-gl@5.5.0/dist/maplibre-gl.js'></script>
<style>
body { margin: 0; padding: 0; }
html, body, #map { height: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
const map = new maplibregl.Map({
container: 'map',
style:
'https://api.maptiler.com/maps/streets/style.json?key=get_your_own_OpIi9ZULNHzrESv6T2vL',
zoom: 0
});
map.on('load', () => {
// 我们使用D3来获取JSON,以便我们可以单独解析和使用它
// 与GL JS在添加的源中的使用分开。您可以使用任何请求方法
// (库或其他方式)
d3.json(
'https://maplibre.org/maplibre-gl-js/docs/assets/hike.geojson',
(err, data) => {
if (err) throw err;
// 保存完整坐标列表以便后续使用
const coordinates = data.features[0].geometry.coordinates;
// 开始时只显示第一个坐标
data.features[0].geometry.coordinates = [coordinates[0]];
// 将其添加到地图
map.addSource('trace', {type: 'geojson', data});
map.addLayer({
'id': 'trace',
'type': 'line',
'source': 'trace',
'paint': {
'line-color': 'yellow',
'line-opacity': 0.75,
'line-width': 5
}
});
// 设置视口
map.jumpTo({'center': coordinates[0], 'zoom': 14});
map.setPitch(30);
// 定期从保存的列表中添加更多坐标并更新地图
let i = 0;
const timer = window.setInterval(() => {
if (i < coordinates.length) {
data.features[0].geometry.coordinates.push(
coordinates[i]
);
map.getSource('trace').setData(data);
map.panTo(coordinates[i]);
i++;
} else {
window.clearInterval(timer);
}
}, 10);
}
);
});
</script>
</body>
</html>