0

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 });
  }
}

Jonathan
  • 441
  • 1
  • 9
  • 28

1 Answers1

1

Since you are getting data from asyn source the excution order of initMap will differ. Move your initMap method inside subscribe block. Use forkJoin to get lat and lng observable to get complete first.

Try this

    import { forkJoin } from 'rxjs';

    export class AppComponent implements OnInit, OnChanges {

    ngOnInit() {
       const latLng = forkJoin(
       this.data.markerLat,
       this.data.markerLng
       ).subscribe(([markerLat, markerLng])=>{
        this.markerLat = markerLat;
        this.markerLng = markerLng;
        this.initMap();
     })
   }
 }
Chellappan வ
  • 23,645
  • 3
  • 29
  • 60