Sunday 6 November 2016

Create a Map that gives you path in between source and destination



Introduction 

The following tutorial guides you through the process of showing path on Google Map using Html and JavaScript 



Use <div> tag with “id” attribute in <body> tag.

<div id="dvMap" >

Use following function in <script> tag.

<script type="text/javascript">

function myMap() {
  var mapCanvas = document.getElementById("dvMap");
  var mapOptions = {
    center: new google.maps.LatLng(51.508742,-0.120850),
    zoom: 5
  };
var map = new google.maps.Map(mapCanvas, mapOptions);
}
</script>

And call it in <body> Like:    <body onLoad="myMap()">. This give you google map after page load.


Use three <input> tag with “id” attribute to enter source and destination values and one to use as a button

 <input id="start" type="textbox/>
<input id="end" type="textbox" />
<input type="button" value="Direction" >

And add one more function in <script> to calculate route and to show you the path.
function calcRoute() {
            var latlng = new google.maps.LatLng(23.219104, 72.657137);
            var myOptions = {
                zoom: 15,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.SATELLITE
            };

            var directionsDisplay = new google.maps.DirectionsRenderer();
            directionsDisplay.setPanel(document.getElementById("directionsPanel"));
            var map = new google.maps.Map(document.getElementById("dvMap"), myOptions);
            directionsDisplay.setMap(map);
            var directionsService = new google.maps.DirectionsService();
            var start = document.getElementById("start").value;
            var end = document.getElementById("end").value;

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

Call this function in onClick attribute in <intput type=” button”>..
That’s it. Run the code and enjoy it..

To download source code click here






No comments:

Post a Comment