VueJS, ReferenceError: google is not defined
Solution 1
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
}
Solution 2
You forgot one parenthesis:
VueGoogleMaps.loaded.then(() => {
var map = new google.maps.Map(document.getElementById('map'))
})
Tell me if this helps.
Also from NPM vue2-google-maps,
If you need to gain access to the
<template> <GmapMarker ref="myMarker" :position="google && new google.maps.LatLng(1.38, 103.8)" /> </template> <script> import {gmapApi} from 'vue2-google-maps' export default { computed: { google: gmapApi } } </script>
Solution 3
If you get "maps of null" it means google computed property is not ready yet.
Try this:
computed: {
google: VueGoogleMaps.gmapApi
}
...
Inside your method to wait for gmapApi:
this.$gmapApiPromiseLazy().then(() => {
//your code here
//E.g. for directions
var directionsService = new this.google.maps.DirectionsService();
});
Smix
Updated on June 12, 2022Comments
-
Smix almost 2 years
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')) } },