Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 749
kduan Avatar asked Mar 09 '13 14:03

kduan


1 Answers

  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

like image 86
geocodezip Avatar answered Oct 02 '22 05:10

geocodezip