Having difficulty updating an angular variable within a callback function

Currently, I am utilizing the Google Maps directions service to determine the estimated 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;
    }
  });


});

While the console is displaying the accurate driving time duration, my variable `this.travelTimeDriving` remains empty.
I suspect that this issue is related to the callback function and scope, but unfortunately, I am unable to resolve it.
Moreover, since the route function does not return a promise, I am unable to utilize `.then()` for handling.

Answer №1

Utilize NgZone for ensuring that the callback is properly bound to the scope. See below for a functioning example:

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

Answer №2

It appears that the scope may not be what you were expecting. In most editors/IDEs, this would result in an error when trying to reference

this.travelTimeDriving = point.duration.text;

If your scope is incorrect or the variable is not declared where you expect it to be, then you might need to check if the variable is declared in the class members of the function being called.

A quick way to troubleshoot this is by logging the value right after setting it to see the result.

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

To better understand the scope at that point, consider using console.log or setting a breakpoint to inspect the value.

If you can provide more context by sharing surrounding code, it will make it easier to assist you further.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sharing environment variables in gulpfile with other JavaScript files outside NODE_ENV

Is it possible to pass a variable other than NODE_ENV from the gulpfile.js to another javascript file? gulpfile.js // Not related to NODE_ENV! let isDevelopment = true; somejsfile.js /* I need to access "isDevelopment" from the gulpfile.js... For the ...

Link AngularJS service array length property to the controller's scope through binding

I am attempting to connect the length of an array from another service to my controller's scope in the following manner: app.controller('TestCtrl', function ($scope, safePostService) { $scope.count = safePostService.queue.length; $ ...

AngularJS is experiencing issues with the sorting filter 'orderBy'

I am experiencing an issue with sorting a table list that has three columns. I have implemented the ability to sort all columns in ascending and descending order. However, when I click on the -Tag to initiate the sorting process, I encounter the following ...

Creating dynamic keys to insert objects

In my coding project, I am dealing with an empty array, a value, and an object. Since there are multiple objects involved, I want to organize them into categories. Here is an example of what I envision: ARRAY KEY OBJECT OBJECT KEY OBJECT ...

What is the reason behind JavaScript's restriction on using double comparison operators?

What is the reason behind javaScript not supporting double comparison? For example, in 64 < str.charCodeAt(i) && str.charCodeAt(i)<=77, why is it not possible to simplify it to 64 < str.charCodeAt(i)<=77? ...

retrieve data properties from an object

Suppose I have the following setup: var myObj = [ { name: 'A', number: 'b1', level: 0 }, { name: 'B', number: 'b2', level: 0 }, ]; I need to figure out how to retrieve all the names and format them like this: ...

Utilizing Google Analytics 4 in a React TypeScript Environment

Currently, there are two options available: Universal Analytics and Google Analytics 4. The reasons why I lean towards using Google Analytics 4: Universal Analytics is set to be retired on July 1, 2023, so it makes sense to start fresh with Google Analyt ...

Adjust the size of the div to fit its content while maintaining the transition animation

I am aiming for the DIV height to automatically adjust to the text within it, while also maintaining a minimum height. However, when the user hovers their mouse over the DIV, I want the height to change smoothly without losing the transition effect. When ...

Is it possible to have two different actions with two submit buttons in PHP?

Here is my form tag: sample name:register.php page <form id="formElem" name="formElem" action="form10.php" method="post"> <input id="pd" name="pd" type="text" AUTOCOMPLETE=OFF /> <input id="pd1" name="fname" type="text" AUTOCOMPLETE=OFF /& ...

Error when spaces are present in the formatted JSON result within the link parameter of the 'load' function in JQuery

I am facing an issue with JSON and jQuery. My goal is to send a formatted JSON result within the link using the .load() function. <?php $array = array( "test1" => "Some_text_without_space", "test2" => "Some text with space" ); $json = jso ...

Transform a string into a boolean value for a checkbox

When using v-model to show checked or unchecked checkboxes, the following code is being utilized: <template v-for="(item, index) in myFields"> <v-checkbox v-model="myArray[item.code]" :label="item.name" ...

How can an Angular Component be created in the browser using the standard method?

Attempting to develop a basic Angular example using JS/ESM. It has been some time since working within the angular environment, and there appear to be two primary choices: Utilizing the UMD lib (preferably to be avoided) Using the ESM2015 folder and loadi ...

Discover the array of results by implementing a while loop in JavaScript

My goal is to create a list of outputs that are not evenly divisible by numbers smaller than the input value. For example, if the input value is 10, the list should be 10, 9, 8, 7, 6, 4, 3, 1. I have written some code in JavaScript for this purpose, but ...

What is the best approach for presenting MySQL data on an HTML div through Node.js?

When working with Node.js, I prefer using Express as my framework. Here is the AJAX code I have on my member.ejs page: function load_member(){ $.ajax({ url: '/load_member', success: function(r){ console.lo ...

Having issues installing Parcel through npm - Encountered an error while parsing package.json information

After creating a package.json file using the command npm init in my project folder, I proceeded to run npm i parcel --save-dev which resulted in an error message: C:\Users\XPRESS\Desktop\starter>npm i parcel --save-dev npm ERR! code ...

Looking for a method to substitute "test" with a different value

Showing a section of the menu using <li id="userInfo" role="presentation" data-toggle="tab" class="dropdown"> <a href="#" name="usernameMenu" class="dropdown-toggle" data-toggle="dropdown" role="button"> <span class="glyphicon glyph ...

The process of upgrading all dependencies to a particular version

I need guidance on upgrading a project from Angular 6 to version 7. The challenge lies in updating numerous dependencies as well. Most tutorials available only cover upgrading to the latest version (v8), rather than a specific one. Can anyone provide ins ...

Troubleshooting: Android compatibility issue with Angular Capacitor iframe

Issue with loading iframe on Android using Angular and Capacitor I have been attempting to use two different iframes in various forums, but unfortunately, it has not resolved my issue. While everything looks fine on Chrome, the iframe fails to load on And ...

What is the best way to ensure my button displays the complete description of a single country after showcasing all the countries?

I have designed a search feature for countries and I am looking to add a button next to the country names that will trigger one of my components responsible for displaying detailed information about the country. Currently, the details are shown only when t ...

Make sure to verify if all values are contained within an array by utilizing JavaScript or TypeScript

These are the two arrays I'm working with. My goal is to ensure that every value in ValuesToBeCheckArr is present in ActualArr. If any values are missing from ActualArr, the function should return 0 or false. Additionally, there is an operator variabl ...