Search code examples
javascriptwebpackgoogle-places-api

Cannot read property 'Autocomplete' of undefined using webpack with load-google-maps-api-2


I'm attempting to set up an auto complete using using maps javascript api place autocomplete but I keep receiving.

Uncaught (in promise) TypeError: Cannot read property 'Autocomplete' of undefined

index.js

var loadGoogleMapsApi = require('load-google-maps-api-2');
const indexTemplate = require("./index.handlebars");

    $(function() {

        let googleMaps = null;

        loadGoogleMapsApi({
            key: 'My api key here'
        }).then(function(_googleMaps) {
            googleMaps = _googleMaps
            var autocomplete = new googleMaps.places.Autocomplete($("#address")[0]);

                googleMaps.event.addListener(autocomplete, 'place_changed', function() {
                    var place = autocomplete.getPlace();
                    console.log(place.address_components);
            });
        });

the full listing is here.

https://github.com/bryandellinger/addressvalidator

if you would like to run it after downloading npm install npm run build (do a webpack build) npm run start (start lite server and open up browser on port 3000)


Solution

  • you need to load the places library; according to the documentation:

    loadGoogleMapsApi({
        libraries: ['places'],
        key: '...'
    })
    .then(function (googleMaps) {
      ...
    })
    .catch(function (error) {
        ...
    });