[GIS] OpenLayers 3 – zoom to a selected feature

openlayers

I am working with OpenLayers 3. I used a dropdown menu to select a feature and I would like to zoom to the extent of the selected feature. At the moment, it is possible to select by the dropdown menu but not to zoom. Is there any way to fix this?

    function selectByDivision(){ 
            var divisionUser = document.getElementById('division-select').options[document.getElementById('division-select').selectedIndex].text;


            var selectedFeatures = select.getFeatures();                                
            selectedFeatures.clear();               
            var features = lyr_divisions3857.getSource().getFeatures();

            if(features){
                  for(i=0;i<features.length;i++){
                                            if(features[i].get('DIVISION')==divisionUser){                                              

                                                        feature= features[i];                                                                                                                   
                                                        selectedFeatures.push(feature);                                                             
                                                                                                                                                                                //map.zoomToExtent(features[i].getDataExtent());

                                                        var polygon = selectedFeatures.getFeatures();
                                                        var extent = polygon.getGeometry();

                                                        var size = (map.getSize());
                                                        view.fit(
                                                        extent,
                                                        size
                                                        );

                                                        map.getView().fit(extent, map.getSize());                                                                                                               
                                                        }
                                                    }                                                                           
                            }                                                                                                                                           
                        }       

Best Answer

Using fit will set the view of the map to fit the geometry being used.

map.getView().fit(feature.getGeometry(), map.getSize())