悬停显示弹出窗口
当鼠标悬停在地图要素上时显示弹出窗口;
<!DOCTYPE html>
<html lang="en">
<head>
<title>悬停显示弹出窗口</title>
<meta property="og:description" content="当鼠标悬停在地图要素上时显示弹出窗口" />
<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%; }
</style>
</head>
<body>
<div id="map"></div>
<script>
const map = new maplibregl.Map({
container: 'map',
style: 'https://api.maptiler.com/maps/streets/style.json?key=get_your_own_OpIi9ZULNHzrESv6T2vL',
center: [-77.04, 38.907],
zoom: 11.5
});
map.on('load', () => {
map.addSource('places', {
'type': 'geojson',
'data': {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'properties': {
'description':
'<strong>白宫</strong><p>美国总统的官邸和工作场所,建于1792年,是美国政治权力的象征。</p>'
},
'geometry': {
'type': 'Point',
'coordinates': [-77.0366, 38.8971]
}
},
{
'type': 'Feature',
'properties': {
'description':
'<strong>林肯纪念堂</strong><p>为纪念美国第16任总统亚伯拉罕·林肯而建,于1922年落成。</p>'
},
'geometry': {
'type': 'Point',
'coordinates': [-77.0503, 38.8893]
}
},
{
'type': 'Feature',
'properties': {
'description':
'<strong>美国国会大厦</strong><p>美国国会的所在地,建于1800年,是美国立法机构的象征。</p>'
},
'geometry': {
'type': 'Point',
'coordinates': [-77.0090, 38.8899]
}
},
{
'type': 'Feature',
'properties': {
'description':
'<strong>华盛顿纪念碑</strong><p>为纪念美国首任总统乔治·华盛顿而建,高169米,是世界上最高的石结构建筑。</p>'
},
'geometry': {
'type': 'Point',
'coordinates': [-77.0353, 38.8895]
}
},
{
'type': 'Feature',
'properties': {
'description':
'<strong>杰斐逊纪念堂</strong><p>为纪念美国第三任总统托马斯·杰斐逊而建,于1943年落成。</p>'
},
'geometry': {
'type': 'Point',
'coordinates': [-77.0366, 38.8813]
}
}
]
}
});
// 添加一个包含兴趣点的图层
map.addLayer({
'id': 'places',
'type': 'circle',
'source': 'places',
'paint': {
'circle-color': '#e25a5a',
'circle-radius': 6,
'circle-stroke-width': 1,
'circle-stroke-color': '#ffffff'
}
});
// 创建一个弹出窗口,但不将其添加到地图上
const popup = new maplibregl.Popup({
closeButton: false,
closeOnClick: false
});
// 当鼠标移入places图层时显示弹出窗口
map.on('mouseenter', 'places', (e) => {
// 更改鼠标样式为指针
map.getCanvas().style.cursor = 'pointer';
// 获取坐标和描述
const coordinates = e.features[0].geometry.coordinates.slice();
const description = e.features[0].properties.description;
// 确保在地图缩小到显示多个要素副本时,
// 弹出窗口出现在用户悬停的那个副本上
while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
}
// 在要素上显示弹出窗口
popup.setLngLat(coordinates).setHTML(description).addTo(map);
});
// 当鼠标离开places图层时移除弹出窗口
map.on('mouseleave', 'places', () => {
map.getCanvas().style.cursor = '';
popup.remove();
});
});
</script>
</body>
</html>