The Angular error message InvalidValueError is thrown when the Map function expects a mapDiv of type HTMLElement, but instead receives a

When attempting to initialize Google Maps, I encountered a particular problem.

In this div, I am trying to load the map but consistently receiving the same error message.

I attempted to use ngAfterViewInit() in case the view wasn't fully loaded before the function was called, but it did not resolve the issue.

Error Message (same as title) -

Uncaught (in promise): InvalidValueError: Map: Expected mapDiv of type HTMLElement but was passed null.

Here is my code:

map.component.ts -

import { Component, Input, OnInit } from "@angular/core";
import { Loader } from "@googlemaps/js-api-loader";
import { GoogleMapsService } from "src/app/Services/GoogleMapsService/google-maps.service";

@Component({
  selector: "app-maps",
  templateUrl: "./maps.component.html",
  styleUrls: ["./maps.component.scss"],
})
export class MapsComponent implements OnInit {
  @Input() inputVal: HTMLInputElement;

  constructor(private googlemapsService: GoogleMapsService) {}
  loader = new Loader({
    apiKey: API_KEY,
    version: "weekly",
  });

  ngOnInit(): void {
    console.log("YO");
  }
  ngAfterViewInit(): void {
    this.loader.load().then(this.googlemapsService.initMap);
  }
}

googlemaps.service.ts -

Import { Injectable } from "@angular/core";

let map: google.maps.Map;

@Injectable({
  providedIn: "root",
})
export class GoogleMapsService {
  constructor() {}

  initMap() {
    const mapOptions = {
      // center: this.userCenter,
      zoom: 8,
      mapTypeId: google.maps.MapTypeId.ROADMAP,

      panControl: true,
      mapTypeControl: false,
      panControlOptions: {
        position: google.maps.ControlPosition.RIGHT_CENTER,
      },
      zoomControl: true,
      zoomControlOptions: {
        style: google.maps.ZoomControlStyle.LARGE,
        position: google.maps.ControlPosition.RIGHT_CENTER,
      },
      scaleControl: false,
      streetViewControl: false,
    };
    const userCenter = new google.maps.LatLng(51.508742, -0.12085);

    const userCenterMarker = new google.maps.Marker({
      position: userCenter,
    });
    userCenterMarker.setAnimation(google.maps.Animation.BOUNCE);
    map = new google.maps.Map(
      document.getElementById("map") as HTMLElement,
      mapOptions
    );
  }
}

maps.component.html -

<input type="text" [(ngModel)]="inputVal" />

<div id="map"></div>

Answer №1

To ensure that the component only loads after the API has loaded, you can utilize the Angular HttpClient jsonp method when the component is actually being used.

For more information, check out this stackblitz. If you need further assistance, feel free to create and share your own stackblitz example.

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

The absence of @angular/compiler in the bundle file is causing an issue with Angular es

I've developed a shell application that operates using and https://github.com/systemjs/systemjs to manage its various micro-frontends. Recently, I created a new Angular application and aimed to integrate it with the esBuild builder tool. Upon runni ...

Creating dynamic components with constructor parameters in Angular 9

Having trouble passing a value to the constructor in the component generation code. Check out the original code here: https://stackblitz.com/edit/angular-ivy-tcejuo private addComponent(template: string) { class TemplateComponent { @ViewChild( ...

typescript dispatch issue

Whenever I attempt to send this dispatch, it consistently results in the following error message (and the same issue occurs with all my other dispatches): The argument of type '(dispatch: Dispatch) => Promise' is not compatible with a paramet ...

Removing a dynamic component in Angular

Utilizing Angular dynamic components, I have successfully implemented a system to display toaster notifications through the creation of dynamic components. To achieve this, I have utilized the following: - ComponentFactoryResolve - EmbeddedViewRef - Ap ...

How to handle type errors when using properties in Vue3 Single File Components with TypeScript

I've hit a roadblock while attempting to utilize properties in Vue3. Despite trying various methods, I keep facing issues during the type-check phase (e.g.: yarn build). The project I'm working on is a fresh Vue3-ts project created using Vite. B ...

