OpenLayers 2 tiene estos eventos de capa "loadstart & loadend".
¿Qué es equivalente a ellos en OpenLayers 3?
Mientras una capa vectorial se carga y se representa, debo mostrar un icono de carga.
OpenLayers 2 tiene estos eventos de capa "loadstart & loadend".
¿Qué es equivalente a ellos en OpenLayers 3?
Mientras una capa vectorial se carga y se representa, debo mostrar un icono de carga.
Suponiendo que uses un ol.layer.Vector
con un ol.source.GeoJSON
, puedes usar algo como esto:
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
}
});
Esto muestra cómo obtener una notificación cuando se carga la fuente vectorial. Solo funciona con fuentes heredadas de ol.source.StaticVector
. Los ejemplos incluyen ol.source.GeoJSON
y ol.source.KML
.
Además, tenga en cuenta que es posible que este código ya no funcione en el futuro, cuando ol3 proporcionará una forma coherente de saber si / cuando se carga una fuente.
En ol3 versión 3.10.0 las cosas han cambiado. Así que es más claro que las versiones anteriores, pero aún más complicado que el ol2.
Por lo tanto, para las capas TILE (ol.layer.Tile), su recorte de código debería tener el siguiente aspecto:
//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';
});
mientras que para las capas WMS el enfoque es un poco diferente:
//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';
});
Para las capas vectoriales WFS, las cosas son aún más complicadas:
//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>";
}
revisa esta publicación. tiene todo lo anterior + un violín para las capas vectoriales WFS
No he encontrado la clase ol.source.GeoJSON
y no pude encontrar un caso donde vectorSource.getState() != 'ready'
. Así que terminé haciendo algo como esto:
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);
});
también puede usar la función 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();
}
});
}
En OL 4.5.0, para capas vectoriales no he encontrado una manera de tratar con la fuente, en lugar de eso, uso lo siguiente en los eventos de capa:
if (layer instanceof ol.layer.Vector) {
layer.on("precompose", function () {
$("#ajaxSpinnerImage").show();
});
layer.on("render", function () {
$("#ajaxSpinnerImage").hide();
});
}
Espero que pueda ayudar.
Lea otras preguntas en las etiquetas layers openlayers events loading