Skip to content Skip to sidebar Skip to footer

'google' Is Not Defined Using Google Maps Javascript Api Loader

I have a Vue CLI project that uses the Google Maps JavaScript API Loader. I import the loader using the code below: import { Loader } from '@googlemaps/js-api-loader'; After that,

Solution 1:

The new package does not return a 'google' object when the promise is resolved, instead it is attached to the window. To use it as you would if following the Vue tutorial (that I am also following) you would need to add:

this.google = window.google

To the map component. For clarity:

asyncmounted() {
   // As per the documentation for the google maps API loaderconst googleMapApi = awaitLoader({
       apiKey: this.apiKey
    })

    // This returns a promise, but not a 'google' objectthis.google = await googleMapApi.load();
    // Set the google object from the correct locationthis.google = window.google;
    this.initializeMap();
},

methods: {
    initializeMap() {
        const mapContainer = this.$refs.googleMap;
        this.map = newthis.google.maps.Map(mapContainer, this.mapConfig);
    }
}

The reference to the tutorial I talk about: https://vuejs.org/v2/cookbook/practical-use-of-scoped-slots.html

Solution 2:

hi @Goodman L you have to try it. Just add window at the front of your code.. happy coding

window.google.maps.Map

Solution 3:

Let’s first establish our GoogleMapLoader.vue template:

<template><div><divclass="google-map"ref="googleMap"></div><templatev-if="Boolean(this.google) && Boolean(this.map)"><slot:google="google":map="map"
      /></template></div></template>

Now, our script needs to pass some props to the component which allows us to set the Google Maps API and Map object:

importGoogleMapsApiLoaderfrom'google-maps-api-loader'exportdefault {
  props: {
    mapConfig: Object,
    apiKey: String,
  },

  data() {
    return {
      google: null,
      map: null
    }
  },

  asyncmounted() {
    const googleMapApi = awaitGoogleMapsApiLoader({
      apiKey: this.apiKey
    })
    this.google = googleMapApi
    this.initializeMap()
  },

  methods: {
    initializeMap() {
      const mapContainer = this.$refs.googleMapthis.map = newthis.google.maps.Map(
        mapContainer, this.mapConfig
      )
    }
  }
}

Please follow this tutorial for the correct way to do it.

https://vuejs.org/v2/cookbook/practical-use-of-scoped-slots.html

Post a Comment for "'google' Is Not Defined Using Google Maps Javascript Api Loader"