【问题标题】:IONIC 3: Uncaught (in promise): ReferenceError: google is not defined ReferenceErrorIONIC 3: Uncaught (in promise): ReferenceError: google is not defined ReferenceError
【发布时间】:2018-03-01 00:13:37
【问题描述】:

你好吗?我正在学习带有 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);
            }
        });
        }

     }

【问题讨论】:

  • 这是一个cordova插件吗?你在设备上运行吗?
  • 没有。笔记本电脑浏览器。是的,是一个cordova插件。
  • cordova 插件未使用ionic serve 加载。使用模拟器/设备
  • 好的。我要试试这条路。
  • index.html链接谷歌地图js SDK文件。

标签: angular google-maps typescript ionic3


【解决方案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】:

确保在加载 Google Maps API 时没有在脚本中使用“异步”和“延迟”。如果您正在使用这些,请删除它们。它会正常工作的。像这样使用它:

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

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

Issue posted on Ionic Forum

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

【讨论】:

    【解决方案3】:

    即使您声明 google,您也必须“等待”设备加载。

    你试过用setTimeout()吗?

    例如:

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

    【讨论】:

      【解决方案4】:

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

      declare var google: any;
      

      关于Git repo上的相同问题

      【讨论】:

      • 但没有声明为any@suraj
      • 您需要使用deviceionic cordova run android --prod --device
      猜你喜欢
      • 2021-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-24
      • 1970-01-01
      相关资源
      最近更新 更多