How to Get Directions with the Google Maps API

A minimal example of getting directions to a location, using the Google Maps API.

This blog post offers a simple solution to providing a ‘get directions’ feature on your website.

I recently had the task of getting the directions from the current user’s location, to the location of a store, as part of an eCommerce project. For this particular application, I was working on the SAP Hybris platform but the process should be the same for any of the main platforms such as Shopify Plus, Magento, BigCommerce etc.

I found the documentation on Google Maps to be a lot more convoluted than necessary. The directions in the documentation explain that you need to use the `DirectionsService` that google maps provide as part of the API, as found in this example.

This is not the case, although you will still need the location in which you would like to direct the user (i.e. the latitude/longitude, or the name of the place).

Assuming you wish to set the start location as the user’s current location, you can achieve this by simply using this endpoint,

<a href="https://www.google.com/maps/dir//{latitude},{longitude}"> Get directions </a>.

There is also an opportunity here to set various rules on how the directions should be set, such as the mode of transport, the travel time, waypoints, and much more. All of these options can be found here.  But, to save you the click, here they are;

{  origin: LatLng | String | google.maps.Place, // where you will begin  destination: LatLng | String | google.maps.Place, // where you will end up  travelMode: TravelMode, //driving, train, boat, transit etc  transitOptions: TransitOptions, // only applies if travelMode is provided  drivingOptions: DrivingOptions, //you can set the departure, and pessimistic or optimistic driving coniditons  unitSystem: UnitSystem, // metric or (the archaic) imperial  waypoints[]: DirectionsWaypoint, // places to stop off on the way  optimizeWaypoints: Boolean, //when true, it chooses the shortest route  provideRouteAlternatives: Boolean, // when true, gives more than one way to get to the destination  avoidFerries: Boolean,   avoidHighways: Boolean,  avoidTolls: Boolean,  region: String}

TLDR;

<a href="https://www.google.com/maps/dir//{latitude},{longitude}"> Get directions </a>

Note: the two  `//` after `dir` are required, as otherwise it will assume you are setting the starting location.

I hope this blog post helped you find what you needed, if you have is any feedback / additional information that you would like covered in this post, please leave a comment, or contact me at [email protected].