簡體   English   中英

為什么我不能在角度2組件中加載谷歌地圖?

[英]Why can't I load google maps in angular 2 component?

這是我的ts組件:

import {Component, OnInit,  Output, EventEmitter} from '@angular/core';

    declare var google: any;

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
    })


    export class AppComponent implements OnInit {
      title = 'Dashboard';
      private map: any;


        constructor() {
          let brussels = new google.maps.LatLng(50.82, 4.35);
          var mapOptions = {
            zoom: 9,
            center: brussels
          };
          this.map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);

          var marker = new google.maps.Marker({
            position: brussels
          });
          //google.maps.event.addListener(marker, 'click', ( () => this.select.next("i was a map click")) )
          marker.setMap(this.map);

        }

      ngOnInit(){

      }

這是我的HTML:

<h1>
  {{title}}
</h1>
<div id="googleMap"></div>
<div id="legend-container"><h3>Legend</h3></div>
<div id="info-box" style="">?</div>

我在主index.html中聲明了谷歌地圖的api密鑰。 問題是我似乎無法將谷歌地圖加載到組件中。 控制台中的錯誤主要有以下幾種:

error_handler.js:45 EXCEPTION: Error in ./AppComponent class AppComponent_Host - inline template:0:0 caused by: google is not definedErrorHandler.handleError @ error_handler.js:45(anonymous function) @ application_ref.js:209ZoneDelegate.invoke @ zone.js:192onInvoke @ ng_zone_impl.js:43ZoneDelegate.invoke @ zone.js:191Zone.run @ zone.js:85(anonymous function) @ zone.js:451ZoneDelegate.invokeTask @ zone.js:225onInvokeTask @ ng_zone_impl.js:34ZoneDelegate.invokeTask @ zone.js:224Zone.runTask @ zone.js:125drainMicroTaskQueue @ zone.js:357
error_handler.js:47 ORIGINAL EXCEPTION: google is not definedErrorHandler.handleError @ error_handler.js:47(anonymous function) @ application_ref.js:209ZoneDelegate.invoke @ zone.js:192onInvoke @ ng_zone_impl.js:43ZoneDelegate.invoke @ zone.js:191Zone.run @ zone.js:85(anonymous function) @ zone.js:451ZoneDelegate.invokeTask @ zone.js:225onInvokeTask @ ng_zone_impl.js:34ZoneDelegate.invokeTask @ zone.js:224Zone.runTask @ zone.js:125drainMicroTaskQueue @ zone.js:357
error_handler.js:50 ORIGINAL STACKTRACE:ErrorHandler.handleError @ error_handler.js:50(anonymous function) @ application_ref.js:209ZoneDelegate.invoke @ zone.js:192onInvoke @ ng_zone_impl.js:43ZoneDelegate.invoke @ zone.js:191Zone.run @ zone.js:85(anonymous function) @ zone.js:451ZoneDelegate.invokeTask @ zone.js:225onInvokeTask @ ng_zone_impl.js:34ZoneDelegate.invokeTask @ zone.js:224Zone.runTask @ zone.js:125drainMicroTaskQueue @ zone.js:357
error_handler.js:51 ReferenceError: google is not defined

任何建議都非常感謝:)

谷歌地圖API尚未加載,您應該異步加載它,並在加載后初始化地圖。 看看有關異步加載谷歌地圖的這個問題

正如@GünterZöchbauer所說,你應該在視圖初始化之后初始化地圖。 (在ngAfterViewInit

這樣的事情:

export class AppComponent implements AfterViewInit {
  title = 'Dashboard';
  private map: any;

  constructor(private el:ElementRef) {
  }
  onMapsReady(){
    let brussels = new google.maps.LatLng(50.82, 4.35);
    var mapOptions = {
      zoom: 9,
      center: brussels
    };
    this.map = new google.maps.Map(this.el.nativeElement, mapOptions);
    var marker = new google.maps.Marker({
      position: brussels
    });
    //google.maps.event.addListener(marker, 'click', ( () => this.select.next("i was a map click")) )
    marker.setMap(this.map);
  }
  ngAfterViewInit(){
    (<any>window).googleMapsReady=this.onMapsReady.bind(this);
     var script = document.createElement("script");
    script.type = "text/javascript";
    document.getElementsByTagName("head")[0].appendChild(script);
    script.src = "http://maps.googleapis.com/maps/api/js?v=3&sensor=false&callback=googleMapsReady";

  }

}

注意 :通過服務加載API會(更好)

此時,DOM中不存在googleMap元素。 將代碼移動到ngAfterViewInit()

 export class AppComponent implements OnInit {
    title = 'Dashboard';
    private map: any;


    ngAfterViewInit() {
      let brussels = new google.maps.LatLng(50.82, 4.35);
      var mapOptions = {
        zoom: 9,
        center: brussels
      };
      this.map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);

      var marker = new google.maps.Marker({
        position: brussels
      });
      //google.maps.event.addListener(marker, 'click', ( () => this.select.next("i was a map click")) )
      marker.setMap(this.map);

    }
 }

嘗試從index.html加載這兩個文件

<script src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>

有關詳細信息,請參閱此處 - https://developers.google.com/chart/interactive/docs/basic_load_libs

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM