What is preventing me from loading Google Maps within my Angular 2 component?

Below is the TypeScript code for my component:

import {Component, OnInit, Output, EventEmitter} from '@angular/core';

declare var google: any;

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

export class AppComponent implements OnInit {
  title = 'Dashboard';
  private map: any;

    constructor() {
      let brussels = new google.maps.LatLng(50.82, 4.35);
      var mapOptions = {
        zoom: 9,
        center: brussels
      };
      this.map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);

      var marker = new google.maps.Marker({
        position: brussels
      });
      //google.maps.event.addListener(marker, 'click', ( () => this.select.next("i was a map click")) )
      marker.setMap(this.map);
    }

  ngOnInit(){

  }

This is the HTML template associated with the component:

<h1>
  {{title}}
</h1>
<div id="googleMap"></div>
<div id="legend-container"><h3>Legend</h3></div>
<div id="info-box" style="">?</div>

I have declared the Google Maps API key in the main index.html file. However, I am facing issues loading the map into the component. The console is showing errors related to the undefined 'google' object:

Error Message: ReferenceError: google is not defined
Stack Trace: [error_handler.js:51]
               [ErrorHandler.handleError @ error_handler.js:51]
               [...and so on...]

If anyone has any suggestions or solutions to resolve this problem, I would greatly appreciate it :)

Answer №1

It appears that the Google Maps API has not been loaded yet. To resolve this issue, you should load it asynchronously and initialize the map after it has finished loading. For more information on loading Google Maps asynchronously, refer to this helpful question.

@Günter Zöchbauer also suggested initializing the map after the view has been initialized (in ngAfterViewInit). Here is an example:

export class AppComponent implements AfterViewInit {
  title = 'Dashboard';
  private map: any;

  constructor(private el:ElementRef) {
  }

  onMapsReady(){
    let brussels = new google.maps.LatLng(50.82, 4.35);
    var mapOptions = {
      zoom: 9,
      center: brussels
    };
    this.map = new google.maps.Map(this.el.nativeElement, mapOptions);
    var marker = new google.maps.Marker({
      position: brussels
    });
    //google.maps.event.addListener(marker, 'click', ( () => this.select.next("i was a map click")) )
    marker.setMap(this.map);
  }
  
  ngAfterViewInit(){
    (<any>window).googleMapsReady=this.onMapsReady.bind(this);
     var script = document.createElement("script");
    script.type = "text/javascript";
    document.getElementsByTagName("head")[0].appendChild(script);
    script.src = "http://maps.googleapis.com/maps/api/js?v=3&sensor=false&callback=googleMapsReady";

  }

}

NB: It is recommended to load the API using a service for better efficiency.

Answer №2

At this stage, the googleMap element is not present in the DOM. It should be moved to the ngAfterViewInit() method.

 export class AppComponent implements OnInit {
    title = 'Dashboard';
    private map: any;

    ngAfterViewInit() {
      let brussels = new google.maps.LatLng(50.82, 4.35);
      var mapOptions = {
        zoom: 9,
        center: brussels
      };
      this.map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);

      var marker = new google.maps.Marker({
        position: brussels
      });
      //google.maps.event.addListener(marker, 'click', ( () => this.select.next("i was a map click")) )
      marker.setMap(this.map);

    }
 }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: Invalid character encountered during login script JSON parsing

I found this script online and have been experimenting with it. However, I encountered the following error: SyntaxError: JSON.parse: unexpected character [Break On This Error] var res = JSON.parse(result); The problem lies in the file below as I am unf ...

React powered interactive tables