Present boundaries shown on Google Maps using the ng-map library

I am currently utilizing ngmap.github.io in combination with the ionic framework. My goal is to dynamically obtain the current position using the following JavaScript code: google.maps.event.addListener(map, 'idle', function(){ var bounds = ...

No errors encountered during compilation for undefined interface object types

Hey there, I'm currently exploring the Vue composition API along with Typescript. I'm facing an issue where I am not receiving any errors when an interface does not align with the specified types for that interface. Although my IDE provides aut ...

Separate the label and content sections in an Angular Material vertical stepper

https://i.sstatic.net/S1gIH.jpg After applying the following CSS: mat-step-header{ display: flex ; justify-content: flex-end ; } I am attempting to make this stepper function properly. I have implemented Angular Material design for a vertical stepp ...

Addressing important problems post npm audit

I recently encountered some issues after running the npm audit command on a project that was just updated to angular 15. Upon inspection, the npm audit flagged a critical vulnerability related to hermes-engine with a fix available through the 'npm au ...

What could be causing my controller method in TypeScript to throw an error message unexpectedly?

Hey there. I'm diving into TypeScript and currently working on converting an Express backend to TS. Everything was smooth sailing until I encountered some unexpected issues. Specifically, the lines const hasVoted = poll.votedBy.some((voter): boolean = ...

After refreshing the page, the JWT token is no longer available

I've recently launched my app on Heroku at this link: Give it a try yourself to witness the issue. Everything seems to be working fine until you refresh the website. The JWT token is stored in LocalStorage but gets lost from the header upon page re ...

What is the method for bypassing libraries while troubleshooting Angular code in Visual Studio Code?

While debugging my Angular project, I keep getting into @angular/core and ts-lib which are large files with many steps. Is there a way to skip over external code during the debugging process? Below is my launch.json configuration: "version": &qu ...

Running an Angular application on dual hosts

Is it possible to host the same Angular application on multiple hosts, such as different IP addresses or ports, using Node.js? ...

Ways to change the CSS styling of the placeholder attribute within a textarea or input field tag

I am currently working on adjusting the font size of the text within the placeholder attribute of a textarea element. While I have been successful in achieving this using vanilla CSS, I have encountered difficulties when trying to implement the same concep ...

I am having issues with the Okta Angular sign-in widget as it is not redirecting

Recently, I integrated the Okta angular sign-in widget into my project, but I encountered an issue. In my application, I have multiple modules including an authentication module that manages sign-in, sign-out, and sign-up functionalities. The route I ult ...

Exploring Angular 2: Unveiling the secrets of lifecycle hooks in lazy loaded

Currently, I'm working on an application that involves lazy loaded Angular modules. I have a straightforward inquiry: Is there a way to detect an event once a module is loaded? For instance, similar to the OnInit lifecycle hook for components. I fo ...

When a ListView item is clicked, a label will display text with text wrapping specific to the selected item in the list

Within the listview items, there is a label that should expand when clicked. For example, initially it only shows one line of text. Upon clicking on the label, it should expand to show 10 lines of text. Current Issue: At present, when I click on the firs ...

Basic exam but located in a place that is not valid

Here is a test I am working on: // import {by, element, browser} from "protractor"; describe('intro', () => { beforeEach(() => { browser.get(''); }); it('should have multiple pages', () => { let buttonOn ...

What is the best way to transform all elements on a webpage into a dynamic scrolling marquee?

Is there a way to make every div in a web application scroll like a marquee? Perhaps by using a specific CSS class or other method? The application is built with Angular 4 and Bootstrap. ...

What is the best way to extract and retrieve the most recent data from an XmlHttpRequest?

Currently, I am using a web service that returns an SseEmitter to program a loading bar. The method to receive it looks like this: static async synchronize(component: Vue) { let xhr = new XMLHttpRequest(); xhr.open('PATCH', 'myUrl.co ...