Exploring routes using Google Maps JavaScript API v3

I've been facing challenges with the Google Maps JavaScript API as I attempt to manually parse the DirectionsResult data for display and later storage in a database.

However, when iterating through the loop:

for (i = 0; i < response.routes.length; i++) {
    var route = response.routes[i];
}

I'm experiencing issues capturing all the provided data from routes[i]. Despite my efforts to display route summaries, I can only retrieve route[1] summary if the index is defined with i. If I define routeIndex with a number, it works fine.

Below is a snippet of my code:

Although DirectionsResult.routes.summary is no longer documented, DirectionsRenderer should offer similar functionality as "Suggested routes," making it theoretically possible to achieve.

UPDATE1: I have streamlined my code by removing unnecessary elements. The code now returns an array of 2 routes, visible in the console. However, when attempting to display the summary for each route, only route[1].summary is shown, while route[0].summary, which should be "Reitti 12," remains hidden. The issue persists across both cases:

document.getElementById("results").innerHTML += route.summary;
console.log(route.summary);

UPDATE2: While the provided solution resolved one issue, I've encountered another problem related to the same iteration loop.

 <014; /* line edited */ 
  directionService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) { 
        directionsRenderer.setDirections(response);
        parseJson(response);
        console.log(response);
        google.maps.event.addListener(directionsRenderer, 'routeindex_changed', function() { 
        console.log(this.getRouteIndex());
    });

    } else {
      alert("Directions query failed: " + status);
    }
  });
}

    // Parse JSON

    function parseJson(response) {
    var resultsHTML = "";
    for (i = 0; i < response.routes.length; i++) {
        var route = response.routes[i];           
            route.overview_path;
            var pathPolyline = route.overview_polyline;
            var routeName = route.summary;  
                resultsHTML += "<p onclick='directionsRenderer.setRouteIndex(i)'>" + (i+1) + ": " + routeName + " ";    
                console.log(routeName);                  
        for (j = 0; j < route.legs.length; j++) {
            var leg = route.legs[j];
                var routeDistance = leg.distance.text;
                var routeDuration = leg.duration.text;
                    resultsHTML += routeDistance + " " + routeDuration + "</p>";
                    for (k = 0; k < leg.steps.length; k++) {
                    var step = leg.steps[k];     
        }
    }        
}
    document.getElementById("results").innerHTML = resultsHTML;

Currently, I am successfully displaying route.summary as intended. However, within the line

resultsHTML += "<p onclick='directionsRenderer.setRouteIndex(i)'>" + (i+1) + ": " + routeName + " ";
, upon clicking each p element, setRouteIndex(i) consistently outputs a value of 3 to the console and draws routes[3] on the map instead of assigning a corresponding routeIndex to each p tag. Interestingly, i+1 correctly displays the respective routeIndex numbers for each route (e.g., 1: route, 2: route).

Answer №1

You have the ability to replace the output for the initial route within the "results" division:

// Eliminate the content in the "results" section
document.getElementById("results").innerHTML = "";
// Display the data from this loop iteration
document.getElementById("results").innerHTML += route.summary; 

Exclude the first line (or shift it outside of the loop).

snippet of code:

var map = null;
var boxpolys = null;
var directions = null;
var routeBoxer = null;
var distance = null; // km

function initialize() {
  // Set the default view of the map to Finland.
  var mapOptions = {
    center: new google.maps.LatLng(65.25, 25.35),
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    mapTypeControl: false,
    streetViewControl: false,
    zoomControl: false,
    zoom: 5
  };

  map = new google.maps.Map(document.getElementById("map"), mapOptions);

  directionService = new google.maps.DirectionsService();
  directionsRenderer = new google.maps.DirectionsRenderer({
    map: map
  });
}
google.maps.event.addDomListener(window, 'load', initialize);

function route() {
  var request = {
    origin: "Sastamala+Finland",
    destination: "Tampere+Finland",
    travelMode: google.maps.DirectionsTravelMode.DRIVING,
    provideRouteAlternatives: true
  }

  // Send out the directions request
  directionService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsRenderer.setDirections(response);
      parseJson(response);
      console.log(response);

    } else {
      alert("Directions query failed: " + status);
    }
  });
}

// Analyze JSON
function parseJson(response) {
    document.getElementById("results").innerHTML = "";
    for (i = 0; i < response.routes.length; i++) {
      var route = response.routes[i];
      // Route attributes
      // Append alternative routes to results division
      document.getElementById("results").innerHTML += i + ":" + route.summary + "<br>";
      console.log(route.summary);
      for (j = 0; j < route.legs.length; j++) {
        var leg = route.legs[j];
        // Leg attributes
        for (k = 0; k < leg.steps.length; k++) {
          var step = leg.steps[k];
          // Steps attributes
        }
      }
    }
  } // End of JSON analysis
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map {
  height: 90%;
  width: 70%;
  float: left;
}
#results {
  height: 90%;
  width: 30%;
  float: right;
}
#controls {
  position: absolute;
  top: 50px;
  font-family: sans-serif;
  font-size: 11pt;
}
<script src="https://maps.google.com/maps/api/js?libraries=geometry" type="text/javascript"></script>
<div id="controls"></div>
<input type="submit" onclick="route()" />
<div id="map"></div>
<div id="results"></div>

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 causes the discrepancy between the values returned by the jQuery getter css() method and JavaScript when accessing the style variable