I am in the process of creating a dynamic table using React, and here is the data structure I am working with: { numRows: 2, numCols: 3, cells: [ { id: 1, pos: { row: 1, col: 1 }, content: 'This is th ...

Unable to compile TypeScript files using gulp while targeting ES5

After starting my first Angular2 app, I encountered an issue where I couldn't use gulp to compile for es5. Below is the dependencies file: "dependencies": { "@angular/common": "2.0.0", "@angular/compiler": "2.0.0", "@angular/compiler-cli ...

The scope's attribute is present, but the variable within the scope's attribute is not

Currently, I am delving into angularJS development, but encountering a perplexing issue. I am attempting to format a JSON into a table with intricate rules. The JSON structure currently is as follows: { "id":"test", "title":"Test Sample", "de ...

Unexpected error: Undefined value in AngularJS push

Cannot call method 'push' of undefined I encounter an error message when running my AngularJS code: $scope.ok = function () { $modalInstance.close(); $scope.key.push({ title: '', gps:'', desc:''}); }; To r ...

When I click on my div, the color does not change as expected

Recently, I wrote a code snippet where there are 9 different div elements each assigned a ".spaces" class. The intention was to change the color of these divs upon clicking on them. However, I encountered an issue where only the first div changes its color ...

Trouble with AngularJS Smart Table when dealing with live data streams

Currently, I am facing a scenario where I am utilizing angularJs smart table for filtering. Here is the HTML code: <section class="main" ng-init="listAllWorkOrderData()"> <table st-table="listWorkOrderResponse"> <thead> ...

Promises and Their Valuable Variables

Recently I began learning JavaScript and I'm encountering some confusion. Here's the code snippet that is causing me trouble: api.posts .browse({ limit: 5, include: 'tags,authors' }) .then(posts => { posts.forEach(post =&g ...

Display a preview of a React component

Currently facing a challenge where I need to create a form for users to adjust the title, background color, button background, text color, and other settings of a component. I want to provide a live preview of the component as the user makes changes. I en ...

UI-router issue: UI view and links not functioning properly

Recently, I decided to implement ui-router for Angular in my project. After adding the following code snippet to my app module within the app.js file: angular .module("ngClassifieds", ['ngMaterial', 'ui.router']) .config(function($md ...

Having difficulty retrieving model values from the angular ui modal dialog

Being only on my second day in the world of Angular, I am trying to navigate around Angular UI and build my first modal dialog. The modal dialog displays properly, but I'm encountering an issue with using models within it. You can view my demo on Plun ...

Learn how to pass an id from the query parameters to the getInitialProps function in Next.js

Looking to create a basic website that displays content from a database? Utilizing the getInitialProps function from Next.js documentation can help with server-side rendering: https://nextjs.org/docs/api-reference/data-fetching/getInitialProps#getinitialpr ...

Tips for saving information in an array with Vue.js?

I am working on a task where I need to fetch data from an API and store only the values that are marked as "true" in a variable. The API response is listed below: API Output Data { "BNG-JAY-137-003": false, "BNG-JAY-137-004": true, ...

Create dynamic cells for CSS grid using JavaScript

I have been manually generating grid cells in a specific pattern by copying and adjusting <div> elements. Although this method works, I am interested in creating an algorithm that can automatically generate the desired layout. The left box in the exa ...

Adjustable Scroll Bar

Could anyone help me find a component similar to the resizable scrollbar on Google Finance? Check out this link: http://www.google.com/finance?q=EURUSD&ei=bhM_UKDXF-aIWqAPVNQ You can see it below the chart. If you know where I can find something like ...

Mocha retries causing logging malfunction: a problem to address

My current situation involves testing something on our network, and occasionally the network experiences delays causing the test to end prematurely. To address this issue, I attempted to set the test to retry with the command this.retries(1). While this ...

Issues with rendering HTML5 drag and drop styles are not visible on a Windows Server 2003 platform

I am currently developing a file upload tool utilizing Valum's Ajax-Uploader as the foundation. The concept is reminiscent of how attaching files works in Gmail. Users should be able to simply drag and drop a file from their desktop into the browser w ...

Is there a way to display the data from a URL as selectable options in a dropdown menu?

I have a URL containing an arrayList of data. My task is to fetch the data from this URL and display it as options in a dropdown menu, allowing users to select the desired option. I am aware that this can be achieved using the Get method, but I am facing d ...

Animating CSS using JavaScript

Recently diving into the world of JavaScript, I've taken on the challenge of creating an analog clock. I began by crafting the second hand using CSS but now I'm eager to transition it to Javascript without relying on jQuery or any other JS framew ...

jQuery sends ajax success to input type number

I am encountering an issue with the ajax success loading function when using input type number. Interestingly, when I switch the input type to text, it works perfectly fine. However, once I change the input type back to number, the loading ceases. <s ...