I am trying to return arrival_stop.name from Google directions API in an Apps Script function. Here is my code:
const GOOGLEMAPS_STEPS_TRANSIT_DETAILS = (origin, destination, mode = 'transit') => {
const { routes = [] } = Maps.newDirectionFinder()
.setOrigin(origin)
.setDestination(destination)
.setMode(mode)
.getDirections();
if (!routes.length) {
throw new Error('No route found!');
}
var stepTransitDetails = routes
.map(({ legs }) => {
return legs.map(({ steps }) => {
return steps.map((step) => {
return step.transit_details.arrival_stop.name;
});
});
})
.join(' , ');
return stepTransitDetails;
};
Error given:
TypeError: Cannot read property 'arrival_stop' of undefined (line 228).
Desired output is a list of stops within the transit step - for example if the step is taking the Piccadilly Line train from Leicester Square to Kings Cross the output would be the list of stations it will stop at.
I have this same code working when returning step.html_instructions rather than step.transit_details.arrival_stop.name and if I remove the .arrival_stop.name it returns [object Object],,object Object], meaning it's recognising the steps which involve transit, but adding the .arrival_stop gives an error.
Working based on Google API Docs
When I saw the data of routes, it seems that there are objects without including the property of transit_details in step. I thought that this might be the reason for your issue. If you want to retrieve step.transit_details.arrival_stop.name, how about the following modification?
var stepTransitDetails = routes
.map(({ legs }) => {
return legs.map(({ steps }) => {
return steps.map((step) => {
return step.transit_details.arrival_stop.name;
});
});
})
.join(' , ');
var stepTransitDetails = routes
.map(({ legs }) => {
return legs.map(({ steps }) => {
return steps.filter(({ transit_details }) => transit_details).map(({ transit_details }) => {
return transit_details.arrival_stop.name;
});
});
})
.join(' , ');
filter is used for retrieving the object including transit_details.