IONIC 3:Uncaught(承诺):ReferenceError:google未定义ReferenceError

时间:2017-09-20 04:47:54

标签: angular google-maps typescript ionic3

你好吗?我正在学习带有Ionic 3教程的Google Maps。我已经完成了那里解释的所有内容,但是当项目启动时,出现了这个错误。我调查了很多,但没有任何作用。谢谢!

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);
            }
        });
        }

     }

4 个答案:

答案 0 :(得分:2)

确保在加载Google Maps API时未在脚本中使用“异步”和“延迟”。如果使用这些,请删除它们。会很好的。像这样使用它:

<script src="http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>

请查看在Ionic论坛上发布的此问题以获取详细指导:

Issue posted on Ionic Forum

希望这会对您有所帮助。 干杯!!!

答案 1 :(得分:1)

确保在加载JavaScript时使用HTTPS!

更改

<script src="http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>

收件人

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>

答案 2 :(得分:0)

您需要declare,如下所示,您在代码中没有这样做。

declare var google: any;

关于Git repo

上的同一问题

答案 3 :(得分:0)

即使您申报谷歌,也必须“等待”加载设备。

您是否尝试过使用setTimeout()

E.g:

ionViewLoad(){
    setTimeout(()=>{ this.initMap(); },100);
}