添加自定义标记
通过在GeoJSON点上使用HTML构造的标记图像添加自定义标记;
<!DOCTYPE html>
<html lang="en">
<head>
<title>添加自定义标记</title>
<meta property="og:description" content="通过在GeoJSON点上使用HTML构造的标记图像添加自定义标记" />
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel='stylesheet' href='https://unpkg.com/maplibre-gl@5.5.0/dist/maplibre-gl.css' />
<script src='https://unpkg.com/maplibre-gl@5.5.0/dist/maplibre-gl.js'></script>
<style>
body { margin: 0; padding: 0; }
html, body, #map { height: 100%; }
.marker {
background-image: url('https://maplibre.org/maplibre-gl-js/docs/assets/cat.png');
background-size: cover;
width: 50px;
height: 50px;
border-radius: 50%;
cursor: pointer;
}
.maplibregl-popup {
max-width: 200px;
}
.maplibregl-popup-content {
text-align: center;
font-family: 'Open Sans', sans-serif;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
const geojson = {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'properties': {
'message': '喵!',
'iconSize': [60, 60]
},
'geometry': {
'type': 'Point',
'coordinates': [-66.324462, -16.024695]
}
},
{
'type': 'Feature',
'properties': {
'message': '喵喵!!',
'iconSize': [50, 50]
},
'geometry': {
'type': 'Point',
'coordinates': [-61.21582, -15.971891]
}
},
{
'type': 'Feature',
'properties': {
'message': '喵喵喵!!!',
'iconSize': [40, 40]
},
'geometry': {
'type': 'Point',
'coordinates': [-63.292236, -18.281518]
}
}
]
};
const map = new maplibregl.Map({
container: 'map',
style: 'https://api.maptiler.com/maps/streets/style.json?key=get_your_own_OpIi9ZULNHzrESv6T2vL',
center: [-65.017, -16.457],
zoom: 5
});
// 为每个标记添加一个HTML元素
for (const marker of geojson.features) {
// 创建一个HTML元素作为自定义标记
const el = document.createElement('div');
el.className = 'marker';
el.style.width = `${marker.properties.iconSize[0]}px`;
el.style.height = `${marker.properties.iconSize[1]}px`;
// 在每个标记上添加弹出窗口
new maplibregl.Marker(el)
.setLngLat(marker.geometry.coordinates)
.setPopup(
new maplibregl.Popup({ offset: 25 }) // 添加弹出窗口
.setHTML(
`<h3>${marker.properties.message}</h3>`
)
)
.addTo(map);
}
</script>
</body>
</html>