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?

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

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

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.