Import Google Maps NPM package into main.js

Hi there,

I’ve started using Sage recently (it’s great!) - and I want to include this Google Maps (npm) package into the main.js file of Sage: https://www.npmjs.com/package/google-maps

It seems to compile correctly with both npm start and npm run build:production, however, in the browser, the JS console contains the following error:
(index):2334 Uncaught TypeError: Cannot read property 'maps' of undefined(…)

For some reason it doesn’t like the new google.maps or even new window.google.maps when I try to be more precise.

Does anybody know if there’s some weird Sage-related reason why this may be failing?

I have some code here if you’re interested: https://gist.github.com/anonymous/710a1998c4c7afe177b99d86f0024ce0 (but no worries if not)

Thanks in advance for any advice!

Cheers,
Morgan

Did you try using the code directly from the example in the Google Maps NPM package? You need to pass thegoogle object in from the load method

1 Like

Good call @kalenjohnson - Based on what you’ve just said, would this work?

// import external dependencies
import 'jquery';
import 'bootstrap/dist/js/bootstrap';
import GoogleMapsLoader from 'google-maps';

// import local dependencies
import Router from './util/router';
import common from './routes/Common';
import home from './routes/Home';
import aboutUs from './routes/About';

// Use this variable to set up the common and page specific functions. If you
// rename this variable, you will also need to rename the namespace below.
const mapEl = document.getElementById('map');
const mapOpts = {
  center: { lat: -34.397, lng: 150.644 },
  scrollwheel: false,
  zoom: 8,
};
const doLoadGmap = (google) => {
  const newMap = new google.maps.Map(mapEl, mapOpts);
  return newMap;
};

GoogleMapsLoader.KEY = 'xxxxxxxxx';
GoogleMapsLoader.load(doLoadGmap(google));

const routes = {
  // All pages
  common,
  // Home page
  home,
  // About us page, note the change from about-us to aboutUs.
  aboutUs,
};

// Load Events
document.addEventListener('DOMContentLoaded', () => new Router(routes).loadEvents());

Best way to find out would be to try it

1 Like

Thanks for the help guys, much appreciated. But still getting an error. Tried running the above and got the following.

ERROR in ./scripts/main.js

/Applications/MAMP/htdocs/wordpress/wp-content/themes/greenkey/assets/scripts/main.js
26:34 error ‘google’ is not defined no-undef

:heavy_multiplication_x: 1 problem (1 error, 0 warnings)

Well that makes sense, the code is doing this:

google is not defined there. Like I said, take the code directly from the docs for the maps NPM package, then start modifying…