[GIS] Zoom to extent of ajax-loaded vector layer in OpenLayers 3

openlayers

I'm loading GeoJSON-data as result from a query to a PostGis-database via AJAX. The feature show up on the map, but I cannot get my map to center on the loaded feature.

var myLayer = new ol.layer.Vector ... // from returned GeoJSON

searchResults.setLayers(new ol.Collection([myLayer]));  // add the layer to a layergroup which is already bound to the map
myLayer.setVisible(true);  // the layer shows up keeping the initial mapview
var extent=parzellen.getSource().getExtent();
alert (extent);  // at this point alert shows me Infinity,Infinity,-Infinity,-Infinity
map.getView().fit(extent, map.getSize());  // this never happens

As shown in the code, propbably due to the fact, that myLayer is called via AJAX the code is executed before the source is completely loaded. Therefore alert(extent) returns Infinity,…

I found, that I have to wait until the source is ready. But in my case this isn't working and the layer doesn't show anymore on the map?

   myLayer.on('change',function(e){
      if(myLayer.getSource().getState() === 'ready') {
        if(myLayer.getSource().getFeatures().length>0) {
          searchResults.setLayers(new ol.Collection([myLayer]));
          myLayer.setVisible(true); 
          map.getView().fit(myLayer.getSource().getExtent(), map.getSize());
        }
      }
    });

Best Answer

I found the following solution here in a post :

parzellen.addEventListener("change", function(event) {
    map.getView().fit(parzellen.getSource().getExtent(), (map.getSize()));
}); 

This did the trick.

Without knowing why in all other cases parzellen.getSource().getExtent() returned Infinity,.. ?

Related Question