I’m a c++ programmer so the following undefined variable error in java script is strange for me. I’ve defined a global variable ,directionResult and the following code initializes its value :
function calcRoute() {
var iMap = {
departure:"tiran,esfahan",
destination:"esfahan"
}
var request = {
origin : iMap.departure,
destination : iMap.destination,
travelMode : google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
document.getElementById("log").innerHTML = result.routes[0];
directionResult = result;
}
});
}
in the last if directionResult will be equal to result which is a parameter to a call-back function. But in another function :
function showSteps() {
var myRoute = directionResult.routes[0].legs[0];
var point = myRoute.steps[index].start_point;
var inst = myRoute.steps[index++].instructions;
obj.setPosition(point);
document.getElementById('inst').innerHTML = inst;
map.panTo(point);
if (index >= myRoute.steps.length)
clearInterval(timer);
}
when I want to use directionResult at the first line,I encounter this error:
TypeError: directionResult is undefined
How can I solve this strange behavior?thanks.
One possible reason directionResult is undefined may be because you are trying to reference it before it has been set. Although your showSteps() function appears after the calcRoute() function, directionResult is not set until the directionsService.route() callback is fired, which happens (presumably) after an AJAX request.
Try calling showSteps() from within the directionsService.route() callback function instead.