需要帮助。我在父组件的创建钩子上加载了Google map api。但我继续在创建的钩子中获取此错误错误:ReferenceError: google is not defined
以下是Google地图脚本的调用方式。
mounted() {
let mapScript = document.createElement('script');
mapScript.setAttribute('src', 'https://maps.googleapis.com/maps/api/js?key=TheKey');
document.head.appendChild(mapScript);
}
这是我希望显示Google地图的子组件。
<template>
<div>
<div ref="mapID" :id="mapID"></div>
</div>
</template>
<script>
export default {
props: [ 'place', 'coordinates' ],
data() {
return {
mapID: 'mapID',
markerCord: '',
markers: []
}
},
methods: {
initialize() {
console.log('Hello World');
let locations = [
['Bondi Beach', -33.890542, 151.274856, 4],
['Coogee Beach', -33.923036, 151.259052, 5],
['Cronulla Beach', -34.028249, 151.157507, 3],
['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
['Maroubra Beach', -33.950198, 151.259302, 1]
];
let map = new
google.maps.Map(document.getElementById(this.mapID), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
let infowindow = new google.maps.InfoWindow();
let marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1],
locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click',
(function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
},
mounted() {
this.initialize()
}
}
</script>
答案 0 :(得分:0)
你要做的不是标准的做法。
我建议您遵循以下所述的最佳做法(安装NPM包):https://stackoverflow.com/a/49291060/1850609
因此,再次按照上述步骤,从长远来看,它将使您免于头痛。
话虽如此,这是您的案例的快速解决方法:
mounted() {
let initializeWhenGoogleIsAvailable = () => {
if (google) { // test if google is available
this.initialize(); // if it is, then initalize
} else {
setTimeout(initializeWhenGoogleIsAvailable, 100) // if it isn't, wait a bit and retry
}
};
initializeWhenGoogleIsAvailable();
}
它将延迟调用this.initialize()
,直到google
在全局范围内可用。
但是,再次,采用NPM方式。