前言
官网指引,生成accesstoken,下载相关依赖请翻阅[https://blog.csdn.net/weixin_44402694/article/details/125414381?spm=1001.2014.3001.5501](https://blog.csdn.net/weixin_44402694/article/details/125414381?spm=1001.2014.3001.5501)
本文使用官网accesstoken,请自行生成私人token
mapbox添加pbf矢量切片图层
效果
代码实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>18、添加pbf矢量切片图层</title>
<link
href="https://api.mapbox.com/mapbox-gl-js/v2.7.0/mapbox-gl.css"
rel="stylesheet"
/>
<script src="https://api.mapbox.com/mapbox-gl-js/v2.7.0/mapbox-gl.js"></script>
<style>
* {
padding: 0;
margin: 0;
list-style: none;
text-decoration: none;
}
html,
body {
width: 100%;
height: 100%;
}
#map {
width: 100%;
height: 100%;
}
.btn-list {
position: fixed;
top: 100px;
left: 100px;
}
</style>
</head>
<body>
<div id="map"></div>
<ul class="btn-list">
<li>
<button onclick="add()">添加</button>
</li>
<li>
<button onclick="remove()">删除</button>
</li>
</ul>
<script>
mapboxgl.accessToken =
'pk.eyJ1Ijoid2FuZ3Rvbmd4dWUiLCJhIjoiY2pzY3E2M2k0MDk3NzN5dDA0Nmtia2h0cCJ9.oP9fEJxOgVzm0dWGvL6tGg'
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/satellite-v9',
center: [108, 35],
zoom: 4,
})
function add() {
if (map.getSource('railway_source')) return
map.addSource('railway_source', {
type: 'vector',
tiles: [
`http://xxxx/tagola/maps/railway-maps/railway/{z}/{x}/{y}.pbf`,
],
minzoom: 3,
maxzoom: 16,
})
map.addLayer({
id: 'railway_bg',
type: 'line',
source: 'railway_source',
'source-layer': 'railway',
layout: {
'line-cap': 'round',
'line-join': 'round',
},
paint: {
'line-color': '#94928C',
'line-width': {
stops: [
[3, 1],
[11, 3],
[22, 4],
],
},
},
})
map.addLayer({
id: 'railway',
type: 'line',
source: 'railway_source',
'source-layer': 'railway',
layout: {
'line-cap': 'round',
'line-join': 'round',
},
paint: {
'line-color': '#fff',
'line-width': {
stops: [
[3, 0.5],
[11, 2],
[22, 3],
],
},
'line-dasharray': [2, 7],
},
})
}
function remove() {
if (!map.getSource('railway_source')) {
return alert('请先添加')
}
map.removeLayer('railway_bg')
map.removeLayer('railway')
map.removeSource('railway_source')
}
</script>
</body>
</html>