Wednesday, October 23, 2013

Simple example for using the Distance Matrix.

Starting of this year I was playing around with good Distance Matrix API and wrote an HTML based application for proof of concept. I thought to extract a small part from that and write a blog to demonstrate the Google Distance Matrix.

As always, I have uploaded my simple code base in my GIT hub.
In this sample, I have configured the Origin as Colombo and destination as  Stockholm to calculated total distance! in between to location.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var origin = "Colombo, Srilanka",
destination = "Stockholm, Sweden",
service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
avoidHighways: false,
avoidTolls: false
},
callback
);
function callback(response, status) {
var orig = document.getElementById("orig"),
dest = document.getElementById("dest"),
dist = document.getElementById("dist");
if(status=="OK") {
dest.value = response.destinationAddresses[0];
orig.value = response.originAddresses[0];
dist.value = response.rows[0].elements[0].distance.text;
} else {
alert("Error: " + status);
}
}
</script>
</head>
<body>
<br>
Very simple HTML sample for using the Google Distance Matrix API.<br><br>
<table border="0">
<tr>
<td>Origin</td>
<td><input id="orig" type="text" style="width:35em"></td>
</tr>
<tr>
<td>Destination</td>
<td><input id="dest" type="text" style="width:35em"></td>
</tr>
<tr>
<td>Distance</td>
<td><input id="dist" type="text" style="width:35em"></td>
</tr>
</table>
</body>
</html>


I initiated new "DistanceMatrixService" and called the "getDistanceMatrix" With parameters!

So go head, change code and play with it!

No comments:

Post a Comment