Finding the distance between two points in JavaScript requires a simple formula

Here is a code snippet that generates two TRACER points and displays them on a map, as well as shows the union between the two points.

<?php 
$latitudInicio = $_GET['latitudInicio'];
$longitudInicio = $_GET['longitudInicio'];
$latitudFin = $_GET['latitudFin'];
$longitudFin = $_GET['longitudFin'];
?>
<!DOCTYPE html>
<html>
 <body>
  <div id="map" style="width: 100%; height: 700px;"></div>
   <script>
    function initMap() {
        var inicio = {lat: <?php echo $latitudInicio ?>, lng: <?php echo $longitudInicio ?>};
        var fin = {lat: <?php echo $latitudFin ?>, lng: <?php echo $longitudFin ?>};
        var map = new google.maps.Map(document.getElementById('map'), {
            center: inicio,
            zoom: 7
        });

        var inicioMarker = new google.maps.Marker({
            position: inicio,
            map: map,
            title: '<?php echo $latitudInicio ?> <?php echo $longitudInicio ?>'
        });
        var finMarker = new google.maps.Marker({
            position: fin,
            map: map,
            title: '<?php echo $latitudFin ?> <?php echo $longitudFin ?>'
        });

        var directionsDisplay = new google.maps.DirectionsRenderer({
           map: map,
            suppressMarkers: true
        });

        var request = {
            destination: fin,
            origin: inicio,
            travelMode: 'DRIVING'
        };

        var directionsService = new google.maps.DirectionsService();
        directionsService.route(request, function(response, status) {
            if (status == 'OK') {
                // Display the route on the map.
                directionsDisplay.setDirections(response);
            }
        });
    }

   </script>
   <script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap"
    async defer></script>
  </body>
 </html>

I am looking to calculate the distance and time between both TRACER points and display it in an input or label field.

I found information in the documentation at this link:

https://developers.google.com/maps/documentation/distance-matrix/start?hl=es

I have managed to fetch a JSON response with distance and duration data, but I am unsure how to incorporate this into my HTML for display purposes.

 {
   "destination_addresses" : [ "New York, NY, USA" ],
 "origin_addresses" : [ "Washington, DC, USA" ],
 "rows" : [
    {
       "elements" : [
         {
           "distance" : {
                "text" : "225 mi",
              "value" : 361715
           },
           "duration" : {
              "text" : "3 hours 49 mins",
              "value" : 13725
           },
           "status" : "OK"
           }
        ]
      }
   ],
   "status" : "OK"
}

If you know how to implement this JSON data to display it in a label, your help would be greatly appreciated!

Answer №1

It seems like you are attempting to showcase data from JSON on a webpage or possibly within maps using an API.

If your goal is simply to extract the data from JSON:

var dataObject = JSON.parse(yourJson)

You can then manipulate the data as you would with any regular object in JavaScript. For example, if you want to display distance in miles, you can do:

var distance = dataObject.rows.elements.distance.text

and then insert this into an HTML element (the method may vary depending on the libraries and frameworks you are using, but vanilla JS would be)

1 - Add an id attribute to the element where you want to display the data, for instance a paragraph:

<p id="distanceMiles"></p>

2 - Update the text of that element with the extracted data from JSON:

document.getElementById("distanceMiles").innerHTML = distance;

If you need to display text directly on maps, although I haven't personally used the GM API, there are resources available such as:

how to make overlay GM API v3

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

What could be the root cause behind the error encountered while trying to authenticate a JWT?

I've been working on integrating a Google OAuth login feature. Once the user successfully logs in with their Google account, a JWT token is sent to this endpoint on my Express server, where it is then decoded using jsonwebtoken: app.post('/login/ ...

Transform a log file into a JSON structure

In my log file titled request.log, the following entries are present: [2022-06-30T09:56:40.146Z] ### POST https://test.csdf/auth/send_otp { "method": "POST", "headers": { "User-Agent": "testing&q ...

Executing AngularJS Accordion event on a webpage

Hello, I am new to using AngularJS and I am currently working on implementing an accordion feature. The accordion is used to display a list of channels on the site. However, I am encountering an issue with the implementation. I want the accordion to be hi ...

Tips for disabling automatic scrolling when a browser is reloaded using JavaScript

In today's world, most browsers automatically adjust the window scroll position upon page refresh. While this is generally a helpful feature, I find myself in a situation where I need to reload a page and direct focus to a different part of the page t ...

