[GIS] Leaflet WMS layer not working until zoomed

leafletwms

I created a toggle button to add and remove wms layer from the map. In the default zoom level, it is working fine. But when I remove layer and zoom in or out, then do "Add Layer", the layer does not show up until map is zoomed in or out.
I tried layer.refresh(), but no improvement. Below is my sample code.

var map = L.mapbox.map('map', 'examples.map-4l7djmvo').setView([24, -89], 5);
var mylayer =      L.tileLayer.wms("http://nowcoast.noaa.gov/wms/com.esri.wms.Esrimap/analyses", {
format: 'image/png',
transparent: true,
layers: 'NSSL_RAS_QPE_72HR'    
});

$('#Check').click(function() {    
   if($(this).text() == "Add Layer")            {
         $(this).text("Remove Layer"); 
         map.addLayer(mylayer); 
         mylayer.refresh();
       }
       else
           {
             $(this).text("Add Layer"); 
             map.removeLayer(mylayer);
              mylayer.refresh();
           }        
});

Best Answer

Just making a cursory glance you might try changing your function to this instead:

$(document).ready(function() {

   $('#Check').click(function() {    
      if($(this).text() == "Add Layer")            {
            $(this).text("Remove Layer"); 
            map.addLayer(mylayer); 
            mylayer.refresh();
          }
          else
              {
                $(this).text("Add Layer"); 
                map.removeLayer(mylayer);
                mylayer.refresh();
              }        
   });
});

Without the document ready part, you script is executed before the page is ever rendered. This can cause weird issues. From now on place any extra controls you make inside the document ready block.

Also, have your tried playing with Leaflet's layer control that is built in. Luckily, they have a nice tutorial for that. Makes it tidy and neat. But at the same time I am also not aware of your end goal.

Related Question