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>