$conf, $runtime; function_exists('chdir') AND chdir(APP_PATH); $r = 'mysql' == $conf['cache']['type'] ? website_set('runtime', $runtime) : cache_set('runtime', $runtime); } function runtime_truncate() { global $conf; 'mysql' == $conf['cache']['type'] ? website_set('runtime', '') : cache_delete('runtime'); } register_shutdown_function('runtime_save'); ?>Google Maps API problem - initMap()|Programmer puzzle solving
最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

Google Maps API problem - initMap()

matteradmin10PV0评论

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=";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

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/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

Share Improve this question asked Dec 7, 2018 at 13:37 Piotr MuchaPiotr Mucha 231 silver badge4 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

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/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.

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far