How to show two routes on the same map? - google-maps

How to show two routes on the same map?
Example: A->B y C->D.
Using Google Maps API.
function calcRoute1() {
var start = 'Huanchaco-Trujillo';
var end = 'Lince-Lima';
var request1 = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request1, function(response1, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response1);
}
});
}
function calcRoute2() {
var start = 'Chiclayo-Lambayeque';
var end = 'Tacna-Tacna';
...
}

This works for me:
var directionsService1 = new google.maps.DirectionsService();
var directionsDisplay1 = new google.maps.DirectionsRenderer();
function calcRoute1() {
var start = 'Huanchaco-Trujillo';
var end = 'Lince-Lima';
var request1 = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService1.route(request1, function(response1, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay1.setDirections(response1);
directionsDisplay1.setMap(map);
}
});
}
var directionsService2 = new google.maps.DirectionsService();
var directionsDisplay2 = new google.maps.DirectionsRenderer();
function calcRoute2() {
var start = 'Chiclayo-Lambayeque';
var end = 'Tacna-Tacna';
var request2 = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService2.route(request2, function(response2, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay2.setDirections(response2);
directionsDisplay2.setMap(map);
}
});
}
google.maps.event.addDomListener(window, 'load', load);
working example

Related

generating multiple google map on same page

I want to generate multiple google map on the same page each showing the route for different destinations.Here is my code :
var container = document.getElementById("container");
function initMap() {
for(var i=0;i<5;i++ ){
container.innerHTML += '<div class="mapSize" id="map' + i + '"></div>';
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
var map = new google.maps.Map(document.getElementById('map'+ i), {
zoom: 11,
center: {lat:-20.239340, lng:57.574604 }
});
directionsDisplay.setMap(map);
var start = 'Albion, Mauritius';
var end = 'Grand Port District, Mauritius';
directionsService.route({
origin: start,
destination: end,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
}
The problem is that the map is displaying only in the last div and I am getting a warning in the "directionsDisplay.setDirections(response);" line : Mutable variable is accessible from closure. Please help me
You have several problems with the posted code. The main issue is the asynchronous nature of the DirectionsService. You need to assign a DirectionsService/DirectionsRenderer to each map. One way to do that is to put the code to create the map and directions in a function and use function closure.
function makeMap(mapEl, start, end) {
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
var map = new google.maps.Map(mapEl, {
zoom: 11,
center: {
lat: -20.239340,
lng: 57.574604
}
});
directionsDisplay.setMap(map);
directionsService.route({
origin: start,
destination: end,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
proof of concept fiddle
code snippet:
function initMap() {
var container = document.getElementById("container");
var maps = [];
var directionsDisplays = [];
var start = 'Albion, Mauritius';
var end = ['Grand Port District, Mauritius', "Port Lous, Mauritius", "Medine Camp de Masque, Mauritius", "Poste Lafayette, Mauritius", "Souillac, Mauritius"];
for (var i = 0; i < 5; i++) {
// container.innerHTML += '<div class="mapSize" id="map' + i + '"></div>';
var elem = document.createElement("div");
elem.setAttribute("class", "mapSize");
elem.setAttribute("id", "map" + i);
container.appendChild(elem);
makeMap(elem, start, end[i]);
}
}
google.maps.event.addDomListener(window, "load", initMap);
function makeMap(mapEl, start, end) {
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
var map = new google.maps.Map(mapEl, {
zoom: 11,
center: {
lat: -20.239340,
lng: 57.574604
}
});
directionsDisplay.setMap(map);
directionsService.route({
origin: start,
destination: end,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
html,
body,
#container {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
.mapSize {
height: 400px;
width: 400px;
}
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="container"></div>

Google Direction API directionsService.route() does not return result

I have tried to utilise the direction api to calculate distance between two places. However, the .route() service does not seem to hold.
$scope.getRes = function(id) {
$scope.bookingReference = {};
$http.get('/api/carpooler/'+id)
.success(function(data) {
data.travelDate = new moment(data.travelDate).format("MMM Do YYYY");
data.travelTime = new moment(data.travelTime).format("h:mm:ss a");
$scope.bookingReference = data;
})
.error(function(data) {
console.log('Error: ' + data);
});
for(i = 0;i<$scope.bookings.length;i++) {
dd = calcRoute($scope.bookings[i].Destination,$scope.bookingReference.Destination);
if( dd < 5000) {// 5 KM
$scope.bookingResultArray.push($scope.bookings[i]);
}
}
$scope.status2 = true;
};
I am calling the calcRoute to return the distance.
var directionsService = new google.maps.DirectionsService();
function calcRoute(ref1,ref2) {
var start = String(ref1);
var end = String(ref2);
var args = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
}
directionsService.route(args, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var myroute=directionsDisplay.directions.routes[0];
} else {
alert("fail");
}
});
var distance= 0;
for(i = 0; i < myroute.legs.length; i++){
distance += myroute.legs[i].distance.value;
//for each 'leg'(route between two waypoints) we get the distance and add it to the total
}
return distance;
};
I get the following error :
Error: myroute is not defined
calcRoute#http://localhost:3000/controllers/home.js:73:12
$scope.getRes#http://localhost:3000/controllers/home.js:91:20
Parser.prototype.functionCall/<#http://localhost:3000/vendor/angular.js:11026:15
ngEventHandler/</<#http://localhost:3000/vendor/angular.js:20468:17
$RootScopeProvider/this.$get</Scope.prototype.$eval#http://localhost:3000/vendor/angular.js:12874:16
$RootScopeProvider/this.$get</Scope.prototype.$apply#http://localhost:3000/vendor/angular.js:12972:18
ngEventHandler/<#http://localhost:3000/vendor/angular.js:20467:15
m.event.dispatch#https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js:4:8497
m.event.add/r.handle#https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js:4:5235
The source for google maps api
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="http://maps.googleapis.com/maps/api/js?libraries=places"></script>
I cannot figure out why the status is always not okay in the directionsService.route call [the alert with "fail" is always the one to turn up]
Am i doing it wrong? I am using angular but i think its not the issue.
You can't access myroute until it exists (inside the DirectionsService callback function). There you need to use the value:
function calcRoute(ref1, ref2) {
var start = String(ref1);
var end = String(ref2);
var args = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
}
directionsService.route(args, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var myroute = directionsDisplay.directions.routes[0];
var distance = 0;
for (i = 0; i < myroute.legs.length; i++) {
distance += myroute.legs[i].distance.value;
//for each 'leg'(route between two waypoints) we get the distance and add it to the total
}
document.getElementById('distance').innerHTML = distance +" meters";
} else {
alert("fail");
}
});
};
proof of concept fiddle
code snippet:
var geocoder;
var map;
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var directionsService = new google.maps.DirectionsService();
directionsDisplay.setMap(map);
calcRoute("New York, NY", "Baltimore, MD");
}
google.maps.event.addDomListener(window, "load", initialize);
function calcRoute(ref1, ref2) {
var start = String(ref1);
var end = String(ref2);
var args = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
}
directionsService.route(args, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var myroute = directionsDisplay.directions.routes[0];
var distance = 0;
for (i = 0; i < myroute.legs.length; i++) {
distance += myroute.legs[i].distance.value;
//for each 'leg'(route between two waypoints) we get the distance and add it to the total
}
document.getElementById('distance').innerHTML = distance + " meters";
} else {
alert("fail");
}
});
};
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="distance"></div>
<div id="map_canvas" style="border: 2px solid #3872ac;"></div>

