Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 - google is not defined (Google Maps)

I want to use google maps on my Angular 5 app, but I encourtered some problem.

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)..

My component:

  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 {}

I'm using AgmCoreModule installed by npm:

npm install @agm/core --save

I tried also importing LatLang class this way:

import LatLng = google.maps.LatLng;

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?

like image 444
adam-pociejowski Avatar asked Nov 29 '17 21:11

adam-pociejowski


1 Answers

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>
like image 155
LLai Avatar answered Sep 24 '22 04:09

LLai