Reputation: 11
Getting this error with some Javascript script: TypeError: undefined is not an object (evaluating 'results[j].distance.text')
Tried adding "var results = []" as recommended in other posts, but didn't help.
function CalculatedRecommededDistance() {
event.preventDefault();
var origin = document.getElementById('pick_up_address').value;
var destination = document.getElementById('drop_off_address').value;
var geocoder = new google.maps.Geocoder();
var service = new google.maps.DistanceMatrixService();
var results = [];
service.getDistanceMatrix({
origins: [origin],
destinations: [destination],
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false,
avoidFerries: false
}, function(response, status) {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var outputDiv = document.getElementById('outputRecommended');
outputDiv.innerHTML = '';
//Display distance recommended value
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
outputDiv.innerHTML += results[j].distance.text + ' in ' +
results[j].duration.text + '<br>';
}
}
});
}
Upvotes: 0
Views: 8928
Reputation: 1659
check if you result has distance and duration Property befor you get it:
function CalculatedRecommededDistance() {
event.preventDefault();
var origin = document.getElementById('pick_up_address').value;
var destination = document.getElementById('drop_off_address').value;
var geocoder = new google.maps.Geocoder();
var service = new google.maps.DistanceMatrixService();
var results = [];
service.getDistanceMatrix({
origins: [origin],
destinations: [destination],
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false,
avoidFerries: false
}, function(response, status) {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var outputDiv = document.getElementById('outputRecommended');
outputDiv.innerHTML = '';
//Display distance recommended value
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
if (result[j].hasownproperty("distance") && result[j].hasownproperty("duartion")){
outputDiv.innerHTML += results[j].distance.text + ' in ' +
results[j].duration.text + '<br>';
}
}
}
});
}
Upvotes: 0
Reputation: 383
Javascript TypeError: undefined is not an object
that means you're trying to treat undefined
value as an Object
. (simply: trying to get data from undefined
value)
you can safely ignore this error by using ?
. As results[j]?.distance?.text
. But this not grantee you will get the expected result. So, first console.log(result)
and see that expected objects are in that output.
Upvotes: 1