Google Map Get Route Direction
Resource from http://www.1stwebdesigner.com/tutorials/distance-finder-google-maps-api/
by B L Praveen
HTML
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<div id="form" style="width:100%; height:20%">
<table align="center" valign="center">
<tr>
<td colspan="7" align="center"><b>Find the distance between two locations</b></td>
</tr>
<tr>
<td colspan="7"> </td>
</tr>
<tr>
<td>First address:</td>
<td> </td>
<td><input type="text" name="address1" id="address1" size="50"/></td>
<td> </td>
<td>Second address:</td>
<td> </td>
<td><input type="text" name="address2" id="address2" size="50"/></td>
</tr>
<tr>
<td colspan="7"> </td>
</tr>
<tr>
<td colspan="7" align="center"><input type="button" value="Show" class="showRoute" /></td>
</tr>
</table>
</div>
<center><div style="width:100%; height:10%" id="distance_direct"></div></center>
<center><div style="width:100%; height:10%" id="distance_road"></div></center>
<center><div id="map_canvas" style="width:70%; height:54%"></div></center>
CSS
body {
background:#eeeeee
}
JavaScript
jQuery('.showRoute').click(function () {
initialize()
//onclick="initialize();"
});
var location1;
var location2;
var address1;
var address2;
var latlng;
var geocoder;
var map;
var distance;
// finds the coordinates for the two locations and calls the showMap() function
function initialize()
{
geocoder = new google.maps.Geocoder(); // creating a new geocode object
// getting the two address values
address1 = document.getElementById("address1").value;
address2 = document.getElementById("address2").value;
// finding out the coordinates
if (geocoder)
{
geocoder.geocode( { 'address': address1}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
//location of first address (latitude + longitude)
location1 = results[0].geometry.location;
} else
{
alert("Geocode was not successful for the following reason: " + status);
}
});
geocoder.geocode( { 'address': address2}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
//location of second address (latitude + longitude)
location2 = results[0].geometry.location;
// calling the showMap() function to create and show the map
showMap();
} else
{
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
// creates and shows the map
function showMap()
{
// center of the map (compute the mean value between the two locations)
latlng = new google.maps.LatLng((location1.lat()+location2.lat())/2,(location1.lng()+location2.lng())/2);
// set map options
// set zoom level
// set center
// map type
var mapOptions =
{
zoom: 1,
center: latlng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
// create a new map object
// set the div id where it will be shown
// set the map options
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
//...