简体   繁体   中英

Difficulty changing style of google map on button click

So I have a map using the google map api and I'm trying to change the water color on a button click. I've been struggling with this one for a while now.

I initialised the map variable outside of the initMap function but that didn't seem to change anything.

    var map;
    function initMap() {

        var map = new google.maps.Map(document.getElementById('map'), {

            center: {              
                lat: 40.674,
                lng: -73.945               
            },
            zoom: 12,
            styles: [
                {
                    featureType: 'water',
                    elementType: 'geology',
                    stylers: [{color: '#17263c'}]
            }
            ]               
        });         
    }

    function showTest() {

        var myStyle =[{
            featureType: 'water',
            elementType: 'geometry',
            stylers: [
                { color: '#fc0101' }
            ]
        }];

    map.setOptions({styles: myStyle});
    }

Even though you initialised a map variable outside your initMap function, the fact you then declare a map variable inside that function prefixed with var , makes it local to just that function.

Change that to:

 function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM