jaska120 jaska120 - 1 month ago 28
JSON Question

Google Maps Javascript API v3 routes iteration

I am struggling with the Google Maps javascript API. I am trying to parse the DirectionsResult by myself to display some data and later on pass them to database.

However the iteration through loop

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


Doesn't seem to catch up with all the data provided from routes[i]. I am trying to display route summaries but can't get any but route[1] summary out, if index is defined with i. If I am defining routeIndex with a number it works just fine.

Here is my code snippet:



<script src="http://maps.google.com/maps/api/js&libraries=geometry" type="text/javascript"></script>
<script type="text/javascript">

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

function initialize() {
// Default the map view 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
});
}

function route() {

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

// Make 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);
}
});
}

// Parse JSON

function parseJson(response) {
for (i = 0; i < response.routes.length; i++) {
var route = response.routes[i];
// Route atribuutit
// Push alternative routes to results div
document.getElementById("results").innerHTML = "";
document.getElementById("results").innerHTML += route.summary;
console.log(route.summary);
for (j = 0; j < route.legs.length; j++) {
var leg = route.legs[j];
// Leg atribuutit
for (k = 0; k < leg.steps.length; k++) {
var step = leg.steps[k];
// Steps atribuutit

}
}
}

} // End of JSON parse
</script>

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;
}

<body onload="initialize();">
<div id="controls"></div>
<input type="submit" onclick="route()"/>
<div id="map"></div>
<div id="results"></div>
</body>





I know DirectionsResult.routes.summary isn't documented anymore but DirectionsRenderer can provide the same functionality as "Suggested routes" so it should be possible to make.

UPDATED: I updated my code by taking all unnecessary things away. The code returns the array of 2 routes, which I can see from the console, but when I am trying to display the summary for each route, it always displays only route[1].summary, which is "Sastamalantie/Reitti 249 ja Porintie/Reitti 11" wheres route[0].summary is "Reitti 12" and is not displayed. The same thing outputs in both cases:
1.
document.getElementById("results").innerHTML += route.summary;

2.
console.log(route.summary);

Answer

You are overwriting the output for the first route in the "results" div:

// this line clears out the "results" div
document.getElementById("results").innerHTML = "";
// this outputs the data from this iteration of the loop
document.getElementById("results").innerHTML += route.summary; 

Remove the first line (or move it outside the loop).

code snippet:

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

function initialize() {
  // Default the map view 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
  }

  // Make 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);
    }
  });
}

// Parse JSON
function parseJson(response) {
    document.getElementById("results").innerHTML = "";
    for (i = 0; i < response.routes.length; i++) {
      var route = response.routes[i];
      // Route atribuutit
      // Push alternative routes to results div	
      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 atribuutit
        for (k = 0; k < leg.steps.length; k++) {
          var step = leg.steps[k];
          // Steps atribuutit
        }
      }
    }
  } // End of JSON parse
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="http://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>