Stefan
Stefan

Reputation: 12360

How to add custom leaflet error handler for open streat map timeouts?

For a few hours I got timeout errors and parts of the map were blue.

enter image description here Also see

OpenStreetMap often sends Gateway Timeout error

https://forum.openstreetmap.org/viewtopic.php?id=68026

The issue seams due to be caused by some OSM server and not due to my code.

What is the recommended way to handle that (temporal) issue? I would like to

A manual way to check the availability could be to fetch some tile image like https://tile.openstreetmap.org/8/136/85.png and check how long it takes to get it.

Does leaflet already provide some build in solution/API function for layer error handling?

Upvotes: 2

Views: 1385

Answers (1)

Stefan
Stefan

Reputation: 12360

A. There is a Fallback plugin: https://github.com/ghybs/Leaflet.TileLayer.Fallback

B. For manual handling of tile errors also see here:

https://gis.stackexchange.com/questions/347646/specify-an-alternative-url-for-a-tilelayer-to-use-in-leaflet

When tile load error happens, Leaflet fires tileerror event. In case of event handling function, event parameter has properties tile and coords, which can be used to fire tile load from secondary url.

var url1 = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var url2 = 'http://{s}.tile.osm.org/{z}/{x}/{y}.png';
var url2s = 'abc';

var map = L.map('map').setView([37.8, -96], 4);

var myLayer = L.tileLayer(url1, {maxZoom: 18}).addTo(map);

function handleTileError(evt) {
  if (evt.tile._hasError) return;

  var si = Math.floor((Math.random() * 3));
  var tileSrc = url2.replace(/{s}/g, url2s.substring(si, si + 1));
  tileSrc = tileSrc.replace(/{x}/g, evt.coords.x);
  tileSrc = tileSrc.replace(/{y}/g, evt.coords.y);
  tileSrc = tileSrc.replace(/{z}/g, evt.coords.z);
  evt.tile._hasError = true;
  evt.tile.src = tileSrc;
};

myLayer.on('tileerror', handleTileError);

Upvotes: 3

Related Questions