Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load googlemaps api before AGM Map

I'm trying to load the google maps API independently of the AGM Maps Module. I'm trying to do this because in certain cases I want to access Google Maps API without using the AGM Module. For instance, if I want to load a street view I need to make a call to the Google Maps service I want the API already loaded and ready to use. The problem arises because the AgmCoreModule in the app.module takes care of loading the Google API like so:

    AgmCoreModule.forRoot({
        apiKey: 'API_KEY',
        libraries: ['places', 'drawing', 'geometry']
    })

This is fine for loading a map using the AGM component. The script is appended to the index.html file and everything works fine. However, if I want to access the Google Maps API without having instantiated a map the AGM module hasn't appended the Google API script and 'google' is undefined.

Is there a way of loading the Google Maps API without using the forRoot() function on the AgmCoreModule?

like image 698
abyrne85 Avatar asked Dec 11 '18 16:12

abyrne85


People also ask

How do you check if Google Maps API is loaded?

if (google. maps) {...} will give you a reference error if google is undefined (i.e. if the API didn't load). Instead, use if (typeof google === 'object' && typeof google. maps === 'object') {...} to check if it loaded successfully.

How do I use Gmap API?

Go to the Google Maps Platform > Credentials page. On the Credentials page, click Create credentials > API key. The API key created dialog displays your newly created API key. Click Close.

Is Google Maps API no longer free?

You won't be charged until your usage exceeds $200 in a month. Note that the Maps Embed API, Maps SDK for Android, and Maps SDK for iOS currently have no usage limits and are at no charge (usage of the API or SDKs is not applied against your $200 monthly credit).


2 Answers

I solved this issue by using the MapsApiLoader service too. I needed to create HealtMap, but @agm/core don't have support, then i used this to load googleMapsApi and create a map.

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

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

import { environment } from 'environments/environment';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AgmCoreModule.forRoot({
      apiKey: environment['apiKeyMaps'],
      libraries: ['visualization'],
    }),
  ],
  providers: [
    GoogleMapsAPIWrapper,
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html

<div #gmap class="map-heat-container" style="height: 500px; width: 500px"></div>

app.component.ts

import { Component, ViewChild, AfterContentInit } from '@angular/core';
import { MapsAPILoader } from '@agm/core';

declare var google: any;

interface Marker {
  lat: number;
  lng: number;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements AfterContentInit {

  @ViewChild('gmap') gmapElement: any;

  map: google.maps.Map;
  heatmap: google.maps.visualization.HeatmapLayer;

  constructor(
    private mapsApiLoader: MapsAPILoader,
  ) { }

  ngAfterContentInit(): void {
    this.mapsApiLoader.load().then(() => {
      this.initMap();
    });
  }

  initMap() {
    this.map = new google.maps.Map(this.gmapElement.nativeElement, {
      zoom: 3.5,
      center: new google.maps.LatLng(-14, -54),
      mapTypeId: google.maps.MapTypeId.SATELLITE,
      zoomControl: false,
      streetViewControl: false,
      disableDefaultUI: true,
    });

    this.heatmap = new google.maps.visualization.HeatmapLayer({
      data: this.getPoints(),
      map: this.map,
    });
  }

  getPoints() {
    // create points
    let markers: Marker[] = [
      { "lat": -23, "lng": -46 }, { "lat": -24, "lng": -53 }, { "lat": -23, "lng": -46 }
    ];

    // transforming points
    return markers.map(point =>
      new google.maps.LatLng(point.lat, point.lng));
  }
}

I needed install @type/googlemaps and add googlemaps to tsconfig.json to use var google in app.component.ts

tsconfig.app.json

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "types": [
      "googlemaps"
    ]
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}

Demo: StackBLitz

like image 64
Giuliano Gusmão Avatar answered Nov 02 '22 21:11

Giuliano Gusmão


I solved this issue by using the MapsApiLoader service. No need to touch anything in app.module or change how AgmCoreModule is initialised.

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


 constructor(
    private _mapsAPILoader: MapsAPILoader
  ) { }

this._mapsAPILoader.load().then(() => {
  //do stuff here
});
like image 42
abyrne85 Avatar answered Nov 02 '22 20:11

abyrne85