mapbox-gl.js实现飞到初始位置功能
时间: 2023-09-06 20:08:45 浏览: 186
mapbox-gl-js-layer-control:mapbox-gl-js切换图层的控件
要使用Mapbox GL JS实现飞到初始位置功能,你可以通过以下步骤来实现:
1. 获取地图的初始中心点和缩放级别:
```javascript
var initialCenter = [lng, lat]; // 初始中心点经纬度
var initialZoom = 12; // 初始缩放级别
```
2. 添加一个按钮,当点击该按钮时,地图会飞到初始位置:
```html
<button id="fly-to-initial">飞到初始位置</button>
```
```javascript
var flyToInitialButton = document.getElementById('fly-to-initial');
flyToInitialButton.addEventListener('click', function() {
map.flyTo({
center: initialCenter,
zoom: initialZoom,
speed: 0.8
});
});
```
3. 完整代码示例:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Mapbox GL JS - Fly to initial position</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.js'></script>
<link href='https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.css' rel='stylesheet' />
</head>
<body>
<div id='map' style='width: 100%; height: 500px;'></div>
<button id="fly-to-initial">飞到初始位置</button>
<script>
mapboxgl.accessToken = 'YOUR_ACCESS_TOKEN';
var initialCenter = [lng, lat]; // 初始中心点经纬度
var initialZoom = 12; // 初始缩放级别
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: initialCenter,
zoom: initialZoom
});
var flyToInitialButton = document.getElementById('fly-to-initial');
flyToInitialButton.addEventListener('click', function() {
map.flyTo({
center: initialCenter,
zoom: initialZoom,
speed: 0.8
});
});
</script>
</body>
</html>
```
这个示例代码会在地图上显示一个按钮,当点击该按钮时,地图会缓慢地飞到初始位置。
阅读全文