【问题标题】:Angular 5 - google is not defined (Google Maps)Angular 5 - 谷歌未定义(谷歌地图)
【发布时间】:2018-05-13 17:05:54
【问题描述】:

我想在我的 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() {}
    }

app.module.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>

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

【问题讨论】:

  • 移除异步和延迟,然后尝试它是否有效,那么即使视图准备就绪,您的地图也可能没有加载。

标签: angular google-maps typescript google-maps-api-3 npm


【解决方案1】:

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

关注他们的入门@9​​87654321@。你最终会得到类似的东西

<agm-map [latitude]="lat" [longitude]="lng">
    <agm-marker [latitude]="lat" [longitude]="lng"></agm-marker>
</agm-map>

【讨论】:

    【解决方案2】:

    从 google maps 获取密钥,然后将该密钥放在 app.module.ts 中的@NgModule@NgModule

    AgmCoreModule.forRoot({
       apiKey: 'your key generated from google maps'
    }); 
    

    在 HTML 中添加这个

    <agm-map [latitude]="lat" [longitude]="lng">
       <agm-marker [latitude]="lat" [longitude]="lng"></agm-marker>
    </agm-map> 
    

    还有这个在 CSS 中

    agm-map {
      height: 300px;
    } 
    

    【讨论】:

      【解决方案3】:

      您只需将相应的依赖项和类型添加到您的项目中。 就是这些。

      在 tsconfig.json -> "types":[... "googlemaps"]

      在 package.json -> "dependencies":[... "googlemaps": "^1.12.0"]

      并且不要忘记您应该从https://developers.google.com/places/web-service/get-api-key 获得的 API 密钥,在通过AgmCoreModule 将其设置为模块后,或者只是将导入脚本添加到 HTML 中,我正在使用 @987654325 的 GMap 组件@ 和所有这些步骤帮助我前进。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-20
        • 2019-01-10
        • 2016-07-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-06
        • 1970-01-01
        相关资源
        最近更新 更多