问题
How are you?. I am studying a Google Maps with Ionic 3 tutorial. I have done everything what is explained there, but when the project is launched, there is appearing this error. I have investigated A LOT, but nothing works. Thanks!.
Error: Uncaught (in promise): ReferenceError: google is not defined
ReferenceError: google is not defined
This is my code:
home.ts
import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController } from 'ionic-angular';
import { IonicPage } from 'ionic-angular';
declare var google;
@IonicPage()
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
@ViewChild('map') mapElement:ElementRef;
map: any;
start = 'chicago, il';
end = 'chicago, il';
directionsService = new google.maps.DirectionsService;
directionsDisplay = new google.maps.DirectionsRenderer;
constructor(public navCtrl: NavController) {
}
ionViewLoad(){
this.initMap();
}
initMap(){
this.map = new google.maps.Map(this.mapElement.nativeElement,
{
zoom: 7,
center: {lat: 41.85, lng: -87.65}
});
this.directionsDisplay.setMap(this.map);
}
calculateAndDisplayRoute(){
this.directionsService.route({
origin: this.start,
destination: this.end,
travelMode: 'DRIVING',
}, (response, status) => {
if(status == 'OK'){
this.directionsDisplay.setDirections(response);
}else{
window.alert('Directions request failed due to ' +
status);
}
});
}
}
回答1:
Make sure you are not using "async" and "defer" in your script when you are loading Google Maps API. If you are using these, please remove them. It'll work fine. Use it like this:
<script src="http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
Please have a look at this issue posted on Ionic forum for detailed guidance:
Issue posted on Ionic Forum
Hope this will help you. Cheers!!!
回答2:
Make sure you use HTTPS when loading javascript!
Change from this
<script src="http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
To
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
回答3:
You need to declare
it as shown below where you didn't do that in your code.
declare var google: any;
About the same issue on Git repo
回答4:
Even if you declare google, you have to 'wait' for the device to be loaded.
Have you tried to use setTimeout()
?
E.g.:
ionViewLoad(){
setTimeout(()=>{ this.initMap(); },100);
}
来源:https://stackoverflow.com/questions/46313492/ionic-3-uncaught-in-promise-referenceerror-google-is-not-defined-referencee