Dear Team
I am not experienced with Roots Sage and I am trying to integrate Google Maps on a specific page. I did similar as described here without success. I get an initMapis not a function error as shown in this screenshot .
What I did in my Sage 9 theme:
Please note that I want to load the script on the contact (example.com/kontakt) page only.
I use Roots Bedrock and the api key is placed in the .env
file:
GOOGLE_MAPS_API='MY_API_KEY_HERE'
Following references are within the Roots Sage theme folder.
In app/setup.php
I extended the wp_enqueue_scripts hook with my google maps script. Please note the &callback=initMap
:
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);
if (is_page( 'kontakt' )) {
wp_enqueue_script('google-maps', 'https://maps.googleapis.com/maps/api/js?key=' . env('GOOGLE_MAPS_API') . '&callback=initMap', [], null, true);
}
if (is_single() && comments_open() && get_option('thread_comments')) {
wp_enqueue_script('comment-reply');
}
}, 100);
I updated resources/assets/scripts/main.js
as follows (see last part “kontakt”):
import kontakt from './routes/kontakt';
...
/** Populate Router instance with DOM routes */
const routes = new Router({
// All pages
common,
// Home page
home,
// About Us page, note the change from about-us to aboutUs.
aboutUs,
// kontakt page
kontakt,
});
I created resources/assets/scripts/routes/kontakt.js
and added following code:
const google = window.google;
export default {
init() {
// JavaScript to be fired on the kontakt page
},
finalize() {
// JavaScript to be fired on the kontakt page, after the init JS
/* eslint-disable no-unused-vars */
let map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644,
},
zoom: 8,
});
}
/* eslint-disable no-unused-vars */
},
};
This compiles but I get the fault “initMap is not a function” as mentioned at the beginning of this post.
Does anyone have an idea what I’m doing wrong or can someone give me a hint on how to best integrate google maps into Roots Sage 9? Is something wrong with the visibility of the function?
Thank you in advance for your appreciated feedback.
Regards from Switzerland,
Philipp