I'm currently working with the Google Maps API. I use the globalFunction when user click on some button. The "calcRoad" function generate the road by using the Google Maps API, and then "Myfunction" use the data from "calcRoad" to do some calculation.
My problem is that right now "Myfunction" doesn't wait "calcRoad" to end before starting. I asume that some of the Google API requests are asynchronous but I can't access the code behind it.
How could I forced "Myfunction" to wait until "calcRoad" is done ?
function globalFunction(){
calcRoad(true,latitude, longitude);
Myfunction();
}
function calcRoad(bool,lat,long) {
marker.setVisible(false);
var date = new Date();
// Add a waypoint
if(bool){
var tampon = new google.maps.LatLng(lat,long);
waypoints.push({
location: tampon,
stopover:false
});
}
var request = {
origin: departure_place.geometry.location,
destination: arrival_place.geometry.location,
travelMode: google.maps.TravelMode[mode],
waypoints: waypoints,
avoidHighways: false,
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
PS: I tried to use some setTimeout before calling "Myfunction" and it is working but as I don't know how long will the "calcRoad" take to finish (depending on users' parametres) I can't use setTimeout.
I hope that I'm clear with my probleme, thanks in advance for your help.
You should add a callback parameter in your calcRoad function :
function globalFunction(){
calcRoad(true,latitude, longitude, Myfunction);
}
function calcRoad(bool,lat,long, cb) {
marker.setVisible(false);
var date = new Date();
// Add a waypoint
if(bool){
var tampon = new google.maps.LatLng(lat,long);
waypoints.push({
location: tampon,
stopover:false
});
}
var request = {
origin: departure_place.geometry.location,
destination: arrival_place.geometry.location,
travelMode: google.maps.TravelMode[mode],
waypoints: waypoints,
avoidHighways: false,
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
cb && cb(); // Check if "cb" callback function is defined and execute it
}
});
}
Something like this should work !
Related
I am trying to fit the bounds of the map after drawing the route on Google Maps, for some reason the below does not get applied, it seems that it's ignored, I've even tried to set manual zoom, it was ignored too:
var bounds = response.routes[0].bounds;
this.map.fitBounds(bounds);
Here is the current result:
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
directionsService.route({
origin: pickUp.formattedAddress,
destination: dropOff.formattedAddress,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
var bounds = response.routes[0].bounds;
this.map.fitBounds(bounds);
} else {
console.log('Directions request failed due to ' + status);
}
});
}
I'm currently developing a Webapps using the Google Maps API. I want to plot X different routes simultaneosly to the same destination location.
If I plot one, it works, but when I work with arrays (Because I don't know how many routes I will plot finally) it shows me this type of errors. The code when calculating the routes is like these.
var rendererOptions = [];
var directionsDisplay = [];
for (var k = 0; k < carLatLng.length; k++) {
rendererOptions[k] = {
map: map
};
directionsDisplay[k] = new google.maps.DirectionsRenderer(rendererOptions[k]);
var request = {
origin: carLatLng[k],
destination: place.geometry.location,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService = new google.maps.DirectionsService();
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay[k].setDirections(response);
} else alert('Failed to get directions');
});
}
The error tells me TypeError: directionsDisplay[k] is undefined. (It refers to the one inside the if() clause)
Hope guys you could help me. I have tried some options but none of them works. Only works when I eliminate the for loop (and the array-type)
Thank you
directionsService.route is asynchronous - by the time the last repsonse is received, the loop would've run it's course, and k == carLatLng.length - thus directionsDisplay[k] will be undefined
What you need is to change
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay[k].setDirections(response);
} else alert('Failed to get directions');
});
to something like
function(directionsDisplay) {
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else alert('Failed to get directions');
});
}(directionsDisplay[k]);
there's probably easier ways to make a closure, but my mind is addled at the moment
edit: for some clarity, maybe, hopefully -
function(captured_k) {
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay[captured_k].setDirections(response);
} else alert('Failed to get directions');
});
}(k);
I'm doing my work with Google Map API. To draw a route between two points, I use this function:
function calcRoute(start, end) {
var pStart = new google.maps.LatLng(start.lat(), start.lng());
var pEnd = new google.maps.LatLng(end.lat(), end.lng());
var request = {
origin: pStart,
destination: pEnd,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
// Box the overview path of the first route
var path = result.routes[0].overview_path;
boxes = rboxer.box(path, distance);
//drawBoxes(boxes);
nearbyMarkets = search_market(boxes);
// PUT HERE???
}
});
}
After this, I need access the Direction Display object, which only available after the route is rendered successfully (means this function's done). I tried to put that code block in that position, but at that time, the Direction property of Direction Display is still not available, so it's failed. But if I call it after calcRoute function, it's OK.
So, my question is, how can I know when the callback finish so that I can continue my work? I've tried putting a flag like below, but it was unsuccessful, the loop is infinite.
function calcRoute(start, end) {
var pStart = new google.maps.LatLng(start.lat(), start.lng());
var pEnd = new google.maps.LatLng(end.lat(), end.lng());
var pass = false;
var request = {
origin: pStart,
destination: pEnd,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
// Box the overview path of the first route
var path = result.routes[0].overview_path;
boxes = rboxer.box(path, distance);
//drawBoxes(boxes);
nearbyMarkets = search_market(boxes);
pass = true;
}
});
while (!pass) {
}
}
Observe the directions_changed-event:
google.maps.event.addListener(directionsDisplay, 'directions_changed',function(){
if(this.get('directions')){
//directions are available, do something
}
});
I am trying to create an object that handles Google Maps Api as following:
function GoogleMap(container, mapOptions) {
this.Container = container;
this.Options = mapOptions;
this.Map = new google.maps.Map(document.getElementById(this.Container), this.Options);
// Direction
this.DirectionService = new google.maps.DirectionsService();
this.DirectionRenderer = new google.maps.DirectionsRenderer();
this.DirectionRenderer.setMap(this.Map);
this.DirectionId = 0;
this.DirectionResponse = new Array();
this.DrawDirectionDriving = drawDirectionDriving;
}
and the drawDirectionDriving function is like this:
function drawDirectionDriving(start, end) {
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
this.DirectionService.route(request,
function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
this.DirectionRenderer.setDirections(response);
this.DirectionResponse[this.DirectionId] = response;
this.DirectionId++;
}
else {
alert("Error during drawing direction, Google is not responding...");
}
}
);
}
and in somewhere, I am using the object like this:
var myGoogleMap;
function MapInit() {
myGoogleMap = new GoogleMap("divMap", myMapOptions);
myGoogleMap.DrawDirectionDriving("İstanbul", "Ankara");
}
The Google Map is shown on my browser, there is no problem in constructing the object but error in DrawDirectionDriving function.
When I create a breakpoint on this line: " myGoogleMap.DrawDirectionDriving("İstanbul", "Ankara");" the "DirectionRenderer" seems constructed, but after this line (after the "Draw" method) the DirectionRenderer object seems null (undefined) so it outs en error like this "couldn't get setDirections properties it is null bla bla..."
Could you please give me a hand?
Thanks in advance...
The this keyword does point to something else in the route callback function. It's DirectionRenderer property resolves to null/undefined, and getting the setDirections property from that will cause the exception.
Use a dereferencing variable:
function drawDirectionDriving(start, end) {
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
var that = this;
this.DirectionService.route(request,
function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
that.DirectionRenderer.setDirections(response);
that.DirectionResponse[this.DirectionId] = response;
that.DirectionId++;
// ^^^^ points to the GoogleMap instance
}
else {
alert("Error during drawing direction, Google is not responding...");
}
}
);
}
I'm on ASP.NET MVC and I'm using Google Maps API with Javascript. I send a Model to the View with one or more waypoints to add to the route.
function calcRoute() {
initialize();
var start = "<%= Model.StartAddress %>";
var end = "<%= Model.ClientAddress %>";
var waypts = [];
waypts.push({
location: "<%= Model.PickupAddress[0] %>",
stopover:true
});
var request = {
origin: start,
destination: end,
waypoints: waypts,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
Is it possible to add waypoints this way with the addresses in Model.PickupAddress array? I have seen examples code by using JSON (for markers), but if I can do it directly in this Javascript code, that's fine for me.