2015-09-30 38 views
0

使用openlayer 3.3.0,我們有一個地圖分爲縣,每個縣是'功能',我想選擇一個功能並更改其邊框顏色,當我選擇另一個功能時,我希望先前選擇的功能恢復爲其原始樣式,並使新功能具有應用的選定樣式。OpenLayers 3(3.3.0)一次選擇一項功能

所以我用它來添加交互。

var select = new ol.interaction.Select({ 
      condition: ol.events.condition.click, 
     }); 
select.on('select', function(evt){ 
    var features = evt.target.getFeatures(); 
    features.forEach(function(feature){ 
     feature.setStyle(new ol.style.Style({ 
       stroke: new ol.style.Stroke({ 
        color: '#007aa9', 
        width: 1.5; 
       })) 
    } 
}) 
map.addInteraction(select); 

這一切工作正常,但它不會「取消選中」以前選擇的特徵,因此,如果我按一下週圍所有的功能得到了選擇風格

我似乎可以解決這個問題的唯一辦法是爲了設置'priorSelectedFeature'變量,並在'on'事件中重置它的樣式,但它看起來有點笨重,不應該有一種方法來檢測某個功能何時被「取消選擇」並重置其樣式?

回答

0

會出現解決方案可能是更新到版本3.4(它不工作在3.3),然後你可以訪問'選定'和'取消選擇'屬性。 所以我重構我的事件代碼爲

  select.on('select', function(evt){ 
       var selectedFeatures = evt.selected; 
       selectedFeatures.forEach(function(feature){ 
        feature.setStyle(new ol.style.Style({ 
         stroke: new ol.style.Stroke({ 
         color: '#007aa9', 
         width: 1.5; 
         })); 
       }); 
       var deselectedFeatures = evt.deselected; 
       deselectedFeatures.forEach(function(feature){ 
        feature.setStyle(new ol.style.Style({ 
         stroke: new ol.style.Stroke({ 
         color: '#000000', 
         width: 0.4; 
         }) 
        }) 
       }); 
      }); 

對還是錯?