var geocoder = new google.maps.Geocoder();
var service = new google.maps.DistanceMatrixService();
var map;
// https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=47601,%20USA&destinations=02543,%20USA
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
service.getDistanceMatrix({
origins: ["47601, USA"],
destinations: ["02543, USA"],
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
console.log("status=" + status + ", response=" + response);
if (status != 'OK') {
alert('Error was: ' + status);
} else {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = '';
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
if (results[j].status != 'OK') {
alert("result[" + j + "] Error was: " + results[j].status);
geocoder.geocode({
'address': destinationList[i]
}, reverseGeocodeResult);
break;
}
outputDiv.innerHTML += originList[i] + ' to ' + destinationList[j] +
': ' + results[j].distance.text + ' in ' +
results[j].duration.text + '<br>';
}
}
}
});
}
function reverseGeocodeResult(response, status) {
if (status == 'OK') {
geocoder.geocode({
latLng: response[0].geometry.location
}, findDistancesToResponses);
}
}
function findDistancesToResponses(response, status) {
var destArr = [];
for (var i = 0; i < response.length; i++) {
destArr.push(response[i].geometry.location);
}
service.getDistanceMatrix({
origins: ["47601, USA"],
destinations: destArr,
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = '';
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
if (results[j].status != 'OK') {
alert("result[" + j + "] " + destinationList[j] + " Error was: " + results[j].status);
}
outputDiv.innerHTML += originList[i] + ' to ' + destinationList[j] +
': ' + results[j].distance.text + ' in ' +
results[j].duration.text + '<br>';
}
}
})
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&ext=.js"></script>
<div id="map_canvas"></div>
<div id="output"></div>