Hi nauna,
Refer below code.
HTML
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=API_Key&libraries=places"></script>
<script type="text/javascript">
$(document).ready(function () {
$input = $("#txtPlace");
var options = { types: ['(cities)'] };
autocomplete = new google.maps.places.Autocomplete($input.get(0), options);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var address = autocomplete.getPlace().formatted_address;
if (document.getElementById("lblAddress").innerHTML == "") {
document.getElementById("lblAddress").innerHTML = address;
$input.val('').attr('placeholder', 'Enter Destination');
}
else {
document.getElementById("lblAddress").innerHTML = document.getElementById("lblAddress").innerHTML + "</br>" + address;
$input.val('').attr('placeholder', '');
}
if (document.getElementById("lblAddress").innerHTML.split('<br>').length == 2) {
var soure = document.getElementById("lblAddress").innerHTML.split('<br>')[0];
var destination = document.getElementById("lblAddress").innerHTML.split('<br>')[1];
GetRoute(soure, destination);
}
});
});
function GetRoute(source, destination) {
var directionsDisplay;
directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
var directionsService = new google.maps.DirectionsService();
//*********DISTANCE AND DURATION**********************//
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
var distance = response.rows[0].elements[0].distance.text;
var duration = response.rows[0].elements[0].duration.text;
var dvDistance = document.getElementById("dvDistance");
dvDistance.innerHTML = "";
dvDistance.innerHTML += "Distance: " + distance + "<br />";
dvDistance.innerHTML += "Duration:" + duration;
} else {
alert("Unable to find the distance via road.");
}
});
}
</script>
<input type="text" id="txtPlace" style="width: 200px" placeholder="Enter Source" />
<br />
<asp:Label ID="lblAddress" Text="" runat="server" />
<table>
<tr>
<td colspan="2">
<div id="dvDistance">
</div>
</td>
</tr>
<tr>
<td>
<div id="dvMap" style="width: 300px; height: 300px">
</div>
</td>
<td>
<div id="dvPanel" style="width: 300px; height: 300px">
</div>
</td>
</tr>
</table>
Screenshot