I was able to get this working after a bit of fiddling. Give the #map-canvas
element a height (you can do this in CSS):
<div id="map-canvas" style="height:500px"></div>
Add the callback
argument to the google-maps
script URL and add the defer
and async
attributes to the google-maps
script tag. Also make custom-scripts
a dependency for google-maps
:
if ( ! function_exists( 'foundationpress_scripts' ) ) :
function foundationpress_scripts() {
//Load custom JS script
wp_enqueue_script('custom-scripts', get_stylesheet_directory_uri() . '/assets/javascript/custom/custom-scripts.js', array(), '1.0.0', true );
// Load Google Maps API. Make sure to add the callback and add custom-scripts dependency
wp_enqueue_script('google-maps', 'https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&callback=initMap', array( 'custom-scripts' ) );
// Add the comment-reply library on pages where it is necessary
if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
wp_enqueue_script( 'comment-reply' );
}
}
add_action( 'wp_enqueue_scripts', 'foundationpress_scripts' );
endif;
// Add async and defer attributes
function google_maps_script_attributes( $tag, $handle) {
if ( 'google-maps' !== $handle ) {
return $tag;
}
return str_replace( ' src', ' async="async" defer src', $tag );
}
add_filter('script_loader_tag', 'google_maps_script_attributes', 10, 2);
Make sure to do a hard reload in your browser after fixing everything.