openlayersopenlayers-5

How to update an XYZ layer in Open Layers 5


Is removing and re-adding an XYZ layer the only way to update it in ol5?

I know TileWMS has an updateParams() method, which is nice, but some of the layers I'm working with are XYZ with a time query parameter.

Here is the pseudo code for how I've worked around it, but it doesn't seem like the right way to go about it.

function createLayer() {
    return new TileLayer({
        source: new XYZ({
            url: 'https://url?x={x}&y={y}&z={z}&time=' + dateTimeString,
        })
    });
}
map.addLayer(createLayer());
// user interaction to change the time
map.removeLayer(createLayer());
map.addLayer(createLayer());

Solution

  • This method can be used either as a dummy parameter to override caching or to set a configurable time parameter on sources such as weather maps:

    var layer = new TileLayer({
                source: new XYZ()
            });
    function setTileUrl(dateTime) {
        layer.getSource().setUrl('https://url?x={x}&y={y}&z={z}&time=' + dateTime);
    }
    setTileUrl(initialDateTime);
    map.addLayer(layer);
    // user interaction to change the time
    setTileUrl(newDateTime);