I do custom wordpress temple site with google maps script, and php code. I have problem with loading of it, they do not always work, sometimes i must refreshing site ten times until it starts to work.

If they do not work, I get an error

"initMap is not a function"

Code of my temple site:

<?php /* Template Name: Mapy */ ?>

<?php get_header(); ?>


<style>
    #colophon{
        display: none;
    }
    .page-template {
        background-color: black!important;
    }
    .gm-style-iw {
        height: 165px!important;
        width: 300px!important;
    }
</style>

<section style="padding-top:70px; padding-bottom:0px;">
    <div id="map" class="no-transition"></div>
    <div class="legend">
        <ul>
            <li>Wielki format</li>
            <li>Citylight</li>
            <li>Backlight</li>
        </ul>
    </div>
</section>

<?php 

    wp_enqueue_script( 'my-map-script', get_template_directory_uri() . '/js/my-map-script.js', array(), '1.0.0', true );

    $storeData = [];
    $args = array( 'post_type' => 'product');
    $loop = new WP_Query( $args );

    foreach ($loop->posts as $post){
        $storeData[] = [
            'title' => apply_filters('the_title', $post->post_title),
            'url' => get_permalink(),
            'num'   => get_field('numer_katalogowy'),
            'lat'   => get_field('gps_dlugosc'),
            'long'  => get_field('szerokosc_gps'),
            'surface'  => get_field('powierzchnia'),
            'height'  => get_field('dlugosc'),
            'width'  => get_field('szerokosc'),
            'light'  => get_field('oswietlenie'),
        ];
    }
    wp_localize_script('my-map-script', 'storeData', $storeData);
?>


<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAg-GBNbwLWCxiN-UI-0COkr1bgAKpXjQU&callback=initMap"></script>


<?php get_footer(); ?>

Code of my js file:

function initMap() {
  // The location of Uluru
    var poznan = {lat: 52.402684, lng: 16.9213905};
    var j = storeData.length;
    var infowindow = new google.maps.InfoWindow({
        maxWidth: 200
    });
    var marker, i;

    var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 15,
          center: poznan,
      }
    );

    for (i = 0; i < j; i++) {
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(storeData[i].lat, storeData[i].long),
            map: map
        });

        google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
                infowindow.setContent(
                    '<div class="marker-window-content">' +
                        '<h3>' + storeData[i].title + '</h3>' +
                        '<span>' + storeData[i].num + '</span>' +
                        '<p>' + 'Wysokość: ' + storeData[i].height + ' m'+ '</p>' +
                        '<p>' + 'Szerokość: ' + storeData[i].width + ' m'+ '</p>' +
                        '<p>' + 'Powierzchnia: ' + storeData[i].surface + ' m2'+ '</p>' +
                        '<p>' + 'Oświetlenie: ' + storeData[i].light + '</p>' +
                        '<a href="'+ storeData[i].url + '">' + 'Przejdź do powierzchni' + '</a>' +
                    '</div>'


                );
                infowindow.open(map, marker);
            }
        })(marker, i));
    }
}

I think the problem can be in script order, but i don't know how to resolve it. Adress of site where is problem:

My site

New contributor
Piotr Mucha is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

This part of the Google Maps script URL is the culprit:

&callback=initMap

It means that when the script is loaded it will attempt to run the initMap() function, but you're enqueueing your script that contains the function in the footer, after the Google Maps <script> tag, which you're outputting in the middle of the page. This means that your script won't be loaded before Google Maps attempts to run initMap().

You should enqueue the Google Maps script using wp_enqueue_script(), with your custom script as a dependency, to make sure they load in the right order.

So remove the <script> tag and add:

wp_enqueue_script( 
    'google-maps', 
    'https://maps.googleapis.com/maps/api/js?key=AIzaSyAg-GBNbwLWCxiN-UI-0COkr1bgAKpXjQU&callback=initMap',
    [ 'my-map-script' ],
    null,
    true
);

This will ensure that the Google Maps script will be loaded after your script, guaranteeing that the initMap() function will be available.

  • Great answer! Your solution work great! Thanks! – Piotr Mucha Dec 7 at 14:10
  • No problem. If it helped you can mark the answer as accepted to help let other users know that your question has an answer. – Jacob Peattie Dec 7 at 14:57

Your Answer

Piotr Mucha is a new contributor. Be nice, and check out our Code of Conduct.

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.