2016-08-12 71 views
0

我想爲selectInteraction激發select事件。這裏是我到目前爲止的代碼:OpenLayers 3 - SelectInteraction事件沒有激發

// create and instance of the selectInteraction 
var selectInteraction = new ol.interaction.Select({ 
    layers: myLayers 
}); 

// add select event handler 
// NOT BEING CALLED WHEN FEATURES ARE PUSHED TO SELECTED ARRAY 
selectInteraction.on("select", function (evt) { 

    var selected = evt.selected; 
    var deselected = evt.deselected; 

    selected.forEach(function(feature) { 
     feature.setStyle(myCustomStyleFunction); 
    }); 

    deselected.forEach(function(feature) { 
     feature.setStyle(null); 
    }); 


}, selectInteraction); 

// add the interaction to the map 
myMap.getInteractions().extend([ selectInteraction ]); 

// function called with feature to be selected 
function programmaticallySelectFeature(feature) { 

    // get the selectInteraction for the map 
    myMap.getInteractions().forEach(function (interaction) { 

     if (interaction instanceof ol.interaction.Select) { 
      selectInteraction = interaction; 
     } 

    }); 

    // push the feature to the selectInteraction 
    selectInteraction.getFeatures().push(feature); 

} 

我知道select事件不會在特徵推送到選定數組時觸發。否則,它按預期工作。那麼如何才能使這個工作?我可以聽另一個事件嗎?

回答

0

,你可以聽的事件或點擊地圖上singleclick,並推回功能在選擇的特徵:

map.on('click', function(evt){ 
    var feature = map.forEachFeatureAtPixel(evt.pixel, function(feature, layer) { 
     return feature; 
    }); 
    if(feature){ 
     selectInteraction.getFeatures().push(feature); 
    } 
}); 

這當然假設你想用一個點擊選擇功能