Leaflet Automatically reload layer with updated time in URL Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Leaflet Automatically reload layer with updated time in URL without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have a Leaflet map that shows a rain radar overlay for Australia.

The map correctly loads and shows the latest rain radar however I want it to automatically update every 10 minutes without reloading the entire page. I tried using setUrl on the layer but that did not work. I have included a JSFiddle of my working map without automatic reload.

I define the layer with:

var RainRadarAus = L.tileLayer('https://api.weather.bom.gov.au/v1/rainradar/tiles/{time}/{z}/{x}/{y}.png', {
  attribution: 'Rain data © Bureau of Meteorology',
  time: getRadarTime(),
  maxZoom: 10,
  minZoom: 5,
  tileSize: 256,
})

I use this function to get the time argument

function getRadarTime() {
  d = new Date();
  d.setTime((Math.trunc(d.valueOf() / 600000) * 600000) - 600000);
  console.log(d.toString());
  return d.getUTCFullYear().toString() + (d.getUTCMonth() + 1).toString().padStart(2, '0') + d.getUTCDate().toString().padStart(2, '0') + d.getUTCHours().toString().padStart(2, '0') + d.getUTCMinutes().toString().padStart(2, '0');
}

I want to reload the layer and get a new time value from getRadarTime every 10 minutes.

JSFiddle: https://jsfiddle.net/ghLzykqx/

Thanks

Answer

You can use setInterval to create a timer which is called every x milliseconds. And then you need to update the tile options time and redraw it:

// MINUTES * SECONDS * MILLISECONDS
var TIME = 10 * 60 * 1000
setInterval(function(){
    RainRadarAus.options.time = getRadarTime();
    RainRadarAus.redraw();
}, TIME);
We are here to answer your question about Leaflet Automatically reload layer with updated time in URL - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji