Confused adding google maps js

Hi all,

I’m trying to use google maps in my roots theme and am a bit confused!

This is my .js file:

const google = window.google;
export default {
  init() {
    // JavaScript to be fired on the about us page
    console.log('design centres page');

    let myLatLng = {lat: $('.map-container').data('lat'), lng: $('.map-container').data('lng')};
    console.log(myLatLng);

    let map = new google.maps.Map(document.getElementById('map-canvas'), {
      zoom: 4,
      center: myLatLng,
    });

    console.log(map);
  },
};

Then the way I’ve got it working is by adding the following to the bottom of my setup.php file:

add_action('wp_enqueue_scripts',  function(){
	wp_enqueue_script('google-maps', 'https://maps.googleapis.com/maps/api/js?key=mykey', [], null, true);
}, 10);

However if I don’t add this and put the enqueue where my other scripts are enqueued it doesn’t work:

/**
 * Theme assets
 */
add_action('wp_enqueue_scripts', function () {
    wp_enqueue_style('sage/main.css', asset_path('styles/main.css'), false, null);
    wp_enqueue_script('sage/main.js', asset_path('scripts/main.js'), ['jquery'], null, true);
    wp_enqueue_style('sage/fonts.css', 'https://fonts.googleapis.com/css?family=Lato:400,700,900|Roboto:100,300,400,700', false, null);
	wp_enqueue_script('google-maps', 'https://maps.googleapis.com/maps/api/js?key=mykey', [], null, true);

    if (is_single() && comments_open() && get_option('thread_comments')) {
        wp_enqueue_script('comment-reply');
    }
}, 100);

The only difference I can see is that the priority is different? However even when I change it from 100 to 10, it still doesn’t work this way? What am I missing??

In what order are these scripts printed out with the various options you described? Sounds like it could be a load order/race conditin thing.

This topic was automatically closed after 42 days. New replies are no longer allowed.