How to enable and disable Google map layers using checkboxes?

I am trying to add toggeble traffic, cloud and weather layers to Google maps using checkboxes. However, when I try to do this, all the layers disappear regardless of whether the checkboxes have been checked or unchecked. I have 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 would 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>
+5
source share
1 answer
  • To use the weather layer, you need to enable it.
  • ( HTML-), ( , onload)
  • .
  • , setMap (map), setMap (null)

"":

    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);}
}

+6

All Articles