Search code examples
openlayersopenlayers-5

Having openlayers load data from layer with visible = false


I have a Vector Layer with a Vector Source that is very expensive to load, but not so expensive to render. I have a button im my GUI to toggle the visibility of the layer. The problem is, the first time the visibility is set to true, the loading takes a long time. I would like to load the data for the layer in advance while the rest of the data is loaded (from all the visible layers), so that when the visibility is set to true, it only has to render it. Is that possible in Openlayers?

I tried various stuff like setting the visibility to true on 'precompose' and then setting it to false after the HTTP request has been sent (with a custom 'loadend' event), but I couldn't get it to work properly; I couldn't switch the layer off anymore. I guess that happened because after the first time loading, it had the data cached, so my custom 'loadend' event didn't fire anymore. Anyway I would favour a more elegant solution.

Edit: I can't just send the request beforehand as in Mikes answer, because there is not the request. The request depends on the extent as well as the projection and thus is made in the loader function of the Vector Source.


Solution

  • If you want your layer to be loaded on the fly you have to make it visible, otherwise requests are not send. One way to have it work is to make the layer visible but prevent features drawing (return an empty style in your style function)

    var visible = false; // turn it to true to have the features drawn
    var vector = new ol.layer.Vector({
      source: new ol.source.Vector({
        // your source definition
      }),
      visible: true,
      style: function(feature, resolution) {
        if (!visible) {
          return [];
        } else {
          return your_style_for_the_feature;
        }
      }
    });
    

    The layer will be loaded and drawn but nothing will be visible as the features are not drawn. Just set visible to true to return your style in the style function and make the them drawn. You also have to tell the source it has to redraw using changed function:

    // Draw the layer
    visible = true;
    vector.getSource().changed();