Google Directions Service with Waypoints not working

Here is my code for displaying waypoints with google directions:-
// Show Route (-)
if (e.keyCode == 109 && $("#booking-docket").dialog("isOpen")) {
var pickup = $('#txt-pickup-lat-long').val();
var pickupLat = pickup.split(",")[0];
var pickupLng = pickup.split(",")[1];
var destination = $('#txt-destination-lat-long').val();
var destinationLat = destination.split(",")[0];
var destinationLng = destination.split(",")[1];
var via = $('#txt-via-lat-long').val();
var viaLat = via.split(",")[0];
var viaLng = via.split(",")[1];
var start = new google.maps.LatLng(parseFloat(pickupLat), parseFloat(pickupLng));
var end = new google.maps.LatLng(parseFloat(destinationLat), parseFloat(destinationLng));
var waypts = new google.maps.LatLng(parseFloat(viaLat), parseFloat(viaLng));
var request = {
origin:start,
destination:end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
It worked perfectly fine until I added the waypoint in, not sure why but nothing happens now when I try to show the route, any ideas?
Your original example could be changed like:
//var waypts = new google.maps.LatLng(parseFloat(viaLat), parseFloat(viaLng));
var request = {
origin:start,
destination:end,
waypoints: [{
location: new google.maps.LatLng(parseFloat(viaLat), parseFloat(viaLng)),
stopover: false
}],
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};

How to add multiple (separated with a plus symbol) waypoints to a map

Thanks to geocodezip , I have managed to create a map with directions functionality and XML markers loaded. There is a problem left though:
How can I add waypoints to it? They should be separated by plus symbol or something else appropriate.
Here is the current code:
<script type="text/javascript">
//<![CDATA[
// global "map" variable
var map = null;
var rendererOptions = {
draggable: true
};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);;
var directionsService = new google.maps.DirectionsService();
// A function to create the marker and set up the event window function
function createMarker(latlng, name, html) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
var contentString = html;
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
}
// ===== request the directions =====
function getDirections() {
// ==== Set up the walk and avoid highways options ====
var request = {};
if (document.getElementById("walk").checked) {
request.travelMode = google.maps.DirectionsTravelMode.WALKING;
} else {
request.travelMode = google.maps.DirectionsTravelMode.DRIVING;
}
if (document.getElementById("highways").checked) {
request.avoidHighways = true;
}
if (document.getElementById("alternatives").checked) {
request.provideRouteAlternatives = true;
}
// ==== set the start and end locations ====
var saddr = document.getElementById("saddr").value
var daddr = document.getElementById("daddr").value
request.origin = saddr;
request.destination = daddr;
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function initialize() {
// create the map
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(43.907787,-79.359741),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// Read the data from example.xml
if (document.getElementById("showmarkers").checked) {
downloadUrl("example.xml", function(doc) {
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
var html = markers[i].getAttribute("html");
var label = markers[i].getAttribute("label");
// create the marker
var marker = createMarker(point,label,html);
}
});
}
// Read the data from example2.xml
if (document.getElementById("showmarkers2").checked) {
downloadUrl("example2.xml", function(doc) {
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
var html = markers[i].getAttribute("html");
var label = markers[i].getAttribute("label");
// create the marker
var marker = createMarker(point,label,html);
}
});
}
}
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
//]]>
</script>
This is the code I have used to generate waypoints, but it's not working now:
var via = document.getElementById("via").value;
if (via) {
so = via.split("+")
if (so.length > 1) {
var wpArray = [];
for (i=0; (i<so.length); i++) {
wpArray.push({location: so[i], stopover:true})
}
request = {
origin:saddr,
destination:daddr,
waypoints: wpArray,
provideRouteAlternatives: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}
} else {
request = {
origin:saddr,
destination:daddr,
waypoints:[{location:via, stopover:true}],
provideRouteAlternatives: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}
}
} else {
request = {
origin:saddr,
destination:daddr,
provideRouteAlternatives: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}
}
EDIT This is the working function:
function getDirections() {
// ==== Set up the walk and avoid highways options ====
var request = {};
if (document.getElementById("walk").checked) {
request.travelMode = google.maps.DirectionsTravelMode.WALKING;
} else {
request.travelMode = google.maps.DirectionsTravelMode.DRIVING;
}
if (document.getElementById("highways").checked) {
request.avoidHighways = true;
}
if (document.getElementById("alternatives").checked) {
request.provideRouteAlternatives = true;
}
// ==== set the start and end locations ====
var start = document.getElementById("start").value
var end = document.getElementById("end").value
request.origin = start;
request.destination = end;
request.waypoints = via;
var so;
var via = document.getElementById("via").value;
if (via) {
so = via.split("+")
if (so.length > 1) {
var wpArray = [];
for (i=0; (i<so.length); i++) {
wpArray.push({location: so[i], stopover:false})
}
request = {
origin:start,
destination:end,
waypoints: wpArray,
provideRouteAlternatives: true,
avoidHighways: document.getElementById("highways").checked,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}
} else {
request = {
origin:start,
destination:end,
waypoints:[{location:via, stopover:false}],
provideRouteAlternatives: true,
avoidHighways: document.getElementById("highways").checked,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}
}
} else {
request = {
origin:start,
destination:end,
provideRouteAlternatives: true,
avoidHighways: document.getElementById("highways").checked,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}
}
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
Not sure why you have 2 xml files or what their format is. Here is an example which shows/hides markers based on their categories (again translated from Mike Williams' v2 tutorial):
http://www.geocodezip.com/v3_MW_example_categories.html
(also copied to How to show/hide markers from XML file without refreshing the page with the part of the question it applied to)

Displaying multiple routes on a google map

I am trying to display multiple routes on same map but am unable to do so.
No matter what I do I get only one route.
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
Any pointers will be helpful.
I had the same problem. This thread on a Google group for Google maps shows how to do it.
The author (a Google employee), wrote this:
You should be able to create two DirectionsRenderer objects, each that
use the same map and different DirectionsResults.
var map = new google.maps.Map(document.getElementById("map_canvas"));
function renderDirections(result) {
var directionsRenderer = new google.maps.DirectionsRenderer;
directionsRenderer.setMap(map);
directionsRenderer.setDirections(result);
}
var directionsService = new google.maps.DirectionsService;
function requestDirections(start, end) {
directionsService.route({
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(result) {
renderDirections(result);
});
}
requestDirections('Huntsville, AL', 'Boston, MA');
requestDirections('Bakersfield, CA', 'Vancouver, BC');
I tried it and it does work.
Did you try as follows?
Here I have captured one path and displayed it. You can do the same by writing pointsArray = result.routes[1].overview_path; besides it and display it in a new loop.
directionsService.route (request, function (result, status)
{
if (status == google.maps.DirectionsStatus.OK)
{
directionsDisplay.setDirections (result);
pointsArray = result.routes[0].overview_path;
var i = 0;
var j = 0;
for (j = 0; j < pointsArray.length; j++)
{
var point1 = new google.maps.Marker ({
position:pointsArray [j],
draggable:false,
map:map,
flat:true
});
}
}
});