创建悬停效果
使用事件和特性状态创建每个要素的悬停效果;
<!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: [-100.486052, 37.830348],
zoom: 2
});
let hoveredStateId = null;
map.on('load', () => {
map.addSource('states', {
'type': 'geojson',
'data':
'https://maplibre.org/maplibre-gl-js/docs/assets/us_states.geojson'
});
// 基于特性状态的填充不透明度表达式将在特性的悬停状态设置为true时呈现悬停效果
map.addLayer({
'id': 'state-fills',
'type': 'fill',
'source': 'states',
'layout': {},
'paint': {
'fill-color': '#627BC1',
'fill-opacity': [
'case',
['boolean', ['feature-state', 'hover'], false],
1,
0.5
]
}
});
map.addLayer({
'id': 'state-borders',
'type': 'line',
'source': 'states',
'layout': {},
'paint': {
'line-color': '#627BC1',
'line-width': 2
}
});
// 当用户将鼠标移到state-fill图层上时,我们将更新鼠标下方特性的状态
map.on('mousemove', 'state-fills', (e) => {
if (e.features.length > 0) {
if (hoveredStateId) {
map.setFeatureState(
{source: 'states', id: hoveredStateId},
{hover: false}
);
}
hoveredStateId = e.features[0].id;
map.setFeatureState(
{source: 'states', id: hoveredStateId},
{hover: true}
);
}
});
// 当鼠标离开state-fill图层时,更新之前悬停特性的状态
map.on('mouseleave', 'state-fills', () => {
if (hoveredStateId) {
map.setFeatureState(
{source: 'states', id: hoveredStateId},
{hover: false}
);
}
hoveredStateId = null;
});
});
</script>
</body>
</html>