Google Maps API Tutorials (JavaScript)

Google Maps API Directions Service Example

Last modified on April 17th, 2023
Raja Tamil
Google Maps API Javascript

Directions Service

The Directions Service is a client-side JavaScript libraray that lets us to get directions data between two locations based on travel mode such as driving, walking etc.

The Directions Service talks to Google Maps API behind the scene that takes direction requests such as origin, destination, travel mode and returns the efficient directions path data including multi-part directions.

1. Create A Map Object

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Google Maps API Directions Services</title>
</head>
<body>
    <div id="map" style="height:100vh"></div>
    <script src=" https://maps.googleapis.com/maps/api/js?key=[YOUR_API_KEY]"></script>
    <script src="app.js"></script>
</body>
</html>

app.js

const map = new google.maps.Map(document.getElementById("map"), {
    center: new google.maps.LatLng(45.4215296, -75.6971931),
    zoom: 15,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
});

FREE 1-HOUR COURSE:
Vue JS & Google Maps API

ACCESS FREE COURSE NOW

2. Make A Request To Directions Service

1. Create an instance of the DirectionsService Object.

const directionsService = new google.maps.DirectionsService();

2. Call the route() method on the directionsService object to initiate an HTTP request to the Directions Service.

directionsService.route();

This method takes a couple of arguments which are DirectionsRequest and response callback function.

3. Directions Service Request Object

The route() method takes directions request javascript object as an argument.

Directions Request object has three required query parameters which are

  • origin
  • destination
  • travelMode
 directionsService.route(
    {
            origin: "190 Main Street, Ottawa, Canada",
            destination: "290 First Avenue, Ottawa, Canada",
            travelMode: "DRIVING"
    }
)
namedescription
originThe value of the origin parameter can be one of 3 formats which are plain street address or geographic coordinates (latitude and longitude separated by a comma without any space in between) or the place_id.

This will be the starting point for calculating the directions between locations

For Example:
origin=123+Slater+Street+ON
origin=41.43206,-81.38992
origin=place_id:r345UTjjf(&*(*ljh*&
destinationThe value of the destination parameter can be one of the three formats similar to origin.This will be the ending point for calculating directions between locations.For Example:

destination=321+Slater+Street+ON
destination=41.43206,-81.38992
destination=place_id:r345UTjjf(&*(*ljh*&
travelMode – M uppercaseThis could be DRIVING, BICYCLING, TRANSIT & WALKING – and it must be all uppercase

4. Directions Service Response Object

The second argument of route() method would be a response callback function. 

The DirectionsService is asynchronous so the callback function will be called upon completion of the Service request.

 directionsService.route(
    {
            origin: "190 Main Street, Ottawa, Canada",
            destination: "290 First Avenue, Ottawa, Canada",
            travelMode: "DRIVING"
    },
    (response, status) => {
     console.log(response);
     console.log(status);
    }
)

Then it will return a directionsResult and a DirectionsStatus that we can access from the parameters in the callback function. 

As you can see, the response object has a lot of information about the directions…the legs property will have travel distance, duration and steps information which basically tells you when to maneuver such as turn left, turn right, keep right and so on.

The overview path will show you the location coordinates which can be used to draw the polyline between the origin and destination locations on the map.

FREE 1-HOUR COURSE:
Vue JS & Google Maps API

ACCESS FREE COURSE NOW

5. Show Directions On The Maps

const map = new google.maps.Map(document.getElementById("map"), {
    center: new google.maps.LatLng(45.4215296, -75.6971931),
    zoom: 15,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
});

const directionsService = new google.maps.DirectionsService();

directionsService.route(
    {
            origin: "272 Bronson Ave, Ottawa, Canada",
            destination: "1385 Woodroffe Ave, Nepean, Canada",
            travelMode: "DRIVING",
    },
    (response, status) => {
        if (status === "OK") {

            new google.maps.DirectionsRenderer({
                suppressMarkers: true,
                directions: response,
                map: map,
              });
        }
    }
)

6. Enable Directions Service

Try it out

See the Pen Google Maps API Directions Services Example by SoftAuthor (@softauthor) on CodePen.

 

FREE 1-HOUR COURSE:
Vue JS & Google Maps API

ACCESS FREE COURSE NOW