Angular 5 - google tanımlı değil (Google Haritalar)
Angular 5 uygulamamda Google Haritalar'ı kullanmak istiyorum, ama bazı sorunlarla karşılaştım.
Görünüm yüklenirken js konsolunda hata alıyorum:
LoginComponent_Host.ngfactory.js? [sm]:1 ERROR ReferenceError: google is not defined
at LoginComponent.ngAfterViewInit (login.component.ts:15)
at callProviderLifecycles (core.js:12428)..
Bileşenim:
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 ile yüklenen AgmCoreModule’u kullanıyorum:
npm install @agm/core --save
LatLang sınıfını bu şekilde de içe aktarmayı denedim:
import LatLng = google.maps.LatLng;
Ve index.html dosyamda script kullan
<script src="https://maps.googleapis.com/maps/api/js?key=KEY&libraries=places" async defer></script>
Ama sürekli aynı sorunları alıyorum. Bir şeyi mi kaçırıyorum?
Cevap #1
agm/core Google Haritalar'ı yükler ve modül ithalinde API anahtarınızı ayarlar, böylece <script src="https://maps.googleapis.com/maps/api/js?key=KEY&libraries=places" async defer></script> kullanmanıza gerek kalmaz
Başlangıç kılavuzlarını takip edin. Sonuç olarak şöyle bir şeyle karşılaşacaksınız
<agm-map [latitude]="lat" [longitude]="lng">
<agm-marker [latitude]="lat" [longitude]="lng"></agm-marker>
</agm-map>
Cevap #2
Google Haritalar'dan anahtarı alın ve ardından bu anahtarı @NgModule altında app.module.ts dosyasına yerleştirin
AgmCoreModule.forRoot({
apiKey: 'your key generated from google maps'
});
ve HTML'de bunu ekle
<agm-map [latitude]="lat" [longitude]="lng">
<agm-marker [latitude]="lat" [longitude]="lng"></agm-marker>
</agm-map>
ve ayrıca bu da CSS'te
agm-map {
height: 300px;
}
