Combining Google Directions and Google Places-Collection of common programming errors
Finally, I found the errors that I made.
First error.
I did not pass a necessary argument map when I created a service object.
//Before
service = new google.maps.places.PlacesService();
//After
var myOptions = {
zoom: 8,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas2"), myOptions);
service = new google.maps.places.PlacesService(map);
Second error.
I declared all variables inside a CalcRoute() function thus making them unreachable for other functions.
So, I had to declare them as global variables.
Third error.
I made two requests to Google Places API at a time. This created an error.
So, I put a second request in a callback function of a first one.
Here is a final working example.
var map
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var placesService;
var moscow = new google.maps.LatLng(55.749646,37.62368);
var start;
var end;
var places = [];
function calcRoute() {
start = 'Domodedovo airport';
end = 'Hotel Balchug Kempinsky';
if(start == '' || end == '')
{
document.getElementById("directionsPanel").innerHTML = "
Sorry, directions not found.
";
return;
}
var myOptions = {
zoom: 8,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas2"), myOptions);
var request1 = {
location: moscow,
radius: '50000',
query: start
};
//Executing Google Places request
placesService = new google.maps.places.PlacesService(map);
placesService.textSearch(request1, callback1);
}
function callback1(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
places[0] = results[0].formatted_address;
var request2 = {
location: moscow,
radius: '50000',
query: end
};
placesService.textSearch(request2, callback2);
}
else
{
document.getElementById("directionsPanel").innerHTML = "
Sorry, directions not found.
";
return;
}
}
function callback2(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
places[1] = results[0].formatted_address;
//Executing Google Directions request
var request = {
origin:places[0],
destination:places[1],
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request,
function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
directionsDisplay.setDirections(response);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
}
else
{
document.getElementById("directionsPanel").innerHTML = "
Sorry, directions not found.
";
};
});
//End of Google Directions request
}
else
{
document.getElementById("directionsPanel").innerHTML = "
Sorry, directions not found.
";
return;
}
}
Originally posted 2013-11-15 09:08:32.