Draw Multiple Routes with Google Map API in Google Sheet

I will make it really quick. Yesterday, I created a script which use google JavaScript Api to extract nearby places and draw multiple routes to all these nearby places.

I used the following API end point to pull all the nearby places.

Step 1:

var response = UrlFetchApp.fetch(“https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670,151.1957&radius=5000&name=church&key=YOUR_API_KEY”);

var results = JSON.parse(response).results;

Logger.log(results.length);

var places =[];
places.pop();

for(var i=0;i< results.length; i++){

places.push([results[i].name,results[i].place_id]);

}

Step 2: Draw Map in div

var map = new google.maps.Map(document.getElementById(‘map’), {zoom: 20,center: {lat: 41.85,lng: -87.65}});

Step 3: Use directionsService and directionsDisplay  to calculate routes and display on Google maps

var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
dDisplays.push(directionsDisplay);

 

Step 4: Get route response with intermediate function and store all responses in array

function directResult(response, status) {
if (status === ‘OK’) {
responses.push(response);
} else {
window.alert(‘Directions request failed due to ‘ + status);
}
}

Step 5: Get the final route with the below function

function directResultFinal(response, status) {
if (status === ‘OK’) {
responses.push(response);
for (var d = 0; d < dDisplays.length; d++) {
dDisplays[d].setDirections(responses[d]);
}
} else {
window.alert(‘Directions request failed due to ‘ + status);
}
}

Step 6: Final function to draw the actual route

function calculateAndDisplayRoute(directionsServiceS, place1, place2, func) {
directionsServiceS.route({
origin: { placeId: place1 },
destination: { placeId: place2 },
travelMode: ‘DRIVING’
}, func);
}

Step 6: Final Call for Map Api initialization

<script async defer
src=”https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap”>
</script>

Here is the final result

 

 

Please contact me if you do have such requirement.

Leave a Reply

Your email address will not be published. Required fields are marked *