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

Angular template error: Potential is present but not defined

Encountering an issue with my Angular application's template file (dashboard.component.html). The error message reads "Object is possibly 'undefined'." Here's the portion of the template that seems to be causing the problem: <div> ...

LeafletJS tiles are only loaded once the map is being actively moved

Currently, I am facing an issue while trying to load a simple leaflet map in my Ionic 2 application. The problem is that not all tiles are loading correctly until the map is moved. this.map = new L.Map('mainmap', { zoomControl: false, ...

Tips for accessing and adjusting an ngModel that is populated by an attribute assigned via ngFor

Looking for guidance on how to modify an input with ngModel attribute derived from ngFor, and update its value in the component. Here is my code snippet for reference: HTML FRONT The goal here is to adjust [(ngModel)] = "item.days" based on button click ...

Is there a way to integrate a calendar feature within an Angular 2 application?

I am brand new to Angular 2 and have a question: I need to integrate a calendar into a page where users can add events. Something similar to the following example: I'm unsure if the angular material calendar project is designed for Angular 2 or for ...

Halt of dispatcher playback occurs after a duration of 10 minutes with discord.js

Currently, I've been working on a music bot using discord.js. To handle audio streaming, I'm utilizing @discordjs/opus and ytdl-core-discord. Everything runs smoothly when testing the bot locally on my machine - songs from YouTube are played with ...

Simulate an HTTP request from a service class during a jasmine test

I initially believed that spying on services in Jasmine using the spyOn method and returning a value when the method is called was straightforward. However, it seems like my assumption may have been too simplistic? I intend to test the following action in ...

Challenge encountered with asynchronous angular queries

Dealing with asynchronous calls in Angular can be tricky. One common issue is getting an array as undefined due to the asynchronous nature of the calls. How can this be solved? private fetchData(id){ var array = []; this.httpClient.get('someUrl ...

Putting VueJS, typescript, and jest to the test: examining the contents of a dropdown list web-component

Currently, I am in the process of testing a dropdown list within a web component utilized in a VueJS application. My main focus is on checking whether the dropdown list actually contains items fetched through an HTTP query (handled in a vuex store) once t ...

"What is the significance of the .default property in scss modules when used with typescript

When dealing with scss modules in a TypeScript environment, my modules are saved within a property named default. Button-styles.scss .button { background-color: black; } index.tsx import * as React from 'react'; import * as styles from ' ...

Struggling to find the definition of a Typescript decorator after importing it from a separate file

Consider the following scenario: decorator.ts export function logStuff(target: Object, key: string | symbol, descriptor: TypedPropertyDescriptor<any>) { return { value: function (...args: any[]) { args.push("Another argument ...

Encountering a "undefined response" issue within an Angular

I am encountering an issue when trying to fetch data from a REST API. Upon logging the response, I am getting an undefined value. How can I resolve this? I have confirmed that the API is sending data by checking my network tab in the developer tool. getPro ...

Listen for key events on an entire component or div in Angular using HostListener

Experimenting with this code in angular 8: @HostListener('keydown.shift.tab', ['$event']) onKeyDown(e) { // you can use preventDefault() to stop other events from triggering e.preventDefault(); console.log(& ...

Enhance your webpage design with stylish CSS formatting using Bulma cards

My HTML output is as follows: https://i.stack.imgur.com/aBdEF.jpg It seems that the footer is not matching up with the cards... The CSS component I am using looks like this: .card-equal-height { display: flex; flex-direction: column; height: 100%; ...

What is the best way to include a non-data custom attribute in a TSX template without any value?

Currently, I am working on a React component with Typescript. The initial code looks like this.... const NameFormatter = React.createClass({ render() { return ( <div> <div className="dataset-name"> ...

Loop through JSON results in Ionic using Angular

I am struggling to retrieve data from a JSON file in Object format using Typescript. When I try to fetch the data from the API, it doesn't display as expected. Typescript this.http.get('http://example.com/api') .subscribe((data) => { ...

"I am looking for a way to receive a response from a loopback in Angular7

Currently, I am utilizing angular7 with loopback. While I can successfully retrieve data, I am unsure how to receive error messages and response statuses. It would be helpful for me to understand what my response code is at the time of the request. Output ...

Using Typescript to extract the type from within the function type parameters

I am currently utilizing an imported type definition that contains a function type definition with a fairly complex parameter type: export interface SomeTypeDefinition { someFunction: ( param1: string, param2: { key1: number, key2: s ...

Implementing real-time style changes with Angular 6 through Environment Variables

Attempting to dynamically change styles in Angular 6 using environment variables has been a success for me. Here is how my file structure is organized: src -app -assets -environments -scss -theme1.scss -theme2.scss -_variables.scss -styles.sc ...

Having two buttons in Protractor with identical text displayed

Hello, I'm encountering an issue with my Protractor e2e test: The problem is that I have a menu with a sub-menu. Both the main menu and the sub-menu contain buttons with the same name text (let's call it "menuItem"). I know how to locate and cli ...

Testing the open dialog with a unit test case

I encountered an issue while writing a unit test case for the open dialog feature in Angular 7. A TypeError is being thrown: "Cannot read property 'debugElement' of undefined." I am seeking assistance from anyone who can help me troubleshoot this ...