I developed the following code to get the distance of the given 2 cities through 2 textfields and i want to send them to google maps distance matrix api using the following URl. I send those cities and got the JSON output file. but my problem is how can i get the specific attribute(distance) from that JSON file and display on a another textfield.
function m() {
var x = document.getElementById("autocomplete").value;
var y = document.getElementById("autocomplete1").value;
var url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + x + "&destinations=" + y + "&key=AIzaSyD5KX6VRon6yQ0vu4s6GSnAVzazRWg8wrc";
window.location=url; // this will go to the above url and display the JSON output file on the browser. I dont want that to be shown. just some processing and should display only the distance form that file on a textfield!
}
the JSON output file http://pastebin.ca/3318529
Please help to solve this. i am new to JSON. So if you have any other ideas tell me. Many thanks :)
If you use Javascript in Browser, you need use Google Maps Api.
Check this example:
<script src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script>
function init() {
var service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
origins: ['Los Angeles'],
destinations: ['New York'],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status !== google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
alert(response.originAddresses[0] + ' --> ' + response.destinationAddresses[0] + ' ==> ' + response.rows[0].elements[0].distance.text);
}
});
}
</script>
<body onload="init()">
</body>
Running example https://jsfiddle.net/3b03m5mt/