關鍵
經過反複的實驗,成功的關鍵是利用select控件來改變樣式,同時要注意避免因select的注冊而鎖住地圖。
代碼
記住要用styleFunction來寫入樣式,同時注意不能單獨設定要素的樣式,一旦設定無法再轉換。
var select = new ol.interaction.Select({
condition: function(evt) {
return evt.originalEvent.type == 'mousemove'; //注冊事件
},
style: function(feature,resolution){
var geo = feature.getGeometry();
if(geo instanceof ol.geom.Point){
var style;
if(feature.get('id')){
style = new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5,1],
src: './position2.png'
}),
text: new ol.style.Text({
text:'1',
font:'normal normal bold 12px arial,sans-serif',
offsetY:-30,
fill:new ol.style.Fill({color:'#ffffff'})
})
});
}else{
style = new ol.style.Style({
image: new ol.style.Circle({radius:7, //填充圖案樣式
fill: new ol.style.Fill({color:'#ffcc33'})
})
});
}
return style;
}
if(geo instanceof ol.geom.LineString){
return new ol.style.Style({
stroke: new ol.style.Stroke({
color:'rgb(165,24,27)',
width:3,
lineDash:[10,10]
}) //邊界
});
}
if(geo instanceof ol.geom.Polygon || geo instanceof ol.geom.MultiPolygon){
return new ol.style.Style({
fill: new ol.style.Fill({color:'rgba(0,0,0,0.6)'}), //填充
stroke: new ol.style.Stroke({
color:'#a5181b',
width:3,
lineDash:[10,10]
}) //邊界
});
}
}
});
map.addInteraction(select);
var layer = new ol.layer.Vector({
source: olkit.searSource,
style: function(feature,resolution){
var geo = feature.getGeometry();
if(geo instanceof ol.geom.Point){
var style;
if(feature.get('id')){
style = new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5,1],
src: './position.png'
}),
text: new ol.style.Text({
text:'1',
font:'normal normal bold 12px arial,sans-serif',
offsetY:-27,
fill:new ol.style.Fill({color:'#ffffff'})
})
});
}else{
style = new ol.style.Style({
image: new ol.style.Circle({radius:7, //填充圖案樣式
fill: new ol.style.Fill({color:'#ffcc33'})
})
});
}
return style;
}
if(geo instanceof ol.geom.LineString){
return new ol.style.Style({
stroke: new ol.style.Stroke({
color:'#a5181b',
width:3
})
});
}
if(geo instanceof ol.geom.Polygon || geo instanceof ol.geom.MultiPolygon){
return new ol.style.Style({
fill: new ol.style.Fill({color:'#e6a299'}), //填充
stroke: new ol.style.Stroke({
color:'rgb(165,24,27)',
width:3,
lineDash:[10,10]
})
});
}
}
});
補充代碼
解決鎖屏的問題(借助地圖事件解決)
//事件:抓
map.on('pointerdrag',function(evt){
select.setActive(false);
});
//事件:地圖移動結束
map.on('moveend', function(evt) {
select.setActive(true);
});
2017.5更新
要實作不同條件下的選擇問題,可以借助多個select控件完成,map可以添加多個select,是以你想要什麼效果都可以
效果
觸碰前:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIyVGduV2QvwVe0lmdhJ3ZvwFM38CXlZHbvN3cpR2Lc1TPB10QGtWUCpEMJ9CXsxWam9CXwADNvwVZ6l2c052bm9CXUJDT1wkNhVzLcRnbvZ2LcZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39TNyEzN0ETNyIjMwETM2EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
觸碰後: