Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ERROR ReferenceError: google is not defined Angular Map

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>
like image 316
Kamil Avatar asked Nov 14 '25 10:11

Kamil


1 Answers

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>
...
like image 197
jpoehnelt Avatar answered Nov 17 '25 10:11

jpoehnelt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!