Array to create multiple routes on Google Maps v3

Fred Vicentin picture Fred Vicentin · Aug 2, 2012 · Viewed 9.8k times · Source

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);
                }
    })      

        }
 });
}  

Answer

geocodezip picture geocodezip · Aug 3, 2012

Based off my previous example from your earlier question

This is what you say you want: working example with multiple routes

code snippet:

var map, ren, ser;
var data = {};
var data2 = {};
var marker;
var infowindow;
var doMark = true;
var directionsDisplay;

var wayA = [];
var wayB = [];
var directionResult = [];

//Função de Inicio

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
    }
    //Cria o mapa do google, coloca as definições do mapa, como tipo de visualização, pode ser ROADMAP, SATELLITE, HYBRID, TERRAIN
  map = new google.maps.Map(mapDiv, mapOptions);


  var control = document.createElement('DIV');
  control.style.padding = '1px';
  control.style.border = '1px solid #000';
  control.style.backgroundColor = 'white';
  control.style.cursor = 'pointer';
  control.innerHTML = '<img src="http://i47.tinypic.com/2dlp2fc.jpg" border="0" alt="Image and video hosting by TinyPic">';
  control.index = 1;
  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

      }));

      //Renderiza a rota, o draggable é diz se o waypoint é arrastavel ou não
      ren = new google.maps.DirectionsRenderer({
        'draggable': true
      });
      ren.setMap(map);
      ren.setPanel(document.getElementById("directionsPanel"));
      ser = new google.maps.DirectionsService();

      //Cria a rota, o DirectionTravelMode pode ser: DRIVING, WALKING, BICYCLING ou TRANSIT
      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);
        }
      })

    }
  });
}

var html = "<table>" +
  "<tr><td>Nome:</td> <td><input type='text' id='name'/> </td> </tr>" +
  "<tr><td>Endereco:</td> <td><input type='text' id='address'/></td> </tr>" +
  "<tr><td>Tipo:</td> <td><select id='type'>" +
  "<option value='oficina' SELECTED>oficina</option>" +
  "<option value='restaurante'>restaurante</option>" +
  "</select> </td></tr>" +
  "<tr><td></td><td><input type='button' value='Salvar' onclick='saveData()'/></td></tr>";
infowindow = new google.maps.InfoWindow({
  content: html
});


//Geocoding (pesquisar)
function marcar() {
  var endereco = document.getElementById("endereco").value;
  //alert(endereco)
  geocoder = new google.maps.Geocoder();
  geocoder.geocode({
    'address': endereco
  }, function(results, status) {
    if (status = google.maps.GeocoderStatus.OK) {
      latlng = results[0].geometry.location;
      markerInicio = new google.maps.Marker({
        position: latlng,
        map: map
      });
      map.setCenter(latlng);
    }
  });
}

function markNow() {
  if (doMark == false) {

    google.maps.event.addListener(map, "click", function(event) {
      marker = new google.maps.Marker({

        position: event.latLng,
        map: map

      });
      google.maps.event.addListener(marker, "click", function() {
        infowindow.open(map, marker);
      });
    });
  }
}

google.maps.event.addDomListener(window, 'load', goma);
html,
body {
  height: 100%;
  width: 100%;
}
<script src="http://maps.google.com/maps/api/js"></script>
<div id="mappy" style="float:left;width:70%; height:100%"></div>
<div id="directionsPanel" style="float:right;width:30%;height 100%"></div>
<div>
  <label>Endereco</label>
  <input type="text" id="endereco">
</div>

<input type="button" value="Marcar" id="marcar" onClick="marcar()">


</div>