Search code examples
leafletopenlayersfailoverwms

Is it possible with OpenLayers (or other way) to have a failover WMS source?


Our situation: The primary WMS provider is sometimes offline for various reasons. If they are offline all our solutions look horrible (no map, just pins on empty background). So we'd like to use OpenStreet Map as a failover for situations like this. We're using Open Layers and Leaflet (different frontends) and have Geoserver for some WFS services.

Would it be possible to use either of those (or anything else) to semi-automatically handle this? Or would we have to build our own WMS 'proxy' service? There we could of course detect that primary is down and the switch to failover. But even better if there is a built in way to do this.


Solution

  • There is a tileerrorevent on the tilelayer:https://leafletjs.com/reference-1.6.0.html#tilelayer-wms-tileerror

    You can check how many tiles are loaded / failed and then use the fallback TileLayer.

      var loaded = 0;
      var errors = 0;
      var fallbackloaded = false;
      osm.on('tileerror',function(e){
        errors++;
      });
      osm.on('tileload',function(e){
        loaded++;
      });
      osm.on('load',function(e){
        if(loaded == 0 || (errors != 0 && (loaded / errors) > 70)){ //More then 70% wrong
          console.log("WMS is down");
          if(!fallbackloaded){ //prevent infinit loop
            fallbackloaded =true;
            map.removeLayer(osm); //Remove old TileLayer
            osm = L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', {
              maxZoom: 17,
              attribution: 'Map data: &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            });
            map.addLayer(osm); //Add fallback TileLayer
          }
        }
      });
    

    Example: https://jsfiddle.net/falkedesign/r28zojgu/

    Also you can check on startup with JS if the url is reachable and then use the fallback layer.