[GIS] Openlayers 3 – Zoom to Selected Feature (Polygon)

openlayers

I have an ol.source.ServerVector with several polygons drawn as features. I'd like for the map to zoom to the extent of the selected polygon upon selection, but I'm hitting a wall.

I was able to find this post that helped with zooming to all of the features in the source, but not the selected feature specifically

https://stackoverflow.com/questions/23682286/zoomtoextent-openlayers-3

var extent = source.getExtent();
map.getView().fitExtent(extent,map.getSize());

That works great to zoom to all of my polygons, but I can't seem to find any way to only use the selected feature's extent.

Best Answer

if(this.array_.length){
    var extent = this.array_[0].getGeometry().getExtent();
    map.getView().fitExtent(extent,map.getSize());
}

This is inside of an on.('change:length') function, so the 'this' is the selected collection. It might not be the "correct" way to do it, but it seems to be working as desired, so hopefully this helps someone out down the line.

Related Question