I have a problem with the Google DirectionsService. I know it's asynchronous and that is the cause of my troubles. I'd like to wait until the DirectionsService returns a result instead of executing code without an answer. Here is a sample:
function snap_to_road (lat) {
var position;
var request = {
origin: lat,
destination: lat,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
return response.routes[0].legs[0].start_location;
}
});
}
alert(snap_to_road(current.latLng));
The alert
always shows: "undefined". Is there any way to solve this?
I don't think that is possible. You could use a callback parameter in snap_to_road:
function snap_to_road (lat, callback) {
var position;
var request = {
origin: lat,
destination: lat,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
callback(response.routes[0].legs[0].start_location);
}
});
}
snap_to_road(current.latLng, function(result) {
alert(result);
});
Call your alert method after google directions returns result. Like:
Call snap_to_road after button click event.
function snap_to_road (lat) {
var position;
var request = {
origin: lat,
destination: lat,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
ShowAlert(response.routes[0].legs[0].start_location);
}
});
}
function ShowAlert(result){
alert(result);
}
Here is an example of what I mentioned above:
var path = "/path/to/some/resource";
$.ajax({
url: path,
type: "get",
data: serializedData, //<-- depends on what data you are using
async: false, //will wait until resource has loaded or failed
//will be called on success
success: function(response, textStatus, jqXHR){
// log a message to the console
console.log("Successfully loaded resource!");
},
//will be called on error
error: function(jqXHR, textStatus, errorThrown){
// log the error to the console
console.log(
"The following error occured: "+
textStatus, errorThrown
);
},
// callback handler that will be called on completion
// which means, either on success or error
complete: function(){
console.log("Completed: with error or success");
}
});