Find distance between two locations Using Google API

Can we find out distance between two locations on our web application? yes ,we can. Here a couple of lines of code .which written in java script and Google API Easy to use . Copy and paste these lines of code and save like googleapi.htm . belief me it is pretty cool. Click here to Download Demo .



Code:
  1. <!--Author :Mohammad Usman
  2.      date  :12/05/2010 -->
  3. <title>Distance finder</title>
  4. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
  5.         var xmlhttp;
  6.         function GetXmlHttpObject()
  7.         {
  8.             if (window.XMLHttpRequest)
  9.             {
  10.                 return new XMLHttpRequest();
  11.             }
  12.             else if(window.ActiveXObject)
  13.             {
  14.                 try
  15.                 {
  16.                     return new ActiveXObject("Msxml2.XMLHTTP");
  17.                 }
  18.                 catch(e)
  19.                 {
  20.                     return new ActiveXObject("Microsoft.XMLHTTP");
  21.                 }
  22.             }
  23.             else
  24.             {
  25.                 return null;
  26.             }
  27.         }
  28. <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
  29. <script type="text/javascript">
  30.     var location1;
  31.     var location2;
  32.     var address1;
  33.     var address2;
  34.     var latlng;
  35.     var geocoder;
  36.     var map;  
  37.     var line;
  38.     var infowindow1;
  39.     var infowindow2;
  40.     var distance;
  41.     function start(a1, a2)
  42.     {
  43.         document.getElementById("address1").value = a1;
  44.         document.getElementById("address2").value = a2;
  45.        
  46.         initialize();
  47.     }
  48.    
  49.     // finds the coordinates for the two locations and calls the showMap() function
  50.     function initialize()
  51.     {
  52.         geocoder = new google.maps.Geocoder(); // creating a new geocode object
  53.        
  54.         // getting the two address values
  55.         address1 = document.getElementById("address1").value;
  56.         address2 = document.getElementById("address2").value;
  57.        
  58.         // finding out the coordinates
  59.         if (geocoder)
  60.         {
  61.             geocoder.geocode( { 'address': address1}, function(results, status)
  62.             {
  63.                 if (status == google.maps.GeocoderStatus.OK)
  64.                 {
  65.                     //location of first address (latitude + longitude)
  66.                     location1 = results[0].geometry.location;
  67.                 } else
  68.                 {
  69.                     alert("Geocode was not successful for the following reason: " + status);
  70.                 }
  71.             });
  72.             geocoder.geocode( { 'address': address2}, function(results, status)
  73.             {
  74.                 if (status == google.maps.GeocoderStatus.OK)
  75.                 {
  76.                     //location of second address (latitude + longitude)
  77.                     location2 = results[0].geometry.location;
  78.                     // calling the showMap() function to create and show the map
  79.                     showMap();
  80.                 } else
  81.                 {
  82.                     alert("Geocode was not successful for the following reason: " + status);
  83.                 }
  84.             });
  85.         }
  86.     }
  87.    
  88.     // creates and shows the map
  89.     function showMap()
  90.     {
  91.         // center of the map (compute the mean value between the two locations)
  92.         latlng = new google.maps.LatLng((location1.lat()+location2.lat())/2,(location1.lng()+location2.lng())/2);
  93.        
  94.         // get the map type value from the hidden field
  95.         var maptype = document.getElementById("maptype").value;
  96.         var typeId;
  97.         if (maptype == "roadmap")
  98.             typeId = google.maps.MapTypeId.ROADMAP;
  99.         else if (maptype == "hybrid")
  100.             typeId = google.maps.MapTypeId.HYBRID;
  101.         else if (maptype == "satellite")
  102.             typeId = google.maps.MapTypeId.SATELLITE;
  103.         else if (maptype == "terrain")
  104.             typeId = google.maps.MapTypeId.TERRAIN;
  105.        
  106.         // set map options
  107.             // set zoom level
  108.             // set center
  109.             // map type
  110.         var mapOptions =
  111.         {
  112.             zoom: 1,
  113.             center: latlng,
  114.             mapTypeId: typeId
  115.         };
  116.        
  117.         // create a new map object
  118.             // set the div id where it will be shown
  119.             // set the map options
  120.         map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
  121.        
  122.         // event listener to update the map type
  123.         google.maps.event.addListener(map, 'maptypeid_changed', function() {
  124.             maptype = map.getMapTypeId();
  125.             document.getElementById('maptype').value = maptype;
  126.         });
  127.        
  128.         // custom marker
  129.         var rabbit = new google.maps.MarkerImage('distance-finder-custom-marker-image.png');
  130.                
  131.         // create the markers for the two locations    
  132.         var marker1 = new google.maps.Marker({
  133.             map: map,
  134.             position: location1,
  135.             title: "First location",
  136.             icon: rabbit,
  137.             draggable: true
  138.         });
  139.        
  140.         var marker2 = new google.maps.Marker({
  141.             map: map,
  142.             position: location2,
  143.             title: "Second location",
  144.             icon: rabbit,
  145.             draggable: true
  146.         });
  147.        
  148.         // create the text to be shown in the infowindows
  149.         var text1 = '<div id="content">'+
  150.                 '<h1 id="firstHeading">First location</h1>'+
  151.                 '<div id="bodyContent">'+
  152.                 '<p>Coordinates: '+location1+'</p>'+
  153.                 '<p>Address: '+address1+'</p>'+
  154.                 '</div>'+
  155.                 '</div>';
  156.                
  157.         var text2 = '<div id="content">'+
  158.             '<h1 id="firstHeading">Second location</h1>'+
  159.             '<div id="bodyContent">'+
  160.             '<p>Coordinates: '+location2+'</p>'+
  161.             '<p>Address: '+address2+'</p>'+
  162.             '</div>'+
  163.             '</div>';
  164.        
  165.         // create info boxes for the two markers
  166.         infowindow1 = new google.maps.InfoWindow({
  167.             content: text1
  168.         });
  169.         infowindow2 = new google.maps.InfoWindow({
  170.             content: text2
  171.         });
  172.         // add action events so the info windows will be shown when the marker is clicked
  173.         google.maps.event.addListener(marker1, 'click', function() {
  174.             infowindow1.open(map,marker1);
  175.         });
  176.         google.maps.event.addListener(marker2, 'click', function() {
  177.             infowindow2.open(map,marker2);
  178.         });
  179.        
  180.         // add action events for dragging the markers
  181.         google.maps.event.addListener(marker1, 'dragend', function() {
  182.             location1 = marker1.getPosition();
  183.             drawRoutes(location1, location2);
  184.         });
  185.        
  186.         google.maps.event.addListener(marker2, 'dragend', function() {
  187.             location2 = marker2.getPosition();
  188.             drawRoutes(location1, location2);
  189.         });
  190.        
  191.         // initialize directions service
  192.         directionsService = new google.maps.DirectionsService();
  193.         directionsDisplay = new google.maps.DirectionsRenderer(
  194.         {
  195.             suppressMarkers: true,
  196.             suppressInfoWindows: true
  197.         });
  198.        
  199.         directionsDisplay.setMap(map);
  200.        
  201.         drawRoutes(location1, location2);
  202.     }
  203.    
  204.     function drawRoutes(location1, location2)
  205.     {
  206.         // show new addresses
  207.        
  208.         geocoder = new google.maps.Geocoder(); // creating a new geocode object
  209.        
  210.         if (geocoder)
  211.         {
  212.             geocoder.geocode({'latLng': location1}, function(results, status)
  213.             {
  214.                 if (status == google.maps.GeocoderStatus.OK)
  215.                 {
  216.                     if (results[0])
  217.                     {
  218.                         address1 = results[0].formatted_address;
  219.                         document.getElementById("address1").value = address1;
  220.                     }
  221.                 }
  222.                 else
  223.                 {
  224.                     alert("Geocoder failed due to: " + status);
  225.                 }
  226.             });
  227.         }
  228.         if (geocoder)
  229.         {
  230.             geocoder.geocode({'latLng': location2}, function(results, status)
  231.             {
  232.                 if (status == google.maps.GeocoderStatus.OK)
  233.                 {
  234.                     if (results[0])
  235.                     {
  236.                         address2 = results[0].formatted_address;
  237.                         document.getElementById("address2").value = address2;
  238.                         continueShowRoute(location1, location2);
  239.                     }
  240.                 }
  241.                 else
  242.                 {
  243.                     alert("Geocoder failed due to: " + status);
  244.                 }
  245.             });
  246.         }
  247.     }
  248.    
  249.     function continueShowRoute(location1, location2)
  250.     {
  251.         // hide last line
  252.         if (line)
  253.         {
  254.             line.setMap(null);
  255.         }
  256.    
  257.         // show a line between the two points
  258.         line = new google.maps.Polyline({
  259.             map: map,
  260.             path: [location1, location2],
  261.             strokeWeight: 7,
  262.             strokeOpacity: 0.8,
  263.             strokeColor: "#FFAA00"
  264.         });
  265.        
  266.         // compute distance between the two points
  267.         var R = 6371;
  268.         var dLat = toRad(location2.lat()-location1.lat());
  269.         var dLon = toRad(location2.lng()-location1.lng());
  270.        
  271.         var dLat1 = toRad(location1.lat());
  272.         var dLat2 = toRad(location2.lat());
  273.        
  274.         var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
  275.                 Math.cos(dLat1) * Math.cos(dLat1) *
  276.                 Math.sin(dLon/2) * Math.sin(dLon/2);
  277.         var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  278.         var d = R * c;
  279.        
  280.         document.getElementById("distance_direct").innerHTML = "<br/><br/>The distance between the two points (in a straight line) is: "+d;
  281.        
  282.         var travelmode = document.getElementById("travelMode").value;
  283.         // get the selected travel mode
  284.         if (travelmode == "driving")
  285.             travel = google.maps.DirectionsTravelMode.DRIVING;
  286.         else if (travelmode == "walking")
  287.             travel = google.maps.DirectionsTravelMode.WALKING;
  288.         else if (travelmode == "bicycling")
  289.             travel = google.maps.DirectionsTravelMode.BICYCLING;
  290.        
  291.         // find and show route between the points
  292.         var request = {
  293.             origin:location1,
  294.             destination:location2,
  295.             travelMode: travel
  296.         };
  297.         directionsService.route(request, function(response, status)
  298.         {
  299.             if (status == google.maps.DirectionsStatus.OK)
  300.             {
  301.                 directionsDisplay.setDirections(response);
  302.                 distance = "<br/>The distance between the two points on the chosen route is: "+response.routes[0].legs[0].distance.text;
  303.                 distance += "<br/>The aproximative "+travelmode+" time is: "+response.routes[0].legs[0].duration.text;
  304.                 document.getElementById("distance_road").innerHTML = distance;
  305.             }
  306.             else
  307.             {
  308.                 alert('error: ' + status);
  309.             }
  310.         });
  311.        
  312.         // update text in infowindows
  313.         var text1 = '<div id="content">'+
  314.                 '<h1 id="firstHeading">First location</h1>'+
  315.                 '<div id="bodyContent">'+
  316.                 '<p>Coordinates: '+location1+'</p>'+
  317.                 '<p>Address: '+address1+'</p>'+
  318.                 '</div>'+
  319.                 '</div>';
  320.                
  321.         var text2 = '<div id="content">'+
  322.             '<h1 id="firstHeading">Second location</h1>'+
  323.             '<div id="bodyContent">'+
  324.             '<p>Coordinates: '+location2+'</p>'+
  325.             '<p>Address: '+address2+'</p>'+
  326.             '</div>'+
  327.             '</div>';
  328.            
  329.         infowindow1.setContent(text1);
  330.         infowindow2.setContent(text2);
  331.        
  332.         var twitter = "<div class='comments' style='display: inline-block;'></div>";
  333.        
  334.         var facebook = "<div id='facebook' style='display: inline-block;'></div>";
  335.        
  336.         document.getElementById("share").innerHTML = twitter+"&nbsp;"+facebook;
  337.        
  338.         share_twitter(address1, address2);
  339.     }
  340.    
  341.     function toRad(deg)
  342.     {
  343.         return deg * Math.PI/180;
  344.     }
  345. </head>
  346. <body bgcolor="#eeeeee">
  347.     <div id="fb-root"></div>   
  348.     <div id="form" style="width:100%; height:20%">
  349.         <input id="maptype" type="hidden" value="roadmap"/>
  350.         <table align="center" valign="center">
  351.             <tr>
  352.                 <td colspan="7" align="center"><b>Find the distance between two locations</b></td>
  353.             </tr>
  354.             <tr>
  355.                 <td colspan="7">&nbsp;</td>
  356.             </tr>
  357.             <tr>
  358.                 <td>First address:</td>            
  359.                 <td><input type="text" name="address1" id="address1" size="50"/></td>              
  360.                 <td>Second address:</td>               
  361.                 <td><input type="text" name="address2" id="address2" size="50"/></td>
  362.             </tr>
  363.             <tr>
  364.                 <td td colspan="7">&nbsp;&nbsp;&nbsp;Route type:
  365.                     <select id="travelMode" name="travelMode">
  366.                         <option value="driving">driving</option>
  367.                         <option value="walking">walking</option>
  368.                         <option value="bicycling">bicycling (only in US)</option>
  369.                     </select>
  370.                 </td>
  371.             </tr>
  372.             <tr>
  373.                 <td colspan="7">&nbsp;</td>
  374.             </tr>
  375.             <tr>
  376.                 <td colspan="7" align="center"><input type="button" value="Find Distance" onclick="initialize();"/></td>
  377.             </tr>
  378.         </table>
  379.     </div>
  380.     <center><div style="width:100%; height:8%" id="distance_direct"></div></center>
  381.     <center><div style="width:100%; height:8%" id="distance_road"></div></center>
  382.     <center><div style="width:100%; height:20%" id="share"></div></center>
  383.     <center><div id="map_canvas" style="width:60%; height:45%; display: inline-block;"></div></center> 
  384.    
  385.     <center><div style="width:100%; height:4%">Demo App by @usman</div></center>
  386.    
  387. </body>
  388. </html>



No comments:

Post a Comment

Comment On Facebook