Unable to loop through using ngFor

I have a component that retrieves data from the back-end and groups it accordingly. Below is the code snippet: getRecruitmentAgencyClientPositions(): void { this._recruitmentAgencyClientsService.getRecruitmentAgencyClientPositions(this.recruitmentAge ...

New from Firefox 89: The afterprint event!

Having an issue with this fragment of code: const afterPrint = () => { this.location.back(); window.removeEventListener('afterprint', afterPrint); }; window.addEventListener('afterprint', afterPrint); window.print(); I&apos ...

Issues encountered when incorporating personalized CSS into a Vuetify element

Working with the Vuetify selector input component, v-select, and wanting to customize its style led me to inspecting it in Chrome and copying down the necessary classes. For instance, to change the font size of the active value, I utilized: .v-select__sel ...

The Markdown-to-jsx tool is having trouble processing the provided source code

Utilizing a Material UI blog post template found at https://github.com/mui-org/material-ui/tree/master/docs/src/pages/getting-started/templates/blog, I have created my React app using npx create-react-app. Upon console logging the source, it displays as a ...

Tips for enlarging an image by tapping on it in handlebars

I currently have the handlebars template engine integrated with node.js, and I'm facing an issue where thumbnail images from the database are displaying at a fixed width and height of 70. Is there a way to enable users to click on these images in orde ...

Is it possible to disable the timeout for a single call using Axios?

I have set up an axios client instance in my application like this: const backendClient = axios.create({ baseURL: window['getConfig']?.url?.backend, httpsAgent: new https.Agent({ rejectUnauthorized: false }), timeout: window['getConfig ...

What's causing the "Uncaught SyntaxError: Unexpected token u" error to consistently pop up in Chrome?

I've been trying to figure this out all day by searching online, but I'm still stuck. My code is quite long and runs fine in Firefox, but Chrome throws an error: "Uncaught SyntaxError: Unexpected token u". Could someone please point out where I ...

Caution: Anticipated the server's HTML to include a corresponding <body> within a <div> tag

Upon checking the console, I noticed a warning message appearing. I am puzzled as to why this is happening since I have two matching <body> tags in my index.js file. The complete warning message reads: Warning: Expected server HTML to contain a matc ...

Should Errors be Handled in the Service Layer or the Controller in the MVC Model?

Currently, I am in the process of developing a Backend using Express and following the MVC Model. However, I am uncertain about where to handle errors effectively. I have integrated express-async-errors and http-errors, allowing me to throw Errors anywher ...

Oops! Looks like there was an issue with defining Angular in AngularJS

I am encountering issues while attempting to launch my Angular application. When using npm install, I encountered the following error: ReferenceError: angular is not defined at Object.<anonymous> (C:\Users\GrupoBECM18\Documents&bs ...

Tips for sending multiple pieces of data to an Arduino with NodeJS's serialport library

I am having trouble writing multiple data using the same port, but I see that node-serialport allows for reading multiple data functions simultaneously. How can I also write multiple data at the same time? This is how I have attempted it: - index.js- con ...

Look into HTML and JavaScript problems specific to IOS devices

I have encountered some HTML markup and JavaScript functionality issues on my web-app that seem to only occur on iPad and iPhone. Unfortunately, I do not have access to any iOS devices to debug these problems. How can I replicate and troubleshoot these i ...

The property 'caseSensitive' is undefined and cannot be read

After creating a simple code, I am puzzled by an error message that seems to be case sensitive. However, the code appears correct based on my understanding. Here is the code snippet: App.js const express = require('express'); const path = requir ...

Unable to display the value of my array in JSON encoded PHP due to it being undefined

In my cart.php file, I have encoded an array to JSON and returned it to an AJAX function: $data = array(); $data['total'] = '10000'; $data['quantity'] = '10'; echo json_encode($data); In my index.php f ...

The Magnificent jQuery Widget Factory's _trigger Instance

When utilizing the _trigger function to initiate events, I often come across a recurring issue that I struggle to fully comprehend. The problem arises when there are multiple instances of my widget on the same page. In such cases, the most recently instan ...

Retrieve elements from a separate pom file

I am looking to organize my web elements by defining them in a separate js file from my test file using Protractor. In my pom.js object, I have set up the following: let web_elements = function() { this.get_login_mail, function() { ...