Google maps JS API in sage 9



Trying to get Google maps JS API working. Doing the same as in Sage 8, doesn’t work in Sage 9.

I have google maps JS API script enqueued succesfully, with its API key in app/setup.php.

wp_enqueue_script('google-maps', '' . env('GOOGLE_MAPS_API'), [], null, true);

Then, I have this simple code at routes/common.js:

$(function initMap() {
      let mapDiv = document.getElementById('map');
      let map = new google.maps.Map(mapDiv);

But I get: error 'google' is not defined.

What am I missing?


Try to add '': 'google' here:

And google: 'google' here:

Untested, but I believe this should work.

Since the Google Maps JS API is being loading as an external dependency — not a standard Node module — you need to tell Webpack that it is external and you can then use the providePlugin to provide it to all your scripts.


I don’t think you should really need to do the ProvidePlugin step I have above. That would only be if you wanted to provide google to all the scripts. Instead, I would just add import google from 'google' where I need it.


Ok, thank you very much for this explanation! :+1:t3::+1:t3::+1:t3:

I will try it in a while.


Confirmed, it works. Imported into its specific route. Thanks again.


Now how would this work if the script is enqueued on only one page?
For example I only use the places API on the checkout page of woocommerce, for autocompletion.

Thus i have:
if(is_checkout() || is_account_page()){ wp_enqueue_script('google-places', ''.get_option( 'bull-api-keys-maps-key'), false, null ,false); }

However if include google: 'google' in the externals it goes looking for it on other pages as well. How would we go about this?


Can be the answer in the function option for externals?

module.exports = {
  externals: [
    function(context, request, callback) {
      if (/^yourregex$/.test(request)){
        return callback(null, 'commonjs ' + request);

I don’t know enough coding for solve it.