` 元素:
html<div id="marker-icon" style="background-color: red; width:20px; height:20px;"></div>
<div id="circle-icon" style="background-color: blue; border-radius:50%; width:40px; height:40px;"></div>
<div id="polygon-icon" style="background-color: green; width:60px; height:60px;"></div>
**绑定事件**
接下来,我们需要绑定一个事件,用于监听下拉框选项的变化。可以使用以下代码添加一个事件监听器:
javascriptconst select = document.getElementById('icon-select');
select.addEventListener('change', (e) => {
const value = e.target.value;
// 根据选择的值显示相应的图标});
**根据下拉框选项显示图标**
最后,我们需要根据下拉框选项的变化,动态地改变图标的类型和位置。可以使用以下代码实现这一功能:
javascriptconst map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
center: [0,0],
zoom:2 })
});
select.addEventListener('change', (e) => {
const value = e.target.value;
switch (value) {
case 'marker':
map.addLayer(new ol.layer.Vector({
source: new ol.source.Vector({
features: [
new ol.Feature({
geometry: new ol.geom.Point([0,0]),
properties: {
name: 'Marker'
}
})
]
}),
style: (feature) => {
return new ol.style.Style({
image: new ol.style.Icon({
src: 'marker-icon',
scale:1 })
});
}
}));
break;
case 'circle':
map.addLayer(new ol.layer.Vector({
source: new ol.source.Vector({
features: [
new ol.Feature({
geometry: new ol.geom.Circle([0,0],100),
properties: {
name: 'Circle'
}
})
]
}),
style: (feature) => {
return new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'red',
width:2 }),
fill: new ol.style.Fill({
color: 'rgba(255,0,0,0.5)'
})
});
}
}));
break;
case 'polygon':
map.addLayer(new ol.layer.Vector({
source: new ol.source.Vector({
features: [
new ol.Feature({
geometry: new ol.geom.Polygon([
[[-100, -100], [100, -100], [100,100], [-100,100], [-100, -100]]
]),
properties: {
name: 'Polygon'
}
})
]
}),
style: (feature) => {
return new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'blue',
width:2 }),
fill: new ol.style.Fill({
color: 'rgba(0,0,255,0.5)'
})
});
}
}));
break;
}
});
通过以上代码,我们可以实现一个动态地根据下拉框选项改变图标类型和位置的 OpenLayers 地图示例。