3

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.

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

  • 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 Jul 10 '16 at 1:02
  • fitExtent is deprecated. use view.fit() instead. – AdamAL Jan 9 '17 at 9:57
  • @AdamAL : Just like @ janechii has already commented on Jul 10 '16. – ndsmyter Jan 9 '17 at 10:00
  • I suppose I lack reading skills. I missed that. But then again maybe I missed it due to over-verbosity. – AdamAL Jan 9 '17 at 10:29

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.