你好吗?我正在研究使用Ionic 3教程的Google地图。我已经完成了所有所解释的事情,但是当项目启动时,就会出现此错误。我已经调查了很多,但没有任何可行。谢谢!
Error: Uncaught (in promise): ReferenceError: google is not defined
ReferenceError: google is not defined
这是我的代码:
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);
}
});
}
}
确保加载JavaScript时使用https!
从此更改
<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>
当您加载Google Maps API时,请确保您在脚本中不使用" async"one_answers" defer"。如果您正在使用这些,请删除它们。它可以正常工作。这样使用:
<script src="http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
请查看Ionic论坛上发布的此问题,以获取详细的指导:
在离子论坛上发布的问题
希望这对您有帮助。欢呼!!!
您需要declare
,如下所示,您在代码中没有这样做。
declare var google: any;
git Repo
即使您声明Google,也必须'等待'加载设备。
您是否尝试使用setTimeout()
?
例如:
ionViewLoad(){
setTimeout(()=>{ this.initMap(); },100);
}