I've been working with the Google Maps API for quite some time, previously being able to successfully use the Distance Matrix service here. Then I decided to do some refactoring and issues arose...
When trying to get the results of the Distance Matrix service, the rows
object contains an empty (status: ZERO_RESULTS
) array of objects.
The empty object during runtime below:
Normally it would look like this below:
An array of coords
gets passed into the distanceMatrixCoords()
function. They look like this:
And the other variables, such as var origins = pos;
is populated correctly with a coordinates string.
The entire file containing this code is available here
function distanceMatrixCoords(coords) {
var origins = pos;
var destinations = coords;
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [origins],
destinations: destinations,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
},
callback
);
function callback(response, status) {
if (status == google.maps.DistanceMatrixStatus.OK) {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var distanceElement = [];
var theRow = null;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
var element = results[j];
var distance = element.distance.text;
var duration = element.duration.text;
var from = origins[i];
var to = destinations[j];
distanceElement[j] = document.createElement('p');
distanceElement[j].innerHTML = results[j].distance.text;
distanceElement[j].className = 'distance-cell';
}
}
}
}
}
Ultimately, based on the code above, the line var results = response.rows[i].elements;
is where the code breaks. response.rows
is the object that has the multiple ZERO_RESULTS in the array. Compared to my previous code (linked above), the distanceMatrixCoords()
function receives the exact same type of data as before.
The response
object that is passed into the callback()
function contains these values:
destinationAddresses
and originAddresses
are populated correctly with coordinates that look like this comma separated value, "41.0259285,81.5899887"
. Once again the rows
array is the issue.
I have looked at many other sources for an answer, but the Distance Matrix service of the Google Maps API does not seem to have many resources available out there. I saw this question, but no answers have been recorded yet.
The issue was my coordinates were being returned incorrectly from the service I built to get data. The coordinates are, for example, 41.0259285,81.5899887
when they should be 41.0259285,-81.5899887
. The minus sign in front of the longitude is missing, therefore the coordinate is not valid and the distance matrix service doesn't know what to do with them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With