Obtaining travel time and route information using the Google Maps API

I have a vision of something similar to what is shown in the image, but I'm not sure if it's actually possible or how to get started. Can anyone provide guidance on whether this can be achieved and if so, how? Alternatively, if you know of any online examples that are similar and functional, please share. Thank you in advance.

Answer №1

After discovering the solution on my own, I realized that it is indeed possible thanks to jfvanderwalt for providing the helpful link to the Google Docs for Direction API. This led me to a working example of what I needed and how to implement it. You can view my working demo here. Javascript :

    <script>

var rendererOptions = {
  draggable: true
};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);;
var directionsService = new google.maps.DirectionsService();
var map;

var australia = new google.maps.LatLng(41.171418,28.311553);

function initialize() {

  var mapOptions = {
    zoom: 4,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: australia
  };
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  directionsDisplay.setMap(map);
  directionsDisplay.setPanel(document.getElementById('directionsPanel'));

  google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
    computeTotalDistance(directionsDisplay.directions);
  });

  calcRoute();
}

function calcRoute() {

  var request = {
    origin: 'Istanbul, Turkey',
    destination: 'Ankara, Turkey',
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    }
  });
}

function computeTotalDistance(result) {
  var total = 0;
  var time= 0;
  var from=0;
  var to=0;
  var myroute = result.routes[0];
  for (var i = 0; i < myroute.legs.length; i++) {
    total += myroute.legs[i].distance.value;
    time +=myroute.legs[i].duration.text;
    from =myroute.legs[i].start_address;
    to =myroute.legs[i].end_address;


  }
  time = time.replace('hours','H');
  time = time.replace('mins','M');
  total = total / 1000.
  document.getElementById('from').innerHTML = from + '-'+to;
  document.getElementById('duration').innerHTML = time ;
  document.getElementById('total').innerHTML =Math.round( total)+"KM" ;
}

google.maps.event.addDomListener(window, 'load', initialize);

    </script>

HTML:

<div id="map-canvas" style="margin-left:15px;float:left;width:930px; height:280px"></div>
<div style="float:left;padding-left:20px; padding-top:15px; width:100%; height: 80px;">
<div style="float:left;width: 50%;"><h3 id="from"></h3></div>
<div style="float:right;margin-right: 20px;width: 158px;text-align: right;">
<h3 id="duration"></h3>
</div>
<div style="float:right;width: 158px;text-align: right;">

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

The issue with uploading files through ajax and jquery persists

I need to send the form using ajax. The form includes a text input field and a file upload field. However, in the ajax page (formaction.php), the file details are not being received. HTML <form method="post" id="newform" enctype="multipart/form-data"& ...

What is the best way to implement AJAX for linked drop down menus?

Is there a way to make my "Location" drop down list dependent on the selection in my "Client" drop down list? Here are my models: class Client(models.Model): name = models.CharField(max_length=50) class Location(models.Model): name = models.CharField ...

Angular (TypeScript) time format in the AM and PM style

