Search code examples
javascriptangulargoogle-mapstypescriptdirections

Unable to set angular variable inside callback


I'm using the google maps directions service to calculate the travel time.

this.mapsAPILoader.load().then(() => {
  const p1 = new google.maps.LatLng(50.926217, 5.342043);
  const p2 = new google.maps.LatLng(50.940525, 5.353626);

  const directionsService = new google.maps.DirectionsService();
  const request = {
    origin: p1,
    destination: p2,
    travelMode: google.maps.TravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.METRIC,
  };

  directionsService.route(request, (response, status) => {

    if (status === google.maps.DirectionsStatus.OK) {
      const point = response.routes[0].legs[0];
      // console.log(point.duration.text);
      this.travelTimeDriving = point.duration.text;
    }
  });


});

The console logs the correct driving time, but my variable this.travelTimeDriving stays empty.
I guess it had something to do with the callback function and scope but I can't fix it.
Also the route function returns void, no promise so I can't use .then()


Solution

  • Use NgZone to make sure the callback will be bind to the scope. Working sample:

    import { Component, OnInit, NgZone } from '@angular/core';
    declare const google: any;
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
      travelTimeDriving = '';
    
      constructor(private ngZone: NgZone) {}
    
      ngOnInit() {
        let mapProp = {
            center: new google.maps.LatLng(51.508742, -0.120850),
            zoom: 5,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        let map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
    
        const p1 = new google.maps.LatLng(50.926217, 5.342043);
        const p2 = new google.maps.LatLng(50.940525, 5.353626);
    
        const directionsService = new google.maps.DirectionsService();
        const request = {
          origin: p1,
          destination: p2,
          travelMode: google.maps.TravelMode.DRIVING,
          unitSystem: google.maps.UnitSystem.METRIC,
        };
    
        directionsService.route(request, (response, status) => this.ngZone.run(() => {
    
          if (status === google.maps.DirectionsStatus.OK) {
            const point = response.routes[0].legs[0];
            this.travelTimeDriving = point.duration.text;
          }
        }));
      }
    }