After recently beginning to use jquery, I decided to switch due to initialization issues when loading external styles with javascript. Here is a rule defined in an external style sheet: #siteLogoDiv { position:absolute; left:0px; top:0px; width:100%; heig ...

Avoiding the Popover Component from Covering the Screen When the Menu Component Opens in React Material UI

I have implemented a Menu component to display a menu upon hovering over an element. However, I have encountered an issue where the menu includes a Popover component that opens up and covers the entire screen as an overlay, preventing interaction with th ...

``Redirecting a Heroku/Angular application to use the HTTPS version forcefully

I'm encountering an issue with my Angular 5 app hosted on Heroku where users can only access the HTTP version. How do I enforce redirection to the HTTPS version if users attempt to access it via HTTP? My Attempt: app.use(function (req, res, next) { ...

How to initiate focus on Angular 2 MdInputContainer after the view has been

I am encountering an issue with setting focus on the first md-input-container element within a component when the view loads. Despite implementing a @ViewChild property and calling focus on it in the ngAfterViewInit method, the focus does not seem to be wo ...

Vue.js is throwing an error message saying, 'Unrecognized custom element: <ShowList>' while rendering in the browser

After setting up a basic boilerplate project using vue cli create, I made some small modifications that initially seemed to work fine. However, at one point, both of my components suddenly stopped working in the browser without any warnings from vue-cli-se ...

How to use JavaScript to toggle datalabels on Highcharts?

Is it possible to make Highcharts show datalabels for a specific category when clicking on the legend item? I've attempted to enable datalabels using the code below, but it hasn't worked: chart.series[0].data.dataLabels.enabled = true; You can ...

"UserFilter does not support this expression" reported by the GoodData API

Could someone help me understand and resolve this error message I encountered while attempting to create a user filter using the GoodData API? { "error" : { "parameters" : [ "[/gdc/md/PROJECT_ID/obj/OBJECT_ID]=[/gdc/md/PROJECT_ID/obj/O ...

Extract URL as a parameter for $.getJSON using JavaScript

When attempting to include a URL as a parameter along with several other parameters in my frontend to make a JSON request to my Django backend, I am encountering the familiar 404 error - not found. Django urls.py path: path("updateAssignment/<iD&g ...

Is there a way to view the current subnets within an Amazon cloudformation template?

I am customizing a Multi-AZ LAMP stack template by changing the existing VPC ID, adding two subnets, and naming the RDB database, user, and password. The code validates without errors when I click the check button, but fails with a code error when I try to ...

Initializing an HTML5 video player directly from an Array

I am trying to populate a video player on my webpage with an array of videos. Here is the code I have so far: var current = 0; var videos = ["01", "02", "03", "04"]; function shuffle(array) { var currentIndex = array.length, temporaryValue, randomInde ...

Access the JSON file, make changes to a specific value, and then save the

In my JSON data file, I have the following information: [ { "key" : "test1", "desc": "desc1" }, { "key" : "test2", "desc": "desc2" }, ] I have written a script to retrieve this data from the file using AJAX and display it in an HT ...

How to Access a PHP Variable within a JavaScript Function Argument

.php <?php $timeArray = [355,400,609,1000]; $differentTimeArray = [1,45,622, 923]; ?> <script type="text/javascript"> var i=0; var eventArray = []; function generateArray(arrayName){ eventVideoArray = <?php echo json_encode(arrayName); ...

Experiencing an inexplicable blurring effect on the modal window

Introduction - I've implemented a feature where multiple modal windows can be opened on top of each other and closed sequentially. Recently, I added a blur effect that makes the background go blurry when a modal window is open. Subsequently opening an ...

Leveraging RSS XML data in Angular by parsing it with x2js and displaying it using ng-repeat

Hey there, I could really use some assistance. I've been trying to solve this puzzle for the past few days without much luck. My goal is to extract only the item objects from an XML RSS file using Angular and x2js. The structure of the XML file looks ...

My database images are not appearing, instead, blank bootstrap cards are displayed on the

I have set up an online store website with nodejs, express, and mongodb where I have stored image URLs, titles, descriptions in my database. However, the issue is that there are 2 black cards appearing before each image on the webpage. Below is the code sn ...

Tips on sending data with a unique identifier to the backend through a route parameter

Can anyone help me figure out how to send a message to a specific backend route parameter while passing the current ID? I'm not sure how to inform the system about this ID. Here's the Vuex action: postMessage({commit}, payload, id) { axios.pos ...

Unable to connect to 127.0.0.1 or any other IP addresses, but localhost is accessible

I'm currently utilizing Nodejs and Expressjs. When attempting to access my application through , everything loads correctly. However, when trying any other loopback IP addresses (such as 127.0.0.1, my PC name, or my PC IP), I encounter the following ...

Encountering an Unexpected : Token When Parsing JSON Arrays in AngularJS

I've been searching on various forums for an answer to my AngularJS issue without any luck. I have a simple controller that calls an http service and reads the response data, which is in JSON format with an objects array. However, I'm facing diff ...

data.data for accessing the information in my JSON file

I am having this issue with my factory and controller in AngularJS: 'use strict'; angular.module('testCon').factory('UserService', function ($http) { return { getAll: function () { return $http.get(&apos ...

When attempting to reference from a variable, you may encounter an error stating that setAttribute

In my VueJS project, I am facing an issue with dynamically adding the width attribute to an inline SVG code stored in a variable called icon. Despite having the correct SVG icon code in the variable, the setAttribute method is not working as expected and t ...