Integrating PHP into Javascript to display map markers with Google API - problem with wp_localize

I would display Google maps markers on custom site temple with Google API maps. I do everything like this post: Integrating PHP into Javascript to display map markers with Google API

But a console gives me an error, I don't know where I can look for the error.

(index):774 Uncaught (in promise) ReferenceError: storeData is not defined
at initMap ((index):774)
at js?key=AIzaSyAg-GBNbwLWCxiN-UI-0COkr1bgAKpXjQUcallback=initMap:123
at js?key=AIzaSyAg-GBNbwLWCxiN-UI-0COkr1bgAKpXjQUcallback=initMap:123

I think the WordPress first try to use wp_localize, then load jquery. Or Wordpress don't know how to connect jquery-core with jquery CDN.

Code of my custom temple site:

?php /* Template Name: Mapy */ ?

?php get_header(); ?

?php
    $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),
                'lat'   = get_field('gps_dlugosc'),
                'long'  = get_field('szerokosc_gps')
            ];
        }
    wp_localize_script('jquery-core', 'storeData', $storeData);

?

section style="padding-top:70px;"
    div id="map"/div
/section


script
    // Initialize and add the map
    function initMap() {
      // The location of Uluru
      var poznan = {lat: 52.402684, lng: 16.9213905};
      var j = storeData.length;
      //console.log(storeData.length);    
      // The map, centered at Uluru
      var map = new google.maps.Map(
          document.getElementById('map'), {
              zoom: 15,
              center: poznan,
              zoomControl: true,
              mapTypeControl: true,
              scaleControl: false,
              streetViewControl: false,
              rotateControl: false,
              fullscreenControl: true,
          }
      );

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

/script

script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAg-GBNbwLWCxiN-UI-0COkr1bgAKpXjQUcallback=initMap"/script


?php get_footer(); ?

Thank's for help, Sorry I am not good at English.

Topic wp-localize-script google-maps php Wordpress javascript

Category Web


OK, so there are few misconceptions in your code...

1. You should localize your own script and not some built-in one.

You can't be certain what scripts will be used on the site. In your case you localize jquery-core script, but you don't assure that this script is enqueued on the site.

This means that your localization variable may not be included in your page (and it is not in your case).

2. You should localize scripts before they are printed.

Your code localizes the script directly in the template. It would be much nicer, if you'd done this inside functions.php.

But there's even bigger problem - you localize that script after calling get_header(). It means that the script may already be printed, so it won't get localized...

So how to fix this?

1. Move your JS code:

function initMap() {
    ...  
}

to some external file like my-map-script.js.

2. Enqueue and localize it properly

function my_enqueue_map_scripts() {

    if ( is_page(123) ) { // you can enqueue it only for given page, just delete this if, if it should be available globally

        wp_enqueue_script( 'my-map-script', get_template_directory_uri() . '/js/ma-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),
                'lat'   => get_field('gps_dlugosc'),
                'long'  => get_field('szerokosc_gps')
            ];
        }
        wp_localize_script('my-map-script', 'storeData', $storeData);
    }
}
add_action( 'wp_enqueue_scripts', 'my_enqueue_map_scripts' );

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.