Smart Recent Blog Post List

Sep 14, 2011

Distance between two locations with Google Map API

One can easily calculate distance between two location with the help of Google Map APIs. Google Map APIs comes with a set of classes which helps in doing such tasks.
class GDirection, helps in getting the travel distance between the two different location.
So example shown below targets following features :-

  •  Getting distance between two location. 
  •  Getting duration between two location. 
Here goes the complete java script code for it
-------------------------------------------------------------------------------
    <script type="text/javascript">
    var map;
    var gdir;
    var geocoder null;
    var addressMarker;
    var distance;
    
    function initialize({
      if (GBrowserIsCompatible(){      
        map new GMap2(document.getElementById("map_canvas"));

        gdir new GDirections(mapdocument.getElementById("directions"));
    
        GEvent.addListener(gdir"load"onGDirectionsLoad);
        GEvent.addListener(gdir"error"handleErrors);
    
        setDirections("San Francisco""Mountain View""en_US");
      }
    }
    
    function setDirections(fromAddresstoAddresslocale{
      gdir.load("from: " fromAddress " to: " toAddress,
                "locale"locale });
    }
    
    function onGDirectionsLoad()
        // Use this function to access information about the latest load()
        // results.
        // e.g.
      distance gdir.getDistance().meters;
      
      alert("Distance is : " gdir.getDistance().meters "and Duration Is: " +
            gdir.getDuration().seconds/60);
        
      document.getElementById("fdistance").innerHTML gdir.getDistance().meters;
      document.getElementById("fduration").innerHTML gdir.getDuration().seconds/60;
      
    }
    script>
 -------------------------------------------------------------------------------




Can we call GDirection without creating GMap ?
  So the answer is yes, one can create GDirection without pasing GMap also.
So the output will only contain text format.
sample code
       gdir new GDirections(nulldocument.getElementById("directions"));
so instead of map object null is passed in above code line, it will
display direction information in only text format.
One can also use above logic to design their own Google Gadgets too.



1 comments:

Calculating driving distance between two different location is pretty easy with Google MAP APIs.

Post a Comment

Smart Recent Blog Post List