3

i want to use google map api in my angular web application but i have this error -> ERROR ReferenceError: google is not defined

I do everything as in the original google documentation but unfortunately it doesn't work: https://developers.google.com/maps/documentation/javascript/examples/map-simple

My TS class

  /// <reference types="google.maps" />
import { Component } from '@angular/core';
import {} from 'google.maps';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})


export class AppComponent {
  title = 'testapp';

constructor() { }

  ngOnInit() {
    
    initMap();
 
  }
}

let map: google.maps.Map;

function initMap(): void {
  map = new google.maps.Map(document.getElementById("map") as HTMLElement, {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 8,
  });
}

My html class

<!DOCTYPE html>
<html>
  <head>
    <title>Simple Map</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  
    <script src="./index.js"></script>
  </head>
  <body>
    <div id="map"></div>

    <!-- Async script executes immediately and must be after any DOM elements used in callback. -->
    <script
      src="https://maps.googleapis.com/maps/api/js?key=MyAPIKEY&callback=initMap&libraries=&v=weekly"
      async
    ></script>

   

  </body>
</html>
Kamil
  • 51
  • 1
  • 6
  • Take a look at: https://angular-maps.com/ I think you'll find this a lot easier to use within Angular. – Brandon Taylor Jul 12 '21 at 19:39
  • it's true AGM works but I miss tips for specialized things such as measuring distances, automatically finding and saving coordinates etc. And all these things are nicely described in google but not in AGM. :( – Kamil Jul 12 '21 at 19:48

1 Answers1

3

Your index.js is being parsed prior to the Google maps api being available. Two options:

Dynamic loading with https://www.npmjs.com/package/@googlemaps/js-api-loader

import {Loader} from "@googlemaps/js-api-loader";

// ... removed

constructor() { }

  ngOnInit() {
    
    const loader = Loader({apiKey: ''}).load().then(initMap);
 
  }
}

Change order of script parsing

Alternatively, remove the async/callback and place the Google Maps Script above index.js. (This block until the resources have been loaded.)

<script src="https://maps.googleapis.com/maps/api/js?key=MyAPIKEY&v=weekly"></script>
<script src="./index.js"></script>
...
Justin Poehnelt
  • 2,992
  • 1
  • 19
  • 23