跳转到一系列位置
跳转到地图上的一系列位置;
<!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%; }
.visited {
background-color: #3887be;
color: #fff;
padding: 5px;
border-radius: 3px;
}
.wrapper {
position: absolute;
display: table;
width: 100%;
height: 100%;
text-align: center;
}
.message {
display: table-cell;
vertical-align: middle;
font-size: 30px;
font-weight: bold;
color: #fff;
text-shadow: 0 0 5px #000;
}
</style>
</head>
<body>
<div id="map"></div>
<div id="wrapper" class="wrapper" style="display: none">
<div id="message" class="message"></div>
</div>
<script>
// 这是我们要访问的位置的数组
// 格式是:[经度, 纬度, 缩放级别, 标题]
const locations = [
[[-79.38927, 43.64344], 11, '多伦多'],
[[-123.10897, 49.26323], 11, '温哥华'],
[[-0.12624, 51.50091], 11, '伦敦'],
[[139.90334, 35.66091], 11, '东京'],
[[37.61831, 55.75718], 11, '莫斯科'],
[[2.34294, 48.85661], 11, '巴黎']
];
const map = new maplibregl.Map({
container: 'map',
style: 'https://api.maptiler.com/maps/streets/style.json?key=get_your_own_OpIi9ZULNHzrESv6T2vL',
center: [0, 0],
zoom: 1
});
function jumpTo(location, callback) {
var bounds = location[0].reduce(function (bounds, coord) {
return bounds.extend(coord);
}, new maplibregl.LngLatBounds(location[0][0], location[0][0]));
map.fitBounds(bounds, {
duration: 0, // 这里设置为0是即时跳转,无动画
padding: 100
});
document.getElementById('wrapper').style.display = 'block';
document.getElementById('message').textContent = location[2];
setTimeout(function () {
document.getElementById('wrapper').style.display = 'none';
if (callback) callback();
}, 1500);
}
function startJourneyBtnClick() {
// 移除开始按钮
document.getElementById('start-journey-btn').remove();
// 递归访问所有位置
let locationIndex = 0;
const visitLocation = function () {
if (locationIndex >= locations.length) return;
jumpTo(locations[locationIndex], function () {
locationIndex++;
if (locationIndex < locations.length) {
setTimeout(visitLocation, 500);
}
});
};
visitLocation();
}
// 地图加载完成后,显示开始按钮
map.on('load', function () {
// 创建"开始旅程"按钮
const startJourneyBtn = document.createElement('button');
startJourneyBtn.id = 'start-journey-btn';
startJourneyBtn.style.cssText = 'position: absolute; top: 20px; left: 50%; transform: translateX(-50%); z-index: 1; padding: 10px 20px; background-color: #3887be; color: white; border: none; border-radius: 3px; cursor: pointer; font-size: 16px;';
startJourneyBtn.textContent = '开始旅程';
startJourneyBtn.addEventListener('click', startJourneyBtnClick);
document.body.appendChild(startJourneyBtn);
});
</script>
</body>
</html>