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

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' );