vijay

welcome Netizen

Share Your Knowledge.It is a way to achieve immortality

Thursday, May 17, 2012

Find the distance between two places using Google map


Hi..
In this article going to write with help of google API..Here we can find the distance between two places..

Google provide many API service as free for developers. In worldwide we can easily find the distance between two places and also time needed to reach place, everything is calculated by using google map…
It’s also very interesting find our place in google map with logo..
Let us illustrate the coding with some sample pictures below show the exact difference between two places…
  CODE:
Here I gave the complete code to easy to add in anyone project..
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Google Maps API v3 Example: Distance Matrix</title>

    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>

    <style type="text/css">
        body
        {
            margin20px;
            font-familycourier, sans-serif;
            font-size12px;
        }
        #map
        {
            height480px;
            width640px;
            bordersolid thin #333;
            margin-top20px;
        }
    </style>

    <script type="text/javascript">

      var map;
      var geocoder;
      var bounds = new google.maps.LatLngBounds();
      var markersArray = [];
      
      var destinationIcon = "https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=D|FF0000|000000";
      var originIcon = "https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000";

      function initialize() {
        var opts = {
          center: new google.maps.LatLng(55.53, 9.4),
          zoom: 10,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById('map'), opts);
        geocoder = new google.maps.Geocoder();
      }
   
      function calculateDistances() {
      //*****Here we are giving the place or city name directly *****//
//***************www.dotnetcode.in******************************************
  
var origin1 =document.getElementById("txtsrc1").value;
alert(origin1);
var destinationA=document.getElementById("txtdest1").value;
var origin2=document.getElementById("txtsrc2").value;
var destinationB=document.getElementById("txtdest2").value;
alert(origin2);

//*** Uncommnet the below line if you are passing Latitude and logitude value***//
//***************www.dotnetcode.in******************************************

//var origin1 =new google.maps.LatLng(document.getElementById ("txtsrc1").value);
//var destinationA=new google.maps.LatLng(document.getElementById ("txtdest1").value);
//var orgin2=new google.maps.LatLng(document.getElementById ("txtsrc2").value);
//var destinationB=new google.maps.LatLng(document.getElementById ("txtdet2").value);

        var service = new google.maps.DistanceMatrixService();
        service.getDistanceMatrix(
          {
            origins: [origin1, origin2],
            destinations: [destinationA, destinationB],
            travelMode: google.maps.TravelMode.DRIVING,
            unitSystem: google.maps.UnitSystem.METRIC,
            avoidHighways: false,
            avoidTolls: false
          }, callback);
      }

      function callback(response, status) {
        if (status != google.maps.DistanceMatrixStatus.OK) {
          alert('Error was: ' + status);
        } else {
          var origins = response.originAddresses;
          var destinations = response.destinationAddresses;
          var outputDiv = document.getElementById('outputDiv');
          outputDiv.innerHTML = '';
          deleteOverlays();

          for (var i = 0; i < origins.length; i++) {
            var results = response.rows[i].elements;
            addMarker(origins[i], false);
            for (var j = 0; j < results.length; j++) {
              addMarker(destinations[j], true);
              outputDiv.innerHTML += origins[i] + " to " + destinations[j]
                  + ": " + results[j].distance.text + " in "
                  + results[j].duration.text + "<br />";
            }
          }
        }
      }

      function addMarker(location, isDestination) {
        var icon;
        if (isDestination) {
          icon = destinationIcon;
        } else {
          icon = originIcon;
        }
        geocoder.geocode({'address': location}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            bounds.extend(results[0].geometry.location);
            map.fitBounds(bounds);
            var marker = new google.maps.Marker({
              map: map,
              position: results[0].geometry.location,
              icon: icon
            });
            markersArray.push(marker);
          } else {
            alert("Geocode was not successful for the following reason: "
              + status);
          }
        });
      }
     
      function deleteOverlays() {
        if (markersArray) {
          for (i in markersArray) {
            markersArray[i].setMap(null);
          }
          markersArray.length = 0;
        }
      }

    </script>

</head>
<body onload="initialize()">
 <form id="form1" runat="server">

    <div id="inputs">
        <pre class="prettyprint">
<%--var origin1 = new google.maps.LatLng(55.930385, -3.118425);
var origin2 = "Greenwich, England";
var destinationA = "Stockholm, Sweden";
var destinationB = new google.maps.LatLng(50.087692, 14.421150);--%>
      </pre>
        <div>
            Source 1<asp:TextBox ID="txtsrc1" runat="server"></asp:TextBox>
            Destination 1<asp:TextBox ID="txtdest1" runat="server"></asp:TextBox>
        </div>
        <div>
            Source 2<asp:TextBox ID="txtsrc2" runat="server"></asp:TextBox>
            Destination 2<asp:TextBox ID="txtdest2" runat="server"></asp:TextBox>
        </div>
        <p>
            <button type="button" onclick="calculateDistances();">
                Calculate distances</button></p>
    </div>
    <div id="outputDiv">
    </div>
    <div id="map">
    </div>
    </form>
</body>
</html>

To find the particular place ,we can use place name directly or we have to Latitude or Longitude value in the textbox..So when using Latitude and Longitude we need to change the below code in java script..
//var origin1 =new google.maps.LatLng(document.getElementById ("txtsrc1").value);
//var destinationA=new google.maps.LatLng(document.getElementById ("txtdest1").value);
//var orgin2=new google.maps.LatLng(document.getElementById ("txtsrc2").value);
//var destinationB=new google.maps.LatLng(document.getElementById ("txtdet2").value);

I hope everyone like this article..Post your comments here….

0 comments:

Post a Comment