How to turn Google maps layers on and off with check boxes?

10,154
  1. to use the weather layer you need to include the library
  2. to enable and disable layers in the global scope (where HTML click listeners run), your map needs to be global (define it outside of any functions, but initialize it in the onload event)
  3. you also need to define your layers in the global scope.
  4. to display a layer, use setMap(map), to hide it use setMap(null)

modified "check" function:

    function check() 
{

    if(document.getElementById('weather').checked)

      {weatherLayer.setMap(map);}

    else 

      {weatherLayer.setMap(null);}

    if(document.getElementById('clouds').checked)

      {cloudLayer.setMap(map);}

    else 

      {cloudLayer.setMap(null);}

    if(document.getElementById('traffic').checked)

       {trafficLayer.setMap(map);}

    else

       {trafficLayer.setMap(null);}
}

working example

Share:
10,154
kduan
Author by

kduan

Updated on June 13, 2022

Comments

  • kduan
    kduan almost 2 years

    I'm trying to add toggeble traffic, cloud and weather layers to Google maps using check boxes. However when I try to do so all of the layers disappear no matter if the boxes were checked or unchecked. I've never done anything like this in Javascript and I'm really new to Javascript so I have no idea what I'm doing wrong. Here is my code, any help will be great!

    Javascript:

            function check() 
        {
            var weatherLayer = new google.maps.weather.WeatherLayer({
            temperatureUnits: google.maps.weather.TemperatureUnit.FAHRENHEIT
            });
            var trafficLayer = new google.maps.TrafficLayer();
            var cloudLayer = new google.maps.weather.CloudLayer();
    
            if(document.getElementById('weather').checked)
    
            {weatherLayer.setMap(map);}
    
            else if(!document.getElementById('weather').checked)
    
            {weatherLayer.setMap(map);}
    
            cloudLayer.setMap(map);
    
            trafficLayer.setMap(map);
        }
    

    Html

            <label><input type="checkbox" id="weather" checked="checked" onclick="check()" />Weather</label>
            <label><input type="checkbox" id="clouds" onclick="check()" />Clouds</label>
            <label><input type="checkbox" id="traffic" onclick="check()" />Traffic</label>
    
  • kduan
    kduan about 11 years
    Thanks! I still have some problems with the map though. If I set the boxes to checked or unchecked in the code it runs fine, but when I hit the check box in a browser nothing changes. Do you know why this happens? Thanks!
  • geocodezip
    geocodezip about 11 years
    Look at my working example, that works (at least in Chrome).
  • Rafe
    Rafe about 11 years
    Here is a previous question that deals with checking the change of check boxes stackoverflow.com/questions/4471401/… also I think I remember seeing that cloud coverage doesn't show under a certain zoom level?