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

Question

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-0COkr1bgAKpXjQU&callback=initMap:123
at js?key=AIzaSyAg-GBNbwLWCxiN-UI-0COkr1bgAKpXjQU&callback=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; i<5; 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-0COkr1bgAKpXjQU&callback=initMap"></script>


<?php get_footer(); ?>

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

0
, , , Piotr Mucha 3 years 2020-03-30T00:51:21-05:00 0 Answers 105 views 0

Leave an answer

Browse
Browse