跳到主要内容
版本:9.1.0

设置图层要素状态

show

设置图层要素状态。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src='https://delivery.mapmost.com/cdn/sdk/webgl/v9.1.0/mapmost-webgl-min.js'></script>
<style>
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script type="module">
var map = new mapmost.Map({
container: 'map',
style: '<your style url>',
center: [120.71, 31.3306711],
zoom: 13,
userId: '***', // 授权码
});
async function addObjectIdForFeatures(){
let features = []
let res = await fetch('./buildings.geojson')
let result = await res.json()
for (let i = 0; i < result.features.length; i++) {
let id = result.features[i].properties.objectid
result.features[i]['id'] = id
features.push(result.features[i])
}
result.features = features
return result
}

addHoverLayers()

async function addHoverLayers() {
let data = await addObjectIdForFeatures()
map.on('load',function(e) {
map.addSource('source', {
type: 'geojson',
data: data
})
map.addLayer({
'id': 'building',
'type': 'fill',
'source': 'source',
'paint':{
'fill-color': '#FF3D68',
'fill-opacity':[
'case',
['boolean', ['feature-state','hover'], false],
1,
0.5
]
},
});
map.addLayer({
'id': 'borders',
'type': 'line',
'source': 'source',
'paint':{
'line-color': '#FAAD80',
'line-width': 1
}
});

// hover效果实现
let selectedBuildingId = null;
map.on('mousemove','building', (e) => {

if(e.features.length>0) {
if(selectedBuildingId !==null) {
map.setFeatureState(
{source: 'source', id: selectedBuildingId},
{hover: false}
);
}
selectedBuildingId = e.features[0].id;
map.setFeatureState(
{source: 'source', id: selectedBuildingId},
{hover: true}
);
}
});
map.on('mouseleave', 'building', ()=>{
if(selectedBuildingId !==null) {
map.setFeatureState(
{source: 'source', id: selectedBuildingId},
{hover :false}
);
}
selectedBuildingId =null;
});
});
}
</script>
</body>
</html>