点击多边形显示信息
当用户点击多边形时,显示包含更多信息的弹出窗口;
<!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>
<style>
.maplibregl-popup {
max-width: 400px;
font: 12px/20px 'Helvetica Neue', Arial, Helvetica, sans-serif;
}
</style>
<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.04, 38.907],
zoom: 3
});
map.on('load', () => {
// 为州级区划多边形添加数据源
map.addSource('states', {
'type': 'geojson',
'data': 'https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_110m_admin_1_states_provinces_shp.geojson'
});
// 添加一个显示州级区划多边形的图层
map.addLayer({
'id': 'states-layer',
'type': 'fill',
'source': 'states',
'paint': {
'fill-color': 'rgba(200, 100, 240, 0.4)',
'fill-outline-color': 'rgba(200, 100, 240, 1)'
}
});
// 当点击states图层上的要素时,在点击位置打开一个弹出窗口,
// 显示其属性中的HTML描述
map.on('click', 'states-layer', (e) => {
new maplibregl.Popup()
.setLngLat(e.lngLat)
.setHTML(e.features[0].properties.name)
.addTo(map);
});
// 当鼠标悬停在states图层上时,将鼠标指针更改为指针
map.on('mouseenter', 'states-layer', () => {
map.getCanvas().style.cursor = 'pointer';
});
// 当鼠标离开时,将其改回默认值
map.on('mouseleave', 'states-layer', () => {
map.getCanvas().style.cursor = '';
});
});
</script>
</body>
</html>