Tuesday, October 23, 2012

Find distance b/w places

Now we have come to an interesting part , Do you need to find the distance between any two places aroud the world , it's achieved using jQuery maps3 plugin . This is achieved by using the action 'getDistance' and the travel model used here 'google.maps.TravelMode.DRIVING'. Now enjoy calculating the distance between your fav places around the world .

If no Results are found we display a message 'No route could be found between the origin and destination'

If the Source and the destion could not be identified then we display a message 'The origin and/or destination of this pairing could not be geocoded'




<html>
<head>
<script type="text/javascript" src="../jquery/jquery-1.4.4.min.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript" src="../gmap3.js"></script>
<style>
.gmap3 {
  margin: 20px auto;
  border: 1px dashed #C0C0C0;
  width: 1024px;
  height: 768px;
}
</style>
<script type="text/javascript">
function distance(){
  $('body').gmap3({
    action:'getDistance',
    options:{
      origins:[$('#origins').val()],
      destinations:[$('#destinations').val()],
      travelMode: google.maps.TravelMode.DRIVING
    },
    callback: function(results){
      var html = '';
      if (results){
        for (var i = 0; i < results.rows.length; i++){
          var elements = results.rows[i].elements;
          for(var j=0; j<elements.length; j++){
            switch(elements[j].status){
              case google.maps.DistanceMatrixStatus.OK:
                html += elements[j].distance.text + ' (' + elements[j].duration.text + ')<br />';
                break;
              case google.maps.DistanceMatrixStatus.NOT_FOUND:
                html += 'The origin and/or destination of this pairing could not be geocoded<br />';
                break;
              case google.maps.DistanceMatrixStatus.ZERO_RESULTS:
                html += 'No route could be found between the origin and destination.<br />';
                break;
            }
          }
        }
      } else {
        html = 'error';
      }
      $('#results').html( html );
    }
  });
}
</script>
</head>

<body>
Origin :
<input type="text" id="origins" />
Destination :
<input type="text" id="destinations" />
<input type="button" id="distance" value="distance" onclick="distance();">
<br />
<br />
Results :
<div id="results"></div>
</body>
</html>


Google maps get Distance using map3 Plugin

No comments:

Post a Comment