[google-maps] Google Maps API V3 : How show the direction from a point A to point B (Blue line)?

I have latitude and longitude for 2 points on database, I want my Google Map to display a route from point A to point B...

Just like we see here (Google Maps Directions)

Image from the link

How to draw that direction line on map ?

This question is related to google-maps google-maps-api-3

The answer is


  // First Initiate your map. Tie it to some ID in the HTML eg. 'MyMapID'
  var map = new google.maps.Map(
    document.getElementById('MyMapID'),
    {
      center: {
        lat: Some.latitude,
        lng: Some.longitude
      }
    }
  );
  // Create a new directionsService object.
  var directionsService = new google.maps.DirectionsService;
    directionsService.route({
      origin: origin.latitude +','+ origin.longitude,
      destination: destination.latitude +','+ destination.longitude,
      travelMode: 'DRIVING',
    }, function(response, status) {
      if (status === google.maps.DirectionsStatus.OK) {
        var directionsDisplay = new google.maps.DirectionsRenderer({
          suppressMarkers: true,
          map: map,
          directions: response,
          draggable: false,
          suppressPolylines: true, 
          // IF YOU SET `suppressPolylines` TO FALSE, THE LINE WILL BE
          // AUTOMATICALLY DRAWN FOR YOU.
        });

        // IF YOU WISH TO APPLY USER ACTIONS TO YOUR LINE YOU NEED TO CREATE A 
        // `polyLine` OBJECT BY LOOPING THROUGH THE RESPONSE ROUTES AND CREATING A 
        // LIST
        pathPoints = response.routes[0].overview_path.map(function (location) {
          return {lat: location.lat(), lng: location.lng()};
        });

        var assumedPath = new google.maps.Polyline({
         path: pathPoints, //APPLY LIST TO PATH
         geodesic: true,
         strokeColor: '#708090',
         strokeOpacity: 0.7,
         strokeWeight: 2.5
       });

       assumedPath.setMap(map); // Set the path object to the map

I'm using a popup to show the map in a new window. I'm using the following url

https://www.google.com/maps?z=15&daddr=LATITUDE,LONGITUDE

HTML snippet

<a target='_blank' href='https://www.google.com/maps?z=15&daddr=${location.latitude},${location.longitude}'>Calculate route</a>

In your case here is a implementation using directions service.

function displayRoute() {

    var start = new google.maps.LatLng(28.694004, 77.110291);
    var end = new google.maps.LatLng(28.72082, 77.107241);

    var directionsDisplay = new google.maps.DirectionsRenderer();// also, constructor can get "DirectionsRendererOptions" object
    directionsDisplay.setMap(map); // map should be already initialized.

    var request = {
        origin : start,
        destination : end,
        travelMode : google.maps.TravelMode.DRIVING
    };
    var directionsService = new google.maps.DirectionsService(); 
    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });
}

Use the directions API.

Make an ajax call i.e.

https://maps.googleapis.com/maps/api/directions/json?parameters

and then parse the responce


Using Javascript

I created a working demo that shows how to use the Google Maps API Directions Service in Javascript through a

  • DirectionsService object to send and receive direction requests
  • DirectionsRenderer object to render the returned route on the map

_x000D_
_x000D_
function initMap() {_x000D_
  var pointA = new google.maps.LatLng(51.7519, -1.2578),_x000D_
    pointB = new google.maps.LatLng(50.8429, -0.1313),_x000D_
    myOptions = {_x000D_
      zoom: 7,_x000D_
      center: pointA_x000D_
    },_x000D_
    map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),_x000D_
    // Instantiate a directions service._x000D_
    directionsService = new google.maps.DirectionsService,_x000D_
    directionsDisplay = new google.maps.DirectionsRenderer({_x000D_
      map: map_x000D_
    }),_x000D_
    markerA = new google.maps.Marker({_x000D_
      position: pointA,_x000D_
      title: "point A",_x000D_
      label: "A",_x000D_
      map: map_x000D_
    }),_x000D_
    markerB = new google.maps.Marker({_x000D_
      position: pointB,_x000D_
      title: "point B",_x000D_
      label: "B",_x000D_
      map: map_x000D_
    });_x000D_
_x000D_
  // get route from A to B_x000D_
  calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB);_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
function calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB) {_x000D_
  directionsService.route({_x000D_
    origin: pointA,_x000D_
    destination: pointB,_x000D_
    travelMode: google.maps.TravelMode.DRIVING_x000D_
  }, function(response, status) {_x000D_
    if (status == google.maps.DirectionsStatus.OK) {_x000D_
      directionsDisplay.setDirections(response);_x000D_
    } else {_x000D_
      window.alert('Directions request failed due to ' + status);_x000D_
    }_x000D_
  });_x000D_
}_x000D_
_x000D_
initMap();
_x000D_
    html,_x000D_
    body {_x000D_
      height: 100%;_x000D_
      margin: 0;_x000D_
      padding: 0;_x000D_
    }_x000D_
    #map-canvas {_x000D_
      height: 100%;_x000D_
      width: 100%;_x000D_
    }
_x000D_
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>_x000D_
_x000D_
<div id="map-canvas"></div>
_x000D_
_x000D_
_x000D_

Also on Jsfiddle: http://jsfiddle.net/user2314737/u9no8te4/

Using Google Maps Web Services

You can use the Web Services using an API_KEY issuing a request like this:

https://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&key=API_KEY

An API_KEY can be obtained in the Google Developer Console with a quota of 2,500 free requests/day.

A request can return JSON or XML results that can be used to draw a path on a map.

Official documentation for Web Services using the Google Maps Directions API are here