mapbox 自定义图片点

212 阅读1分钟

mapbox-gl的学习过程之自定义点(图片)

项目上有使用到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';
			var map = new mapboxgl.Map({
				container: "map", // 地图容器的ID
				style: "mapbox://styles/mapbox/streets-v11", // 地图样式
				center: [0, 0], // 地图中心点坐标
				zoom: 1, // 地图缩放级别
			});

			map.on("load", function () {
				// 自定义图片的ID
				var customImageId = "custom-marker";

				// 加载自定义图片
				map.loadImage(
					"https://p9-passport.byteacctimg.com/img/mosaic-legacy/3797/2889309425~90x90.png",
					function (error, image) {
						if (error) throw error;

						// 添加自定义图片到Mapbox
						map.addImage(customImageId, image);

						// 添加图层,使用自定义图片作为点
						map.addLayer({
							id: "custom-marker-layer",
							type: "symbol",
							source: {
								type: "geojson",
								data: {
									type: "FeatureCollection",
									features: [
										{
											type: "Feature",
											geometry: {
												type: "Point",
												coordinates: [0, 0], // 点的坐标
											},
										},
										{
											type: "Feature",
											geometry: {
												type: "Point",
												coordinates: [116, 39], // 点的坐标
											},
										},
									],
								},
							},
							layout: {
								"icon-image": customImageId,
								"icon-size": 0.5, // 图片大小
							},
						});
					}
				);
			});
		</script>
	</body>
</html>