Search code examples
vue.jsvuexvue-routervue2-google-maps

Vue2-Google-Maps Accessing gmapApi using beforeEnter() Route Guard


Context: I am trying to get place data via the place_id on the beforeEnter() route guard. Essentially, I want the data to load when someone enters the url exactly www.example.com/place/{place_id}. Currently, everything works directly when I use my autocomplete input and then enter the route but it does not work when I directly access the url from a fresh tab. I believe the issue is because google has not been created yet.

Question: How can I access PlacesService() using the beforeEnter() route guard ?

Error: Uncaught (in promise) ReferenceError: google is not defined

Example Code: In one of my store modules:

const module = {
  state: {
    selectedPlace: {}
  },
  actions: {
    fetchPlace ({ commit }, params) {
      return new Promise((resolve) => {
        let request = {
          placeId: params,
          fields: ['name', 'rating', 'formatted_phone_number', 'geometry', 'place_id', 'website', 'review', 'user_ratings_total', 'photo', 'vicinity', 'price_level']
        }
        let service = new google.maps.places.PlacesService(document.createElement('div'))
        service.getDetails(request, function (place, status) {
          if (status === 'OK') {
            commit('SET_SELECTION', place)
            resolve()
          }
        })
      })
    },
  },
  mutations: {
    SET_SELECTION: (state, selection) => {
      state.selectedPlace = selection
    }
  }
}

export default module

In my store.js:

import Vue from 'vue'
import Vuex from 'vuex'
import placeModule from './modules/place-module'
import * as VueGoogleMaps from 'vue2-google-maps'

Vue.use(Vuex)

// gmaps
Vue.use(VueGoogleMaps, {
  load: {
    key: process.env.VUE_APP_GMAP_KEY,
    libraries: 'geometry,drawing,places'
  }
})

export default new Vuex.Store({
  modules: {
    placeModule: placeModule
  }
})

in my router:

import store from '../state/store'

export default [
  {
    path: '/',
    name: 'Home',
    components: {
      default: () => import('@/components/Home/HomeDefault.vue')
    }
  },
  {
    path: '/place/:id',
    name: 'PlaceProfile',
    components: {
      default: () => import('@/components/PlaceProfile/PlaceProfileDefault.vue')
    },
    beforeEnter (to, from, next) {
      store.dispatch('fetchPlace', to.params.id).then(() => {
        if (store.state.placeModule.selectedPlace === undefined) {
          next({ name: 'NotFound' })
        } else {
          next()
        }
      })
    }
  }
]

What I've tried: - Changing new google.maps.places.PlacesService to new window.new google.maps.places.PlacesService - Using beforeRouteEnter() rather than beforeEnter() as the navigation guard - Changing google.maps... to gmapApi.google.maps... and gmapApi.maps... - Screaming into the abyss - Questioning every decision I've ever made

EDIT: I've also tried the this.$gmapApiPromiseLazy() proposed in the wiki here


Solution

  • The plugin adds a mixin providing this.$gmapApiPromiseLazy to Vue instances (components) only but you're in luck... it also adds the same method to Vue statically

    Source code

    Vue.mixin({
      created () {
        this.$gmapApiPromiseLazy = gmapApiPromiseLazy
      }
    })
    
    Vue.$gmapApiPromiseLazy = gmapApiPromiseLazy
    

    So all you need to do in your store or router is use

    import Vue from 'vue'
    
    // snip...
    
    Vue.$gmapApiPromiseLazy().then(() => {
      let service = new google.maps.places....
    })