At first, my problem was that the google maps with direction service was not loading correctly. After some researches, i find google.maps.event.trigger(map, 'resize').
Ok, now it works. Kinda.
The order of my app is: page x, page A with the map and the direction, page y, page B with the map and the direction.
My script is:
function initialize(mapa_id) {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 17,
mapTypeControl: false,
zoomControl: false,
draggable: false,
center: new google.maps.LatLng(-23.583693,-48.042186),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById(mapa_id), mapOptions);
google.maps.event.trigger(map, 'resize');
directionsDisplay.setMap(map);
if(mapa_id == 'map-canvas'){
navigator.geolocation.getCurrentPosition(rotaInicial, onError, options);
}else{
directionsDisplay.setMap(map);
navigator.geolocation.getCurrentPosition(rotaFinal, onError, options);
}
}
function rotaInicial(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var start = new google.maps.LatLng(latitude,longitude);
var end = new google.maps.LatLng(-23.578659,-48.038045);
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
google.maps.event.trigger(map, 'resize');
directionsDisplay.setDirections(response);
}
});
}
function rotaFinal() {
var start = new google.maps.LatLng(-23.578659,-48.038045);
var end = new google.maps.LatLng(-23.585503,-48.038324);
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
google.maps.event.trigger(map, 'resize');
directionsDisplay.setDirections(response);
}
});
}
So, what happens now: the page A loads the map first (correctly and with no directions) and then after a few seconds (5 - 8) the 'resize' happens and it shows the directions. Then it goes to page y, after click the button it goes to the page B and the map appears only on the top left. After a few seconds again, the 'resize' happens and show the directions. when i do this routine again (back to page x), the first map loads also in top left and it happens all those things.
I have two problems.
I'm not sure if i put the 'resize' code in the right place. Any ideas?
you call both functions that will draw the route(rotaInicial & rotaIFinal) in the success-callback of navigator.geolocation.getCurrentPosition
. getCurrentPosition
will be executed asynchronously and it may take some time till you get a result.
Therefore, as long as you need to set the direction based on the users location, there isn't anything you can do to speed-up the drawing of the directions.