5

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
  • 639
  • 4
  • 11
  • 22

1 Answers1

6
  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

geocodezip
  • 158,664
  • 13
  • 220
  • 245
  • 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! – kduan Mar 09 '13 at 16:58
  • 1
    Look at my [working example](http://www.geocodezip.com/v3_simpleMap_layers.html), that works (at least in Chrome). – geocodezip Mar 09 '13 at 17:05
  • Here is a previous question that deals with checking the change of check boxes http://stackoverflow.com/questions/4471401/getting-value-of-html-checkbox-from-onclick-onchange-events also I think I remember seeing that cloud coverage doesn't show under a certain zoom level? – Rafe Mar 09 '13 at 17:08