5

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.

1

1 Answer 1

7
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.

4
  • 1
    This did help me! But a little update, in ol.Collection, you should interact with the internal array via the getters, ie: getLength() and item(0). Also, OL has consolidated fitExtent and fitGeometry with fit, so just use that on either the geometry or extent.
    – janechii
    Commented Jul 10, 2016 at 1:02
  • fitExtent is deprecated. use view.fit() instead.
    – AdamAL
    Commented Jan 9, 2017 at 9:57
  • @AdamAL : Just like @ janechii has already commented on Jul 10 '16.
    – ndsmyter
    Commented Jan 9, 2017 at 10:00
  • I suppose I lack reading skills. I missed that. But then again maybe I missed it due to over-verbosity.
    – AdamAL
    Commented Jan 9, 2017 at 10:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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