Usando gli eventi loadstart e loadend layer in OpenLayers 3?


Risposte:


19

Supponendo che tu usi un ol.layer.Vectorcon un ol.source.GeoJSONpuoi usare qualcosa del genere:

var vectorSource = new ol.source.GeoJSON({
  projection : 'EPSG:3857',
  url: 'http://examples.org/fearures.json'
});

var vectorLayer = new ol.layer.Vector({
  source: vectorSource
});

map.addLayer(vectorLayer);

// show loading icon
// ...

var listenerKey = vectorSource.on('change', function(e) {
  if (vectorSource.getState() == 'ready') {
    // hide loading icon
    // ...
    // and unregister the "change" listener 
    ol.Observable.unByKey(listenerKey);
    // or vectorSource.unByKey(listenerKey) if
    // you don't use the current master branch
    // of ol3
  }
});

Questo mostra come ottenere una notifica quando viene caricata l'origine vettoriale. Funziona solo con fonti ereditate da ol.source.StaticVector. Gli esempi includono ol.source.GeoJSONeol.source.KML .

Inoltre, si noti che questo codice potrebbe non funzionare più in futuro quando ol3 fornirà un modo coerente per sapere se / quando viene caricata un'origine.


Grande! Lo stavo cercando anch'io. Mi chiedo perché OL3 non lo includa ancora.
— Germán Carrillo,

Perché no vectorSource.once('change', function(e){...}?
— Jonatas Walker,

14

Nella versione 3.10.0 di ol3 le cose sono cambiate. Quindi è più chiaro delle versioni precedenti ma ancora più complicato di ol2.

Quindi, per i layer TILE (ol.layer.Tile) il codice snip dovrebbe apparire come:

//declare the layer
var osmLayer =  new ol.layer.Tile({
  source: new ol.source.OSM()
});
//asign the listeners on the source of tile layer
osmLayer.getSource().on('tileloadstart', function(event) {
//replace with your custom action
document.getElementById('tilesloaderindicatorimg').src = 'css/images/tree_loading.gif';
 });

osmLayer.getSource().on('tileloadend', function(event) {
//replace with your custom action
document.getElementById('tilesloaderindicatorimg').src = 'css/images/ok.png';
 });
osmLayer.getSource().on('tileloaderror', function(event) {
//replace with your custom action        
document.getElementById('tilesloaderindicatorimg').src = 'css/images/no.png';
 });

mentre per i livelli WMS l'approccio è leggermente diverso:

//declare the layer
var wmsLayer =   new ol.layer.Image({
source: new ol.source.ImageWMS({
  attributions: [new ol.Attribution({
    html: '© ' +
        '<a href="http://www.geo.admin.ch/internet/geoportal/' +
        'en/home.html">' +
        'National parks / geo.admin.ch</a>'
  })],
  crossOrigin: 'anonymous',
  params: {'LAYERS': 'ch.bafu.schutzgebiete-paerke_nationaler_bedeutung'},
  serverType: 'mapserver',
  url: 'http://wms.geo.admin.ch/'
})
});

//and now asign the listeners on the source of it
var lyrSource = wmsLayer.getSource();
  lyrSource.on('imageloadstart', function(event) {
  console.log('imageloadstart event',event);
  //replace with your custom action
  var elemId = event.target.params_.ELEMENTID;
  document.getElementById(elemId).src = 'css/images/tree_loading.gif'; 
  });

  lyrSource.on('imageloadend', function(event) {
   console.log('imageloadend event',event);
  //replace with your custom action
  var elemId = event.target.params_.ELEMENTID;
  document.getElementById(elemId).src = 'css/images/ok.png'; 
  });

  lyrSource.on('imageloaderror', function(event) {
   console.log('imageloaderror event',event);
  //replace with your custom action
  var elemId = event.target.params_.ELEMENTID;
  document.getElementById(elemId).src = 'css/images/no.png'; 
  }); 

Per i livelli WFS Vector le cose sono ancora più complicate:

//declare the vector source
sourceVector = new ol.source.Vector({
    loader: function (extent) {
        //START LOADING
        //place here any actions on start loading layer
        document.getElementById('laodingcont').innerHTML = "<font color='orange'>start loading.....</font>";
        $.ajax('http://demo.opengeo.org/geoserver/wfs', {
            type: 'GET',
            data: {
                service: 'WFS',
                version: '1.1.0',
                request: 'GetFeature',
                typename: 'water_areas',
                srsname: 'EPSG:3857',
                bbox: extent.join(',') + ',EPSG:3857'
            }
        }).done(loadFeatures)
            .fail(function () {
            //FAIL LOADING
            //place here any actions on fail loading layer
            document.getElementById('laodingcont').innerHTML = "<font color='red'>error loading vector layer.</font>";
        });
    },
    strategy: ol.loadingstrategy.bbox
});

//once we have a success responce, we need to parse it and add fetaures on map
function loadFeatures(response) {
formatWFS = new ol.format.WFS(),
sourceVector.addFeatures(formatWFS.readFeatures(response));
 //FINISH LOADING
document.getElementById('laodingcont').innerHTML = "<font color='green'>finish loading vector layer.</font>";
}

controlla questo post. ha tutto quanto sopra + un violino per i livelli vettoriali WFS


1
Benvenuto in GIS.SE! Potete per favore espandere la vostra risposta e fornire una breve sintesi dell'articolo a cui siete collegati e quale parte è rilevante per la risposta a questa domanda. In questo modo la risposta sarà in grado di aiutare le persone su questo sito, anche dopo la morte del link.
— Kersten,

scusa newby. fatto!!!!!!!!
— pavlos,

per verificare quale tipo di layer hai, ecco come lo fai per OL3 gis.stackexchange.com/a/140852/63141
— Daniël Tulp,

Questa dovrebbe essere la risposta migliore!
— joaorodr84,

1
Per favore, ragazzi OL .... BACIO ... BACIO ...
— Magno C

2

Non ho trovato la classe ol.source.GeoJSONe non sono riuscito a trovare un caso in cui vectorSource.getState() != 'ready'. Quindi ho finito per fare qualcosa del genere:

    function spin(active) {
        if (active) {
            // start spinning the spinner
        } else {
            // stop spinning the spinner
        }
    }

    // Toggle spinner on layer loading
    layer.on('change', function() {
        spin();
    });
    layer.getSource().on('change', function() {
        spin(false);
    });

pubblica anche la funzione di rotazione, sembra che tu li stia girando e non fermi la rotazione al termine del caricamento del livello
— Daniël Tulp,

1

puoi anche usare la funzione getState ()

if (source instanceof ol.source.Vector) {
        source.on("change", function () {
            //console.log("Vector change, state: " + source.getState());
            switch (source.getState()) {
                case "loading":
                    $("#ajaxSpinnerImage").show();
                    break;
                default:
                    $("#ajaxSpinnerImage").hide();
            }
        });
    }

Sto usando ol-v4.2.0. source.getState()ritorna sempre "pronto"
— himyata,

1

Su OL 4.5.0, per i livelli vettoriali non ho trovato il modo di gestire l'origine, invece utilizzo gli eventi sui livelli seguenti:

if (layer instanceof ol.layer.Vector) {
    layer.on("precompose", function () {
              $("#ajaxSpinnerImage").show();
            });
    layer.on("render", function () {
              $("#ajaxSpinnerImage").hide();
            });
}

Spero possa essere d'aiuto.

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.