EDIT: this problem is solved thanks to the help of geocodezip who pointed me the right way in the comments...
problem: i want transit-directions from google as plain text and i need the transit_details. i tried adding all variations of stuff like (which does not work):
steps[i].transit.arrival_stop.name
solution: most transit routes have the first and last steps walking. in this case, .transit
does not exist and produces the error.
i fixed the code below accordingly (which now works).
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title></title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?"></script>
</head>
<body style="font-family: Arial; font-size: 12px; color:#FFFFFF;" bgcolor="#202020">
<div id="panel" style="width: 300px; float: left;"></div>
<div id="map" style="width: 300px; height: 300px;"></div>
<script type="text/javascript">
calcRoute();
function calcRoute() {
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
directionsDisplay.setMap(map);
var request = {
origin: 'Potsdamer Platz, 10785 Berlin',
destination: 'Falckensteinstraße, Berlin',
travelMode: google.maps.DirectionsTravelMode.TRANSIT,
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
writeDirectionsSteps(directionsDisplay.directions.routes[0].legs[0].steps);
}
else {
console.error('DirectionsStatus is ' + status);
}
});
}
function writeDirectionsSteps(steps) {
var directions = document.getElementById('panel');
directions.innerHTML = '';
for (var i = 0; i < steps.length; i++) {
directions.innerHTML += '<br/><br/>' + steps[i].instructions + '<br/>' + steps[i].distance.text;
if (typeof steps[i].transit !== "undefined") {
directions.innerHTML += '<br/>' + steps[i].transit.arrival_stop.name;
}
}
}
</script>
</body>
</html>
(code based on: Google Maps Api v3: How to change the Default waypoint markers in the Directions (set)Panel?)
any help is appreciated a lot!
You need to code defensively. The
.transit
property will not be there in all the steps, only those that involve the actual transit itself (i.e. not on the walk to and from the station).proof of concept fiddle
code snippet: