Unexpected Error: Trouble with Google Maps API in Angular - Why does Uncaught ReferenceError: google is not defined occur sporadically

Despite encountering this question multiple times, I have not been able to find a solution that works for me. My dilemma involves declaring a class in the following manner:

class Popup extends google.maps.OverlayView {
  // Classy stuff
}

Unfortunately, every time I attempt to do so, I encounter the error

Uncaught ReferenceError: google is not defined

The peculiar thing is that Google Maps functions perfectly fine elsewhere in my code, except when I declare this specific class. Additionally, I am declaring it immediately after a class like this:

@Component({
  selector: 'app-map',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.scss',]
})
export class MapComponent implements AfterViewInit, OnDestroy {
  map: google.maps.Map; <-- No issue with google namespace here
  // Map stuff
}

class Popup extends google.maps.OverlayView { <-- The problem arises with this google namespace
  // Classy stuff
}

Upon refreshing the page, sometimes it loads successfully, while other times it crashes and displays the aforementioned error message.

I include the necessary script in my index.html like this:

<script async defer src="https://maps.googleapis.com/maps/api/js?key=myKey&libraries=places"></script>

This method has always worked flawlessly before (I extensively utilize Google Maps throughout this project without any issues concerning any other google namespaces, except when creating this particular class).

Answer №1

Prior to attempting any solutions, it is advisable to consult the Angular Google Map API Documentation to gain a better understanding of the issue at hand.

For additional insight and potential resolutions, consider perusing the responses on Stack Overflow found here, as they may directly address your current dilemma.

The root cause could stem from one of two possibilities: 1) Initialization issues resulting in the inability to recognize the global Google.Maps object, or... 2) Directive processing by angular-google-maps occurring before complete readiness of the Google Maps SDK.

Answer №2

One possible explanation for the issue you're experiencing is that the overlay may not have loaded yet, while the map has already loaded. The sequence in which scripts load could be causing this problem - it's likely that the map script loads before the overlay script, hence the difference in behavior between the two elements. However, even if the map appears to be working fine now, there could still be potential issues depending on network speed.

To troubleshoot this, consider removing the async and defer attributes from your script loading process. This will ensure that the library is loaded synchronously before attempting to utilize it.

Interestingly, Google themselves recommend loading their script synchronously when dealing with subclassing the API classes.

https://developers.google.com/maps/documentation/javascript/examples/overlay-simple

This methodology effectively subclasses the overlay class, making it easier to load the API synchronously.

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

What is the equivalent of Android Input/Output stream in TypeScript/JavaScript?

My current task involves sending data from Angular to an Android device. The requirement is for the data to be sent to the Android device using its input/output stream methods. If you are unsure of what I am asking, please provide assistance and let me kn ...

Fetching data from MongoDB, loading over 3000 entries and implementing pagination

I'm facing a challenge where I need to display more than 3000 results in an HTML table by fetching MachineID, Username, and Data from my MongoDB. However, I am encountering difficulties when trying to render this data using datatables. The MachineID ...

Unable to import necessary modules within my React TypeScript project

I am currently building a React/Express application with TypeScript. While I'm not very familiar with it, I've decided to use it to expand my knowledge. However, I've encountered an issue when trying to import one component into another comp ...

Leverage ngFor to loop through a "highly intricate" data structure

In my project, I have stored data in a JSON file structured as follows: { "name": { "source1": ____, "source2": ____, "source3": ____ }, "xcoord": { "source1": ____, "source2": ____, "source3": _ ...

Extracting information from Timeless-time-picker utilizing form control

<timeless-time-picker [hourFormat]="'hours24'" [visibleItemsCount]="3" [size]="'medium'" [theme]="'dark'" [selectionHighlightStyle]="'none'" [selectionBoxBackgro ...

What is the best way to create props that can accommodate three distinct types of functions in TypeScript?

I have been encountering a problem with the last function in my props interface that is supposed to support 3 different types of functions throughout the application. Despite adding parentheses as requested, I am still facing errors. // In Parent compon ...

Pausing repetitive HTTP requests in an Angular 6 project within a do while loop

While waiting for the completion of one API call, I am recursively consuming an external API. The http calls are being made using import {HttpClient} from '@angular/common/http' As a newcomer to the framework, there may be something wrong in the ...

Using Nest JS to Handle Null Responses in Services

When using Nest Js to call Axios and get data from the Facebook API, I encountered a problem where the service was returning a null value. Strangely, when I tried calling the response using console.log, it did return a value. Any suggestions on what I migh ...

An argument of type 'Array<T>' necessitates the inclusion of one type argument

I've come across this issue multiple times on various online forums. Despite trying different solutions, I'm still unable to resolve the following error: (11,23): Generic type 'Array' requires 1 type argument(s). This pertains to t ...

I'm puzzled by the error message stating that '<MODULE>' is declared locally but not exported

I am currently working with a TypeScript file that exports a function for sending emails using AWS SES. //ses.tsx let sendEmail = (args: sendmailParamsType) => { let params = { //here I retrieve the parameters from args and proceed to send the e ...

What could be causing this issue of the Angular Material table not displaying properly?

I have been developing a Contacts application using Angular 9 and Angular Material. The goal is to display contact information and an image for each contact in a table row within the list component. Within my app.module.ts, I have imported various modules ...

Exporting variables in Angular's Ahead of Time (AoT) compiler is

I recently attempted to incorporate dynamic configuration into my project, following a guide I found in this insightful post. While everything functions smoothly with the JiT compiler, I encountered the following error when attempting to build using the A ...

Subscribing to valueChanges in reactive forms to dynamically update checkbox options

My goal is to create a select dropdown with options for bmw, audi, and opel. The user can only select one option from the dropdown, but they should also have the ability to select the options that were not chosen using checkboxes. cars = [ { id: 1, na ...

`Angular: Enhancing User Data Presentation`

I'm currently tackling a project and I have a query on my hands. I'm fairly new to Angular and still navigating my way through Observables, Services, and interfaces. The task at hand involves creating a feature for an app that allows a user to v ...

Insufficient html content causing empty spaces on the page

Having trouble with my HTML layout - I want a main content area centered on the page with a sidebar that slides out from the left. Everything is working except for a large gap on the left side. How can I move my content to the left to fill the entire page ...

Leveraging the power of TypeScript and Firebase with async/await for executing multiple

Currently, I am reading through user records in a file line by line. Each line represents a user record that I create if it doesn't already exist. It's possible for the same user record to be spread across multiple lines, so when I detect that it ...

The TSOA Express application is experiencing difficulties in retrieving endpoints

Currently, I am working on developing a REST API using node.js and Typescript. To aid in the documentation process, I am utilizing tsoa and swagger. The build process is successful, and the swagger.json file is generated without any issues. However, when a ...

Is there a way to access a child component's method from the parent component using ref in Vue3?

I am encountering an issue while attempting to call the child method from the parent component in vue3 using the ref method. Unfortunately, an error is being thrown. Uncaught TypeError: addNewPaper.value?.savePaper is not a function Displayed below is m ...

Failure to link peer dependencies in NPM

This is my current package json setup: "devDependencies": { "@angular/common": "2.0.0-rc.4", "@angular/compiler": "2.0.0-rc.4", "@angular/core": "2.0.0-rc.4", "@angular/http": "2.0.0-rc.4", "@angular/platform-browser": "2.0.0-rc.4", ...

Angular4 ASP.NET Core project does not seem to be detecting the API endpoints

I am encountering an issue with my angular application where I consistently receive a "Cannot match any routes" error when attempting to access certain api resources. The base in my application is configured as <base href="/"> and the api source is ...