How to preload leaflet tiles of known borders in the browser cache for faster display?

I am developing a web application that displays animated markers on a flyer map. The map is scaled programmatically to the first borders of the animation, then the animation is played, then the map is scaled to the second borders of the animation, and the second animation is played, and so on ...

My problem is that the loading time of OpenStreetMap fragments sometimes exceeds the duration of the animation, so the map partially loads or even does not load when the marker animation reaches its end.

As I know from the very beginning all the borders that I'm going to increase, I would like to make ajax calls to download all the useful tile images in advance (before any animation starts) to make sure that they are in the browser cache when I need them.

I searched a lot, and I did not find a way to get a list of tile URLs from the borders of the Flyer. Is there a way to manually load tiles into the browser cache for known boundaries and zoom level?

SOLUTION thanks to YaFred answer:

Here is the code to preload the fragments around "mypolyline" with a 20% fill:

var bounds = mypolyline.getBounds().pad(0.2); var zoom = map.getBoundsZoom(bounds); var east = bounds.getEast(); var west = bounds.getWest(); var north = bounds.getNorth(); var south = bounds.getSouth(); var dataEast = long2tile(east, zoom); var dataWest = long2tile(west, zoom); var dataNorth = lat2tile(north, zoom); var dataSouth = lat2tile(south, zoom); for(var y = dataNorth; y < dataSouth + 1; y++) { for(var x = dataWest; x < dataEast + 1; x++) { var url = 'https://a.tile.openstreetmap.fr/osmfr/' + zoom + '/' + x + '/' + y + '.png'; var img=new Image(); img.src=url; } } 

He combines his two answers. When the animation works, I can now preload the tiles for the next one. It works fantastic.

+7
caching browser-cache preload openstreetmap leaflet
source share
1 answer

There are two questions in one:

1 / How to preload tiles?

Tiles are images. You just need to create a link to these images. See JavaScript Preloads

2 / What tiles do you need to load when you know the boundaries?

Take a look at https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames

I have prepared an example here that should be useful. It preloads tiles from the next zoom level when moving the map: https://yafred.imtqy.com/leaflet-tests/20170311-preloading-tiles/

First, it calculates which tiles you need for each corner of your borders using the following code:

 function long2tile(lon,zoom) { return (Math.floor((lon+180)/360*Math.pow(2,zoom))); } function lat2tile(lat,zoom) { return (Math.floor((1-Math.log(Math.tan(lat*Math.PI/180) + 1/Math.cos(lat*Math.PI/180))/Math.PI)/2 *Math.pow(2,zoom))); } 

then it calculates which tiles are inside the borders.

+6
source share

All Articles