FOLLOW

Saturday, April 14, 2018

How to draw a path between two marker points?

In this tutorial, we’ll be learning about how to draws a route between two points. We’ll be using Google Maps Directions API in our application.

Create a new Google Map API Key from the API console using the steps demonstrated in this tutorial.

CSS

You can define map height and width under #map section 
Add this code in your head section of the html file

    <style>
      #map {
        height: 100%;
      }
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>

Script


<script>

      function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 10, 
          center: {lat: 17.3483, lng: 78.3915}, //Default location to show on the map
          mapTypeId: 'terrain'
        });

       //Two coordinates to draw a path
        var flightPlanCoordinates = [
          {lat: 17.4483, lng:  78.3915},
          {lat: 17.291, lng: 78.821}
        ];

        //Draw a simple Polyline
        var flightPath = new google.maps.Polyline({
          path: flightPlanCoordinates,
          geodesic: true,
          strokeColor: '#FF0000',
          strokeOpacity: 1.0,
          strokeWeight: 2
        });

        flightPath.setMap(map);
      }
    </script>


Use your API key here, that you created in the google console.
If you are not created follow this link to create, it's a simple process.

     <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>

Body


<body>
      <div id='map'>
</body>

 Result