Khan
Khan

Reputation: 5204

Angular 9 & google map marker click event not working proprly

Below is my code to initiate map and add cluster and markers. everything is working fine, but the marker click is behaving weird like the event is triggered instantly and hit API as well, but the global variables are updated after few seconds, sometime after minutes.

  renderMap() {

    window['initMap'] = () => {
      this.loadMap();
    };
    if (!window.document.getElementById('google-map-script')) {
      const s = window.document.createElement('script');
      s.id = 'google-map-script';
      s.type = 'text/javascript';
      s.src = 'https://maps.googleapis.com/maps/api/js?key=' + environment.GOOGLE_MAP_API_KEY + '&callback=initMap';

      window.document.body.appendChild(s);
    } else {
      this.loadMap();
    }
  }

  loadMap() {
    const map = new window['google'].maps.Map(this.mapElement.nativeElement, {
      center: {lat: this.center.lat, lng: this.center.lng},
      zoom: this.zoom
    });
    const markers = this.markers.map((location, i) => {
      const marker = new google.maps.Marker({
        position: {lat: location.lat, lng: location.lng},
        label: location.label,
        icon: 'assets/img/marker_.png',
        title: location.title,
        clickable: true
      });

      marker.addListener('click', () => {
        const m = location;
        this.customer = m;
        this.showLocation = true;
        this.loading = true;
        this.center = {
          lat: m.lat,
          lng: m.lng
        };
        this.companyService.company(m.company_id).subscribe((company: any) => {
          this.company = company;
          this.loading = false;
        }, error => {
          this.loading = false;
          console.log(error);
        });
      });
      return marker;
    });

    const markerCluster = new MarkerClusterer(map, markers,
      {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});

  }

  ngOnInt(){
    this.renderMao();
  }

Upvotes: 0

Views: 3141

Answers (1)

kvetis
kvetis

Reputation: 7341

You probably need to run the click callback in NgZone

constructor(private zone: NgZone)


marker.addListener('click', () => {
    this.zone.run(() => { 
     ...
});

Upvotes: 2

Related Questions