Google maps API with tabs needs double click when returning to the map tab

Viewed 463

I'm a beginner with Javascript, and I am trying to deal with the API of Google maps.

I have two tabs, one with a map. When I open the page, the map loads, everything ok. But if I go to the other tab, and return, the map doesnt load. If I double click on the map, it loads normally. I have been reading some posts, like Google maps in hidden div, but no results.

My HTML is:

<head>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAxuujeWPQQygBjre-AD3U8p_tLNZgdw-4" async defer></script>
</head>
<body onload="initMap()">
    <main id="main">
        <section id="tabs">
            <ul>
                <li><a href="#tab1" onclick="initMap()">Map tab</a></li>
                <li><a href="#tab2">Tab for test</a></li>
            </ul>
            <section id="tab1">
                <section style="position: relative; width: 500px; padding-top: 500px; overflow: hidden;">
                    <div style="position: absolute; top: 0px; width: 500px; height: 500px;">
                        <div id="map" style="height:500px;"></div>
                    </div>
                </section>
            </section>
            <section id="tab2">
                <div>
                    Tab for testing
                </div>
            </section>
        </section>
    </main>
    <script>

    </script>
</body>

And my scripts, for Google Maps:

<script>
    var map;
function initMap() {
    var styleArray = [
        {
            featureType: 'all',
            stylers: [
                { saturation: -80 }
            ]
        },{
            featureType: 'road.arterial',
            elementType: 'geometry',
            stylers: [
                { hue: '#00ffee' },
                { saturation: 50 }
            ]
        },{
            featureType: 'poi.business',
            elementType: 'labels',
            stylers: [
                { visibility: 'off' }
            ]
        }];
        // Coordinates
        var coord = {lat: <?php echo '40.689095'; ?>, lng: <?php echo '-74.044640'; ?>};
        // Icon
        var imagen2 = "img/img_web/marker2.png";
        //Create map
        map = new google.maps.Map(document.getElementById('map'), {
            center: coord,
            zoom: 13,
            styles: styleArray
        });
        var markerZ = new google.maps.Marker({icon: imagen2, map: map, position: coord});
    };  
</script>

Script for tabs:

<script>
    $(function() {
        $( "#tabs" ).tabs({
            activate:function(event,ui){
                localStorage.setItem("lastTab",ui.newTab.index() );
            },
            active: localStorage.getItem("lastTab") || 0
        });
    }); 
</script>

Does anybody know what I am doing wrong?

N.

2 Answers
Related