How to Draw Path on Map using Google Maps Direction API

In this tutorial, we are going to see how to draw the path on map between two locations using Google Map Javascript API. This API provides Direction service to draw route between locations. This direction service requires the start and the endpoint of the route to be drawn. It responds the direction resource which will be rendered on the map layer.

In this example, I have a group of checkboxes showing locations options. On submitting the selected checkbox locations, I formed an array of waypoints to request route path. I am sending the waypoints array to the Google Maps Direction service with the start, endpoint of the route. It responds the direction resource with the status. The response status will be checked and the directions will be set on the map based on the status.


HTML Code to Show Waypoints

The following HTML code contains checkbox input options to show the waypoints. It contains a Draw Path button to trigger the Direction service request with the selected waypoints.

<div class="lbl-way-points">Way Points</div>
foreach ($countryResult as $k => $v) {
  <div class="way-points-option"><input type="checkbox" name="way_points[]" class="way_points" value="<?php echo $countryResult[$k]["country"]; ?>"> <?php echo $countryResult[$k]["country"]; ?></div>
<input type="button" id="go" value="Draw Path" class="btn-submit" />

<div id="map-layer"></div>

Code for initMap and Direction Service Request

The code for initializing map is same as we have seen in the previous tutorials, like getting current location, adding map markers and more. In this code, I formed the waypoints array by using the selected checkbox values. Then, I set the options required for the direction service request, like start and end location and the waypoints. The direction service will respond to the request with the direction resource and the status.

This response status is checked by using a callback function. The direction resource is rendered path on the target map layer based on the response status. If the status is not OK, then I have shown a Javascript alert box to acknowledge the user about the problem occurred while requesting the direction.

  	var map;
	var waypoints
  	function initMap() {
    	  	var mapLayer = document.getElementById("map-layer"); 
        	var centerCoordinates = new google.maps.LatLng(37.6, -95.665);
    		var defaultOptions = { center: centerCoordinates, zoom: 4 }
    		map = new google.maps.Map(mapLayer, defaultOptions);

        var directionsService = new google.maps.DirectionsService;
        var directionsDisplay = new google.maps.DirectionsRenderer;

        $("#go").on("click",function() {
        	    waypoints = Array();
            	$('.way_points:checked').each(function() {
                    location: $(this).val(),
                    stopover: true
            var locationCount = waypoints.length;
            if(locationCount > 0) {
                var start = waypoints[0].location;
                var end = waypoints[locationCount-1].location;
                drawPath(directionsService, directionsDisplay,start,end);
    	function drawPath(directionsService, directionsDisplay,start,end) {
          origin: start,
          destination: end,
          waypoints: waypoints,
          optimizeWaypoints: true,
          travelMode: 'DRIVING'
        }, function(response, status) {
            if (status === 'OK') {
            } else {
            window.alert('Problem in showing direction due to ' + status);

Google Maps Direction Service Request – Output

The following screenshot shows the path among the selected waypoints as populated with the checkboxes.



This PHP code tutorial was published on October 10, 2017.

↑ Back to Top