[GIS] Redraw/Refresh WMS layer in Leaflet

leafletwms

I have a WMS layer in my leaflet map:

var wmsLayer = L.tileLayer.wms('http://localhost:8080/geoserver/volonteri/wms?', {
            layers: "trgovine",
            transparent: true,
            format: 'image/png'
        }).addTo(map);

In backend, there is a simple PHP script that stores new points into PostGIS table which is served via geoserver as WMS.

I use an AJAX request to send data to backend PHP script. I need to refresh the layer after successful insert to draw the new point on map, but cannot find any method for refreshing. The code looks like this:

$.ajax({
        type: 'POST',
        url: 'http://localhost:8000/api/trgovina',
        data: { 
            'name': name,
            'shop': shop,
            'geom': geometry
        },
        success: function(){
            /* Redraw/refresh/reload should go here */
        }
    });

How can I solve this? I remember the older versions of openlayers had something simple like .redraw() method, but I'm pretty new to leaflet.

Best Answer

Let me quote from the Leaflet API documentation, about methods for L.TileLayer.WMS:

setParams(<Object> params, <Boolean> noRedraw?)

Merges an object with the new parameters and re-requests tiles on the current screen (unless noRedraw was set to true).

After this moment of RTFM, you should try to simply

wmsLayer.setParams({});

or even

wmsLayer.setParams({}, false);

That makes Leaflet tell the browser to re-request the tiles. But if the tile URLs are actually the same, your web browser might pull the tiles from its cache instead of re-requesting the tiles to the WMS server.

If this is the case, you might want to use some form of cache busting, e.g. adding an ever-changing fake WMS parameter:

wmsLayer.setParams({ wmsParameterThatDoesntExist: Date.now() }, false);

If you do implement cache busting, be aware that this can negatively affect performance, specially if you expect lots of concurrent clients.