Need help formatting time in 12-hour AM PM format for a subscription form. The Date and Time are crucial for scheduling purposes. How can I achieve the desired 12-hour AM PM time display? private weekday = ['Sunday', 'Monday', &apos ...

The challenge of storing GeoJSON data within SQLite database using Cordova

Below is a snippet of code that I am working with: var json_data = document.getElementById("json_data").value; console.log(json_data); tx.executeSql('INSERT INTO floodmaps VALUES (?,?,?)', [1, flodMapName, json_data], function(tx ...

Create a dropdown menu using a PDO query to populate the selectable options

I need to create a Select List that dynamically populates items/information from a Query. I understand the importance of updating the select list every time the database is updated, so JQuery is required for this task. Although I have limited experience wi ...

"Encountering an issue with the parameter 'undefined' in the .find()

Recently, I've been facing some challenges while using the .find() method within a vuex getter. I initialized a store with a list under state (pages) // state.js const state = { pages: [{id:1, content:"Page 1"}, {id:2, content:"Page 2"}] }; In my ...

"Enhance Your Website with Custom jQuery Preloaders

Currently, I am facing a challenge while developing a website. Specifically, I am struggling with resolving the issue of a blank page being displayed. The website that I am working on involves functionality where swiping right triggers data insertion into ...

What is the best way to display HTML and JavaScript content using Express?

Currently, I am working on a simple express app which comprises of two routes. One route is responsible for rendering html, while the other route is supposed to render a JavaScript file. To keep things organized, I plan to store the html files in a ./views ...

Is the MongoDB Query construction functioning properly in Node.js?

Struggling to construct a MongoDB query using OR and AND logic, where each OR word between keywords is placed in the Should block, and each AND word between words is placed in the must block. example - keyword1 OR keyword2 => both should be in the s ...

Receiving a mysterious error despite having everything clearly defined in the JavaScript code

Attempting to create a simple jQuery plugin: HTML: <textarea> <p>Hello World!</p> </textarea> jQuery: $.fn.wysiwyg = function (options) { var e = $(this).replaceWith("<iframe>"); console.log($(this)[0].conten ...

How can we organize and display the data from two linked arrays, one containing player names and the other containing

Looking for help on how to rank 3 players based on their scores using arrays. I've hit a roadblock and need guidance! Here's a brief example: Player 1 : Taylor Score Taylor : 15 Player 2 : Jordan Score Jordan : 20 Player 3 : Alex Score Alex : ...

What is the process for building a reusable component from a static component in Vue 3?

I am delving into Vue 3 and Headless UI, and I have successfully created a ListBox component in App.vue to display a list of People which is functioning as expected. Now, I am aiming to transform it into a reusable component capable of displaying lists of ...

Unable to access property 'name' of null object

I'm currently learning how to build a local library app using Express with The Odin Project's tutorial. Below are the relevant parts of my code: In routes/catalog.js, I have this: router.get("/books", book_controller.book_list); In models/book. ...

Displaying an error message: Uncaught ReferenceError - Undefined reference detected

Hi there, I am having some trouble with a JSON file and I would appreciate some help. The error message I am receiving is: Uncaught ReferenceError: marketlivedata is not defined <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquer ...

Using Vue.js to alter the CSS class property

I am exploring Vue.js and looking to modify a CSS class property. Here is the HTML code utilizing the specified class: <div class="customTimer"></div> Here is the corresponding CSS code: .customTimer { width: 100%; height: 1 ...

Add a new module to your project without having to rely on the initial

I'm looking to experiment with a module by making some adjustments for testing purposes. You can find the code here. Currently, all I need to do is type "npm install angular2-grid" in my terminal to add it to my project. Here's my concern: If ...

Utilizing scope parameters in conjunction with filters

I'm looking for a filtering solution to filter results displayed in a table using ngRepeat. The filter should be based on user input. Currently, I'm implementing it like this: //HTML <input type="search" ng-model="search"> <table> ...

Enriching an array with values using Mongoose

Is there a way to assign a User as an admin for the School? School Schema: const School = new Schema({ name: { type: String, required: true }, grades_primary: [{ type: Schema.Types.ObjectId, ref: 'Grade' }], grades_secondary: [{ type ...

"In Typescript, receiving the error message "Attempting to call an expression that is not callable" can be resolved

I am in the process of creating a function that matches React's useState signature: declare function useState<S>( initialState: S | (() => S), ): [S, React.Dispatch<React.SetStateAction<S>>]; Below is an excerpt from the functi ...

Incorporating a separate Controller and view into a single controller and view using Ajax with the CakePHP

I have three controllers in my app: Forms Attributes Users When posting data on /forms/designpage, I use the following code: $.ajax({ type: "POST", url: "./attributes/untitledfieldname", data: "sequence_no = " + counter + " & type = " + ...