Learn how to use a function in Google Maps to calculate and display distances

I have a script obtained from this link here and I am trying to create a function that returns the distance. This is my current script:

var calcRoute = function(origin, destination) {
    var dist;
    var directionsDisplay;
    var directionsService = new google.maps.DirectionsService();
    directionsDisplay = new google.maps.DirectionsRenderer();
  var request = {
    origin:origin,
    destination:destination,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
      dist = response.routes[0].legs[0].distance.value / 1000;
    }
  });
    return dist;
};
$scope.resto = calcRoute("-7.048357, 110.418877","-7.048443, 110.441022");

I have included two parameters in the function, and I expect it to return the distance. However, the script does not seem to be returning the value from

dist = response.routes[0].legs[0].distance.value / 1000
.

I am using angularjs and the resto in my View is not displaying the distance. Can anyone help me? Is there something wrong with the script or is it something else?

Answer №1

Before the function directionsService.route is called, the function calcRoute has already run and returned the value of dist, which will be undefined at that point.

The correct way to access the value is inside the callback function of directionsService.route.

To achieve this, you can add another parameter (a callback function) to the calcRoute function. This way, once directionsService.route responds, you can pass the value to this new callback function.

Give it a try!

var calcRoute = function(origin, destination, cb) {
    var dist;
    var directionsDisplay;
    var directionsService = new google.maps.DirectionsService();
    directionsDisplay = new google.maps.DirectionsRenderer();
    var request = {
        origin: origin,
        destination: destination,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    
    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
            cb(null, response.routes[0].legs[0].distance.value / 1000);
        } else {
            cb('pass error information');
        }
    });
};

calcRoute("-7.048357, 110.418877", "-7.048443, 110.441022", function(err, dist) {
    if (!err) {        
        $scope.resto = dist;
    }
});

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

Is it possible to use JavaScript for detecting third-party videos?

I'm currently developing an HTML5 video player that also has a fallback to flash. One of the challenges I am facing is that the video content is being provided by various third-party sources. It seems that some of these third parties serve videos bas ...

unable to retrieve the response from a POST request sent to a node server

Currently in the process of learning how to utilize node and express, I have embarked on creating a sample website that incorporates both along with the Google translate API. The goal is to explore the numerous features offered by these technologies. Unfor ...

Error: The function 'myAppController' is not defined and is therefore not a valid argument

I am trying to incorporate my service into my controller and print a message to the console (in the Auth Service), but I keep encountering this error: Argument 'myAppController' is not a function, got undefined. Can you help me figure out what I& ...

Adjust the size of a map on an HTML page after it has

Currently, I am utilizing Angular 2 to create a simple webpage that includes a Google 'my map' displayed within a modal. <iframe id="map" class="center" src="https://www.google.com/maps/d/u/0/embed?mid=1uReFxtB4ZhFSwVtD8vQ7L3qKpetdMElh&ll ...

Troubleshooting a problem with $addToSet and $each in Mongo and Node.js

I'm facing an issue while using $addToSet to add an array of Strings to a MongoDB database. The Object setup is defined as follows: var mongoose = require('mongoose'); var Schema = mongoose.Schema; module.exports = mongoose.model('Co ...

Connecting Vue.js components together

I have two separate components - one for viewing data and another for editing the same data. The viewing component contains labels and paragraphs, while the editing component includes inputs and textareas. Both components are fed the same data object. Is ...

Enhanced JavaScript Autocompletion in Integrated Development Environments

What is the inner workings of Intellisense in IDEs like Webstorm and Eclipse for JavaScript? From which source do the suggestions originate? Is it possible to tweak the code to enhance the accuracy of the suggestions? https://i.sstatic.net/ZVBB3.png ...

How can you convert a JavaScript object with nested arrays into JSON format?

I have been working with a JavaScript object that contains nested objects with associative arrays. I attempted to use the stringify function from the json2.js library, but the output did not include the arrays inside the nested objects. In my scenario, I b ...

Adjust parameters using JavaScript and three.js in real-time

I am not well-versed in JavaScript and I am facing an issue. I need to dynamically change the parameter passed to a function written in JavaScript, but the code is structured in a way that is unfamiliar to me. Therefore, I am seeking assistance. On my web ...

What is the best way to choose an option from a <select> dropdown using Angular's Protractor version 0.24?

I've noticed that Protractor is constantly improving, and I'm currently on version 0.24. However, I'm struggling to figure out how to simulate clicking a value from a <select> list. Could anyone provide an example of how they select a ...

Tips for maintaining a sticky header while continuing to utilize Bootstrap table classes such as table-responsive and table-stripped

This is Here's my code on jsfiddle I've attempted to make the header sticky while maintaining the current layout, but every approach I've tried ends up messing with the responsiveness of the table. My next plan involves using a JavaScript ...

Utilizing Directives to Embed Attributes

My current challenge involves changing the fill color of attributes in an in-line SVG using Angular and TypeScript. The goal is to have the SVG elements with a "TA" attribute change their fill color based on a user-selected color from a dropdown menu. Howe ...

The beta version of Angular 2.0 introduces the BrowserDomAdapter for easy access to the DOM

I have a Component in Angular 2.0 that is attempting to utilize the DOM Adapter API from Angular's BrowserDomAdapter documentation. The initialization of this DomAdapter can be found here. However, I am uncertain about whether the Dom Adapter needs t ...

Error: Unable to convert Mongoose object to ObjectId

Currently tackling an issue with my small blog app and I seem to be stuck at this error- { "message": "Cast to ObjectId failed for value \" 597c4ce202ca9c353fc80e8a\" at path \"_id\" for model \"Blog\"", "name": "CastErr ...

Template for child directive failing to reflect scope updates

I am working on a custom directive that includes child directives: <rp-nav> <rp-nav-item cat="1"></rp-nav-item> <rp-nav-item cat="2"></rp-nav-item> <rp-nav-item cat="3"></rp-nav-item> <rp-nav-it ...

Convert the jQuery functions click(), hide(), and fadeIn() into their equivalent native JavaScript functionalities

I'm determined to speed up my page by reducing requests. Does anyone have a solution for keeping the functionality of the code below without having to load the entire JQuery library? $("#div1").click(function () { $("#div2).hide(); $("#div3). ...

Effortlessly submit form data in Codeigniter without the need for page refreshing using jQuery ajax

I've been working on submitting form data in the codeigniter framework using ajax and jQuery to prevent page refreshing, but I keep getting a fail message. Since I'm new to ajax, can someone help me troubleshoot this error? This is my Controlle ...

Adjust the border color of Material UI's DatePicker

https://i.sstatic.net/ZvNOA.png Hello everyone, I am currently working with a DatePicker component from Material UI. My main goal is to change the border color of this component. I have attempted various methods such as modifying classes, adjusting the th ...

Angular UI date picker is currently experiencing an issue where the short date format is displaying incorrectly, showing past dates

The UI date picker is displaying the wrong date when a short date format is selected and a date from a previous year like 1921 is chosen. Instead of showing 1921, it displays as if it were in year 2021. This behavior is not correct and should show the sele ...

"Node.js is giving an error stating that the object does not have a

I am attempting to save the user details from the registration form into a JSON file for authentication purposes. However, I am having trouble appending the data in the correct format. Here is the code snippet that I have tried: var filename = "./user_log ...