Monday, August 11, 2014

Going the distance with the Google Maps JavaScript API

I recently had a client that wanted to calculate the distance between 2 of their locations and keep it consistent. These calculations were going to be used in travel expense reports and they didn't want mileage to vary based on the way the employee decided to calculate their mileage. I recommended that we write a small app that allows the employees to select their start and end locations and we provide the mileage from a single source. I recommended and we went with the:

Google Maps JavaScript API Directions Service


I saw a lot of recommendations for Distance Matrix but after vetting it, I felt that it would be simpler to pull what I needed from the DirectionsResult object from the DirectionsService.

I setup a Start dropdown and an End dropdown. On a dropdown change event I would update the mileage. It also updates the route shown on the map.

clip_image002

Inside my dropdown change event handler, I call a method that takes the response from the DirectionsService() call and grabs the distance field text from the “leg”.

 function showDistance(directionResult) {  
   var myDistance = directionResult.routes[0].legs[0].distance;  
   var myDistanceText = myDistance.text;  
   document.getElementById('outputDiv').innerHTML = myDistanceText;  
 }  

It's fairly straightforward. If your trip were going to have multiple legs then you would need to loop through the legs[] array and grab each distance field and add them up. In that case or in the case that you need to get a distance or distances for reasons other than just printing it out, I would separate the getting of the distance from the showing of the distance.

You can steal all the code here on GitHub. This app has opened the scope creep floodgates. If I add to it, I may update this post if something worth sharing comes out of it.