I am trying to change the center of a map within a dynamic script. The issue is that I do get the data that I am subscribing to, but it does not change the center of the map. I tested this out by creating a setInterval() within the component and seeing if the data changes, after I execute the method outside the component. Here is an example of the code
https://codesandbox.io/s/joey-basic-gmaps-lw5d4
export class AppComponent implements OnInit, OnChanges {
public markerLat = 39;
public markerLng = -76;
title = "CodeSandbox";
private apiKey = environment.googleMapsAPIkey;
constructor(private data: DataService) {
const dynamicScripts = [
"https://maps.googleapis.com/maps/api/js?key=" + this.apiKey
];
for (var i = 0; i < dynamicScripts.length; i++) {
const node = document.createElement("script");
node.src = dynamicScripts[i];
node.type = "text/javascript";
node.async = true;
node.charset = "utf-8";
document.getElementsByTagName("head")[0].appendChild(node);
}
}
ngOnInit() {
this.data.markerLat.subscribe(markerLat => this.markerLat = markerLat);
this.data.markerLng.subscribe(markerLng => this.markerLng = markerLng);
setTimeout(() => {
this.initMap();
}, 1000);
}
ngOnChanges() {
setTimeout(() => {
this.initMap();
}, 1000);
}
ngOnDestroy() {
this.data.markerLat.subscribe(markerLat => this.markerLat = markerLat).unsubscribe();
this.data.markerLng.subscribe(markerLng => this.markerLng = markerLng).unsubscribe();
}
initMap() {
const google = window.google;
const center = { lat: this.markerLat, lng: this.markerLng };
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 8,
center: center
});
const marker = new google.maps.Marker({ position: center, map: map });
}
}