I have a function that allows me to change color to a selected feature in my layer's source. Within the same function I would like also to change the map view by zooming in to the selected feature extent.

Since I have different layers (with different sources) I have grouped first my layers and my sources

layers_group = [];
layers_group.push(layer_1, layer_2);

source_group = [];

My function is as follows:

(function($) {
//when clicking the select
document.getElementById("show_feature").addEventListener('click', function () {
//first step it loads the vector layer and sets the style to transparent
    var i;
    for (i = 0; i < layers_group.length; ++i){
//second step when the select changes (i.e. I make a choice)
    $("#show_feature").change(function() {
//it starts the function to change styles according to the selection made
        var selectedFeature = $("#show_feature").val();
        var index;
        for (index = 0; index < source_group.length; ++index){

    //if substring(selected text) exist within feature property('Region')
    //should return any value other than -1
                if (feat.get('Region').indexOf(selectedFeature)!=-1) {
                        //sets the style on the feature if it exists
                        //should zoom to the selected feature polygon
                        var extent = feat.getGeometry().getExtent();
                        map.getView().fitExtent(extent, map.getSize());

                } else {
                //and if it doesn't exist switch back to a transparent style - not visible

})( jQuery );

Everything works well except for the zooming, as I get a "TypeError: map.getView is not a function" and no zooming is performed.

Could somebody help me in solving this?


You should check map whether it has getView function.
and my suggestion about selecting feature and zooming is to use ol.interaction.Select.
select interaction with select event can do what you want.

// select interaction working on "click"
var selectClick = new ol.interaction.Select({
  condition: ol.events.condition.click


select.on('select', function(e) {
  var extent = e.target.getFeatures().getArray()[0].getGeometry().getExtent();

see codepen example here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.