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).