Search code examples
javascriptopenlayers

OpenLayers http refresh callback function


Here's a stripped down version of my code that reloads a KML file every 2 seconds. On each update, I want to have the camera pan to the layer's feature's extent but I can't figure out where to set the callback.

//set up ajax    
var protocol = new OpenLayers.Protocol.HTTP({
    url: "feed.kml",
    format: new OpenLayers.Format.KML(),
    callback: function(){
        alert("here"); //never called
    }
});

//create refresher
var refresh = new OpenLayers.Strategy.Refresh({force: true, active: true});

//create layer for kml
var trackLayer = new OpenLayers.Layer.Vector("KML", {
    strategies: [new OpenLayers.Strategy.Fixed(), refresh],
    protocol: protocol,
});

//add to map
map.addLayer(trackLayer);

//refresh the kml every 2 seconds
setInterval(function(){
    refresh.refresh();      
    //pan to extent
    map.panTo(trackLayer.getDataExtent().getCenterLonLat());
},2000);

the problem is that this line: map.panTo(trackLayer.getDataExtent().getCenterLonLat()); is being called before the request is finished.

Here's the docs:


Solution

  • Nvm I got it. I feel stupid for not figuring this out faster.

    //zoom callback
    trackLayer.events.register("featuresadded",trackLayer,function(){
        var bounds = trackLayer.getDataExtent();
        if(bounds){ map.panTo(bounds.getCenterLonLat()); }
    });