Angular 5-未定义google(Google地图) [英] Angular 5 - google is not defined (Google Maps)
问题描述
我想在Angular 5应用中使用google maps,但遇到了一些问题.
I want to use google maps on my Angular 5 app, but I encourtered some problem.
加载视图时,我在js控制台中收到错误:
When view is loading I receive error in js console:
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
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:
I'm using AgmCoreModule installed by npm:
npm install @agm/core --save
我也尝试过这种方式导入LatLang类:
I tried also importing LatLang class this way:
import LatLng = google.maps.LatLng;
并在我的index.html中使用脚本
And use script in my index.html
<script src="https://maps.googleapis.com/maps/api/js?key=KEY&libraries=places" async defer></script>
但是我一直都收到相同的问题. 我想念什么吗?
But all the time I received same issues. Am I missing something?
推荐答案
agm/core
加载Google地图&在模块导入中设置您的api密钥,因此您不需要<script src="https://maps.googleapis.com/maps/api/js?key=KEY&libraries=places" async defer></script>
agm/core
loads google maps & sets your api key within the module import, so you do not need <script src="https://maps.googleapis.com/maps/api/js?key=KEY&libraries=places" async defer></script>
按照他们的入门教程.您最终会得到类似
Follow their getting started tutorial. You'll end up with something like
<agm-map [latitude]="lat" [longitude]="lng">
<agm-marker [latitude]="lat" [longitude]="lng"></agm-marker>
</agm-map>
这篇关于Angular 5-未定义google(Google地图)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!