mapbox-gl的学习过程之自定义线
项目上 有使用到mapbox地图 学习记录一下,以下是代码:
mapbox官方文档
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Guides</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
<!-- npm i mapbox-gl -->
<link rel="stylesheet" href="./node_modules/mapbox-gl/dist/mapbox-gl.css" />
<script src="./node_modules/mapbox-gl/dist/mapbox-gl.js"></script>
<style>
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
// TO MAKE THE MAP APPEAR YOU MUST
// ADD YOUR ACCESS TOKEN FROM
// https://account.mapbox.com
// 引入Mapbox GL JS库
// 初始化地图
// mapboxgl.accessToken = "YOUR_MAPBOX_ACCESS_TOKEN"; // 替换为你的Mapbox访问令牌
var map = new mapboxgl.Map({
container: "map", // 地图容器的DOM元素ID
style: "mapbox://styles/mapbox/streets-v11", // 使用的地图样式
center: [-74.5, 40], // 初始化中心点坐标(这里是纽约)
zoom: 9, // 初始化地图缩放级别
});
// 当地图加载完成后
map.on("load", function () {
// 添加路线GeoJSON数据
map.addSource("route", {
type: "geojson",
data: {
type: "FeatureCollection",
features: [
{
type: "Feature",
properties: {},
geometry: {
type: "LineString",
coordinates: [
[-74.5, 40], // 起点经纬度
[-78.5, 45], // 终点经纬度
[-74.5, 50], // 起点经纬度
[-78.5, 55], // 终点经纬度
// 可以添加更多的坐标点以形成更复杂的路线
],
},
},
],
},
});
// 添加路线图层
map.addLayer({
id: "route",
type: "line",
source: "route",
layout: {
"line-join": "round",
"line-cap": "round",
},
paint: {
"line-color": "#3887ff",
"line-width": 5,
"line-opacity": 0.75,
},
});
});
</script>
</body>
</html>