Utilizing JSON data from Google Maps Matrix with JavaScript

I am trying to fetch the real-time duration of a particular route on Google Maps through my JavaScript code. However, I seem to be stuck. Here's what I have written so far:

$(document).ready(function Duration() {
    var d = new Date();
$.ajax({
    url: 'http://maps.googleapis.com/maps/api/distancematrix/json?origins=91058%20Haupt%20Str.%6+DE&destinations=91058%20Cauerstr.%208+DE&mode=driving&language=de-DE&sensor=false&traffic_model=best_guess&departure_time='+(d.getTime()+300000),
    dataType: "json"
}).done(function(data) {
        var dur = data.rows[0].elements[0].duration.text;
        $("#duration").text(dur);         
    });
});

Simply want to display in HTML using:

<div id="duration"></div>

Would appreciate some assistance! Thank you in advance :)

Answer №1

For a successful execution of this task, it is essential to consult Google's documentation. Due to cross-domain restrictions, loading the requested resources may not be feasible. However, the provided code snippet should solve the issue: https://jsfiddle.net/Lw3Ls4yd/

Start by obtaining a Google Maps API key by registering here: https://developers.google.com/maps/documentation/javascript/get-api-key

Once you have acquired the key, insert it into your page at the appropriate location.

<script async defer src="https://maps.googleapis.com/maps/api/js?key'KEY HERE' type="text/javascript"></script>

Next, include the following JavaScript in your local environment:

var distanceService = new google.maps.DistanceMatrixService();
var d= new Date();
distanceService.getDistanceMatrix({
    origins: [ "Cauerstraße 8, 91058 Erlangen, Deutschland" ],
    destinations: [ "Hauptstraße 6, 48607 Ochtrup, Deutschland" ],
    travelMode: google.maps.TravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.METRIC,
    transitOptions: {
            departureTime:d
        },
    durationInTraffic: true,
    avoidHighways: false,
    avoidTolls: false
},
function (response, status) {
    if (status !== google.maps.DistanceMatrixStatus.OK) {
        console.log('Error:', status);
    } else {
        console.log(response);
        $('#duration').text(response.rows[0].elements[0].duration.text);
    }
});

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

When the clearOnBlur setting is set to false, Material UI Autocomplete will not

I recently encountered an issue in my project while using Material UI's Autocomplete feature. Despite setting the clearOnBlur property to false, the input field keeps getting cleared after losing focus. I need assistance in resolving this problem, an ...

From Google Assistant to Python Results

Is there a way to control a Bitcraze Crazyflie drone using Google Home? I'm looking to give the command "Drone fly to x3 y4" which will be processed through Firebase and result in the Google Assistant Output: "Flying to x3 y4". Additionally, I need an ...

Display every even number within the keys of objects that have values ending with an odd number

I need a way to print all even values that are paired with odd values in the object keys, but my code only works for arr1, arr3, and arr5. Can someone help me adjust the 'let oddArr' method (maybe using a loop) so that it will work for any array ...

Unable to view cross domain cookies within the browser's development tools

I am currently working on a web application that has an Angular front end running on http://localhost:4200 and a NodeJs backend running on http://localhost:3000. When a user successfully logs in, a cookie is set from the backend containing a token. However ...

When an item in the accordion is clicked, the modal's left side scroll bar automatically scrolls to the top. Is there a solution to prevent this behavior and

When I first load the page and click on the Sales accordion, then proceed to click on Total reported and forecasted sales, the scrollbar jumps back up to the top The marked ng-container is specifically for the UI of Total reported and forecasted sales He ...

What steps should I take to successfully install using npm if I keep encountering the same error?

Every time I attempt to install a package using npm, I encounter the following warning: npm WARN EBADENGINE Unsupported engine { npm WARN EBADENGINE package: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c7b3aeaba2b3be ...

What is the best way to retrieve data from the server for individual div elements?

Utilizing Laravel and JQuery to render the HTML is my current approach. <div id="div1">0</div> <div id="div2">0</div> <div id="div3">0</div> Each instance of 0 within the divs needs to be s ...

Creating a form submission event through Asp.net code behind

Is there a way to change the onsubmit parameter of a form in an asp.net project, specifically from the master page code behind of a child page? I am interested in updating the form value so that it looks like this: <form id="form1" runat="server" onsu ...

Dynamic Filtering with jQuery List

I'm attempting to create a dynamic filter list on keypress event. For example, if I type "It" into the input field, the elements that do not match this value will be hidden. I'm unsure if the code structure I have implemented below effectively ac ...

Navigating within fixed-positioned divs

I'm attempting to create something similar to the layout seen on: The desired effect is to have fixed content on the right side, with only the left side scrolling up to a certain point before the entire page scrolls normally. However, in my implement ...

Incorporating live text into a tag while arranging items by price in both ascending and descending order

I recently added a button to my online shop that allows users to sort products by price, even though I don't fully understand the underlying JavaScript code. I want to enhance this button by updating the text to indicate whether the sorting order is ...

Exploring VBA-JSON to extract a JSON array within a JSON object seamlessly in VBA Excel

I am currently working on implementing VBA macros to retrieve real-time data from a website using API calls. To achieve this, I have incorporated the VBA-JSON library into my project. There are two main scenarios that arise when fetching the data: Scenari ...

What are some strategies for stopping a form from redirecting me while utilizing ReactJS and ExpressJS?

Recently, I created a form that redirects to the route /repair upon submission with an action of /repair. However, I would prefer to keep it as a Single Page Application (SPA) where after submitting the form, the fields are cleared, and a simple message l ...

What is the reason behind the undefined value of "this" in this particular class method?

I have scoured the depths of the internet in search of a solution, but I am still grappling with an issue related to a JS class I am developing for a Micro Service (still learning as I go). When attempting to call a method within a class on an instantiate ...

Guide on sending JSON data to a server and receiving JSON/XML in response with JSP

I am new to developing web applications. I have successfully created a dynamic web project using Java EE on a Glassfish server. Now, I am trying to enable clients to send data to the server using JSON and receive data from the server in either JSON or XML ...

Tips on retrieving the API response using AJAX

Currently, I am attempting to retrieve the API response from Flickr using Ajax in my application built with Laravel. To accomplish this, I have established a specific Route and function dedicated to handling API calls. //Route.php Route::post('/getlo ...

Reorganize the layout of a Python dictionary with the help of recursion

I am working with a dictionary that contains data for "Land" and "Air": { "Land": { "2018": { "VALUE:Avg": 49.0, "VALUE:Sum": 49.0 }, "2008": { ...

Python script used to extract data from Vine platform

I am looking to extract post data, such as title, likes, shares, and content, from various brands' public accounts on Vine using Python. Currently, I have a few ideas in mind: There is a Vine API called Vinepy available on GitHub (https://github.c ...

Displaying paginated results in the header instead of using JSON in Laravel 5

Currently, I am faced with the challenge of implementing pagination for search results in my Laravel API. While browsing through the documentation, I stumbled upon a solution at https://laravel.com/docs/5.3/pagination#converting-results-to-json, which appe ...

Setting up Socket.io results in numerous transport polling GET requests being initiated

I have set up an express.js server-side and followed the socket.io guide. However, I am facing issues with the socket connection not being successful, and there seems to be a high number of unexpected GET requests like this: https://i.stack.imgur.com/GDGg ...