Angular 5 - 谷歌未定义(谷歌地图)

2024-05-27

我想在我的 Angular 5 应用程序上使用谷歌地图,但遇到了一些问题。

加载视图时,我在 js 控制台中收到错误:

LoginComponent_Host.ngfactory.js? [sm]:1 ERROR ReferenceError: google is not defined 
at LoginComponent.ngAfterViewInit (login.component.ts:15) 
at callProviderLifecycles (core.js:12428)..

我的组件:

  import {AfterViewInit, Component} from '@angular/core';
    declare let google: any;

    @Component({
      selector: 'app-login',
      templateUrl: './login.component.html',
      styleUrls: ['./login.component.css']
    })
    export class LoginComponent implements AfterViewInit {

       ngAfterViewInit(): void {
          let origin = new google.maps.LatLng(4.0, 2.0 );
          let destination = new google.maps.LatLng(1.0, 1.5);
       }

       constructor() {}
    }

应用程序模块.ts

import {AgmCoreModule} from '@agm/core';

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    AppRoutingModule,
    AgmCoreModule.forRoot({
      apiKey: 'KEY'
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

我正在使用由 npm 安装的 AgmCoreModule:

npm install @agm/core --save

我也尝试以这种方式导入 LatLang 类:

import LatLng = google.maps.LatLng;

并在我的index.html中使用脚本

<script src="https://maps.googleapis.com/maps/api/js?key=KEY&libraries=places" async defer></script>

但我一直收到同样的问题。 我错过了什么吗?


agm/core加载谷歌地图并在模块导入中设置您的 api 密钥,因此您不需要<script src="https://maps.googleapis.com/maps/api/js?key=KEY&libraries=places" async defer></script>

跟随他们的入门指南tutorial https://angular-maps.com/guides/getting-started/。你最终会得到类似的东西

<agm-map [latitude]="lat" [longitude]="lng">
    <agm-marker [latitude]="lat" [longitude]="lng"></agm-marker>
</agm-map>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular 5 - 谷歌未定义(谷歌地图) 的相关文章

随机推荐