I have a Google Maps project, and I want to do an array to create multiple routes using directions.
For example, I click on the map and appear a marker named "A", and when I click the second time, display a marker named "B". Ok, this is working.
But when I click the third time I want to display a new "A" point and the fourth time a new "B", don't need to erase the other route. I want only to display multiple routes, I know that I need to create an Array, but i don't know where i put the array, and etc. I will post here my code, if someone can create an example for me will be so helpful.
This is my example
And this was my resumed code without the multiple routes:
var wayA ;
var wayB;
var doRoute = true;
if (doRoute == true){
doRoutes();
}
function doRoutes()
{
google.maps.event.addListener(map, "click", function(event) {
if (!wayA) {
wayA = new google.maps.Marker({
position: event.latLng,
map: map
});
}else if (wayA){
wayB = new google.maps.Marker({
position: event.latLng,
map: map
});
ren = new google.maps.DirectionsRenderer( {'draggable':true} );
ren.setMap(map);
ren.setPanel(document.getElementById("directionsPanel"));
ser = new google.maps.DirectionsService();
ser.route({ 'origin': wayA.getPosition(), 'destination': wayB.getPosition(), 'travelMode': google.maps.DirectionsTravelMode.DRIVING},function(res,sts) {
if(sts=='OK')ren.setDirections(res);
})
}
});
}
}
This is the resolution:
var map, ren, ser;
var data = {};
var data2 = {};
var marker;
var infowindow;
var doMark = true ;
var directionsDisplay;
var wayA = [];
var wayB = [];
var directionResult = [];
//Initialize
function goma()
{
var mapDiv = document.getElementById('mappy');
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(-23.563594, -46.654239),
mapTypeId : google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map( mapDiv, mapOptions );
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(control);
google.maps.event.addDomListener(control, 'click', function() {
doMark = false;
markNow();
});
google.maps.event.addListener(map, "click", function(event) {
if (wayA.length == wayB.length) {
wayA.push(new google.maps.Marker({
draggable: true,
position: event.latLng,
map: map
}));
} else {
wayB.push(new google.maps.Marker({
draggable: true,
position: event.latLng,
map: map
}));
ren = new google.maps.DirectionsRenderer( {'draggable':true} );
ren.setMap(map);
ren.setPanel(document.getElementById("directionsPanel"));
ser = new google.maps.DirectionsService();
ser.route({ 'origin': wayA[wayA.length-1].getPosition(), 'destination': wayB[wayB.length-1].getPosition(), 'travelMode': google.maps.DirectionsTravelMode.DRIVING},function(res,sts) {
if(sts=='OK') {
directionResult.push(res);
ren.setDirections(res);
} else {
directionResult.push(null);
}
})
}
});
}
See Question&Answers more detail:
os