Toggle Map Style and the Polygons Shown

In my previous Google Maps examples, I store all objects such as polygons and markers in an overlayArray.  Having a “global” theme change that doesn’t just alter the mapStyle, but also polygons is as simple as looping through your Array and setting options.   Here I’m using variable t1 to control the true/false variable, on a live site you should probably do something local such as adding a Class name to the button.

 

  var t1 = true;
    $("#toggle-theme").click(function(e) {
        e.preventDefault();
        if (t1) {
            t1 = false;
            map.setOptions({
                styles: mapstyleDefault
            });
            for (var i in overlayArray) {
                overlayArray[i].setOptions({
                    strokeColor: '#ff0000',
                    fillColor: '#ff0000',
                })
            }
        } else {
            t1 = true;
            map.setOptions({
                styles: mapstyleAlternate
            });
            for (var i in overlayArray) {
                overlayArray[i].setOptions({
                    strokeColor: '#29800b',
                    fillColor: '#29800b',
                })
            }
        }
    
    });

More Posts

Donate

Hey was this useful? Please consider tipping or subscribing as a member. Even just $1 or $5 can help me improve this content and keep it ad-free.