'ANGULAR InvalidValueError: Map: Expected mapDiv of type HTMLElement but was passed null
I have this problem when trying to initialize google maps. As you can see Im trying to load the map in this div but I always get the same message.
tried using
ngAfterViewInit()
because I thought maybe the view doesn't finish loading before the function is called but it didn't help.
Error Message (same as title) -
Uncaught (in promise): InvalidValueError: Map: Expected mapDiv of type HTMLElement but was passed null.
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>
Solution 1:[1]
The API can be loaded when the component is actually used by using the Angular HttpClient jsonp method to make sure that the component doesn't load until after the API has loaded.
Try looking at this stackblitz. If that doesn't spark something, maybe share a stackblitz of your own.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | mathewspete |