Google maps JS API in sage 9

sage9

#1

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', 'https://maps.googleapis.com/maps/api/js?key=' . 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?


#2

Try to add 'window.google': '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.


#3

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.


#4

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

I will try it in a while.


#5

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


#6

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', 'https://maps.googleapis.com/maps/api/js?v=3&libraries=places&key='.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?


#7

Can be the answer in the function option for externals?

https://webpack.js.org/configuration/externals/#function

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

I don’t know enough coding for solve it.