<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Add custom icons with Markers</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
<link href="https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.js"></script>
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>
</head>
<body>
<style>
.marker {
display: block;
border: none;
border-radius: 50%;
cursor: pointer;
padding: 0;
}
</style>
<div id="map"></div>
<script>
mapboxgl.accessToken =
'pk.eyJ1IjoibHh0aWFudGlhbiIsImEiOiJjaXd2ZjlkYnQwMTZvMnRtYWZnM2lpbHFvIn0.ef3rFZTr9psmLWahrqap2A';
const geojson = {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'properties': {
'message': 'Foo',
'iconSize': [60, 60]
},
'geometry': {
'type': 'Point',
'coordinates': [-66.324462, -16.024695]
}
},
{
'type': 'Feature',
'properties': {
'message': 'Bar',
'iconSize': [50, 50]
},
'geometry': {
'type': 'Point',
'coordinates': [-61.21582, -15.971891]
}
},
{
'type': 'Feature',
'properties': {
'message': 'Baz',
'iconSize': [40, 40]
},
'geometry': {
'type': 'Point',
'coordinates': [-63.292236, -18.281518]
}
}
]
};
const map = new mapboxgl.Map({
container: 'map',
// Choose from Mapbox's core styles, or make your own style with Mapbox Studio
style: 'mapbox://styles/mapbox/streets-v12',
center: [-65.017, -16.457],
zoom: 5
});
// Add markers to the map.
for (const marker of geojson.features) {
const box = document.createElement('div');
const textEl = document.createElement('div');
textEl.innerText = marker.properties.message;
textEl.style.color = 'red';
textEl.style.textAlign = 'center';
const img = document.createElement('div');
const width = marker.properties.iconSize[0];
const height = marker.properties.iconSize[1];
img.className = 'marker';
img.style.backgroundImage = `url(https://placekitten.com/g/${width}/${height}/)`;
img.style.width = `${width}px`;
img.style.height = `${height}px`;
img.style.backgroundSize = '100%';
box.appendChild(textEl);
box.appendChild(img);
box.addEventListener('click', () => {
window.alert(marker.properties.message);
});
// Add markers to the map.
new mapboxgl.Marker(box)
.setLngLat(marker.geometry.coordinates)
.addTo(map);
}
</script>
</body>
</html>
mapboxgl 添加带注记marker
最新推荐文章于 2024-07-22 20:33:56 发布
此代码示例展示了如何使用MapboxGLJS库在地图上添加自定义大小的图标标记。通过GeoJSON数据结构定义位置和图标尺寸,并使用JavaScript动态创建和添加标记。用户点击标记时会显示提示信息。
摘要由CSDN通过智能技术生成