Search code examples
javascriptgoogle-mapsvue.jsvuejs2vue2-google-maps

VueJS, ReferenceError: google is not defined


I have the following source code and I got also the following error when I try to instantiate a new var with google.maps ...:

google' is not defined

Many of the answers talked about loading the API script asyncronously before everything else, and the order of the scripts matters, but I don't think that's my issue.

PS: I use this in the main.js

Vue.use(VueGoogleMaps, {    
  load: {    
    key: 'MY-KEY',    
    libraries: 'places', //// If you need to use place input    
  },    
})     

Can anyone help me? Thanks.

<div class="map-container">     
       <gmap-map     
         id="map"     
         ref="map"     
         :center="center"     
         :zoom="15"     
         map-type-id="roadmap"     
         style="width:100%;  height: 400px;">     
           <gmap-marker     
           :key="index"    
            v-for="(m, index) in markers"    
            :position="m.position"    
             @click="center=m.position"    
             ></gmap-marker>    
                </gmap-map>
            </div>
<script>    
    import _ from 'lodash'    
    import { mapState } from 'vuex'    
    import * as VueGoogleMaps from 'vue2-google-maps'   

    export default {    
      computed: {    
        ...mapState([    
          'map',    
        ]),    
        mapStyle: function () {     
          const h = document.body.clientHeight - 80    
          return 'width: 100%; height: ' + h + 'px'    
        },    
        center: function () {    
          return { lat: 44.837938, lng: -0.579174 }    
        },    
      },    
      mounted: function () {    
        VueGoogleMaps.loaded.then(() => {
           var map = new google.maps.Map(document.getElementById('map'))    
        }
      }, 

Solution

  • As you have imported everything as VueGoogleMaps I would assume that google is within this object.

    EDIT: Seems that google object is called gmapApi.

    So change

    var map = new google.maps.Map(document.getElementById('map'))   
    

    to

    let map = new VueGoogleMaps.gmapApi.maps.Map(document.getElementById('map'))   
    

    Since you are not importing anything explicitly it should all rest within VueGoogleMaps. So if you want to have it called google, add the computed field as described in the other answer, except that gmapApi should sit within VueGoogleMaps.

    So

    computed: {
        google: VueGoogleMaps.gmapApi
    }