Insert Multiple Routes into the Google Maps Maps Api

Asked

Viewed 1,360 times

1

how can I be putting multiple routes in my code same in the image below

Data of horigem and destination already arrive in this variable

var destino = gps.attr("destino");
var from_to = gps.attr("from_to");

Map Today

inserir a descrição da imagem aqui

As I would like
inserir a descrição da imagem aqui

  <script type="text/javascript" src="jquery-1.9.0.js"></script>
  <script src="http://maps.google.com/maps/api/js?v=3.2&sensor=false"></script>
   <script type="text/javascript" src="http://www.google.com/jsapi"></script>
   <script type="text/javascript" src="script.js"></script>
   <script type="text/javascript" src="util.js"></script>
<script>
//Icons
var customIcons = {
   airport: {
    icon: 'images/AirPort.png',
    shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
  },  
};

//Popup dos markers
var infoWindow = null;  
//A visibilidade do mapa precisa estar global
var map = null;
//Este é um array global dos marcadores presentes na tela
var markersArray = [];
 //* Inicialização da API de Mapas do Google 
function initialize() {
    //Não vou explicar o óbvio!!!
    var myLatlng = new google.maps.LatLng(-22.904546, -43.097979);
    var myOptions = {
        zoom : 11,
        center : myLatlng,
        mapTypeId : google.maps.MapTypeId.ROADMAP

    }

    map = new google.maps.Map(document.getElementById("map_canvas"),
            myOptions);
      var trafficLayer = new google.maps.TrafficLayer();
      trafficLayer.setMap(map);
      //  Inicio do Jonson para altera a cor do Mapa
    var pink_parks = [
 ];
map.setOptions({styles: pink_parks});

directionsDisplay = new google.maps.DirectionsRenderer();    
directionsDisplay.setMap(map);                   
       // Fim do jonson     

    infoWindow = new google.maps.InfoWindow;                

    //Esse método eu criei para realizar o load dos markers no mapa
    //Execução imediata!!!
    updateMaps();

    //Definimos tambem execução com intervalo de tempo
    // 5000 = 5 segundos
    // 10000= 10 segundos
    window.setInterval(updateMaps, 30000);
}
 //* Método que remove os overlays dos markers
function clearOverlays() {
  for (var i = 0; i < markersArray.length; i++ ) {
   markersArray[i].setMap(null);
  }
}
 //* Método que realiza chama o caminho do xml de dados
 //e atualiza o mapa    
function updateMaps() {
    // Vamos remover o que já havia de overlay
    // É possível implementar a remoção e inclusão seletiva
    clearOverlays();
    var timestamp = new Date().getTime();
    var data = 'gps/data.php?t=' + timestamp;

    //Me guardo o direito a não explicar o óbvio, novamente
    $.get(data, {}, function(data) {
        $(data).find("gps").each(

                function() {
                    var gps = $(this);
                    var destino = gps.attr("destino");
                    var from_to = gps.attr("from_to");
                    var id_saida = gps.attr("id_saida");
                    var start = gps.attr("start");
                    var forn = gps.attr("fornecedor");
                    var foto1 = gps.attr("foto1");
                    var fotom = gps.attr("fotom");

                    var id_pax = gps.attr("id_pax");

                    var id_motorista = gps.attr("id_motorista");
                    var img = gps.attr("img");
                    var statusgps = gps.attr("statusgps");
                    var p_tipo_veiculo = gps.attr("vei");
                    var icon = customIcons[p_tipo_veiculo] || {};
                    var latlng = new google.maps.LatLng(parseFloat(gps
                            .attr("lat")), parseFloat(gps.attr("longi")));
                    var html = "<b>Codigo do Servi&ccedil;o:&nbsp;" +   
    id_saida + "</b> " + id_motorista + "";
   var marker = new google.maps.Marker({
   position : latlng,
   map : map,
   title: id_saida,
   icon: icon.icon,
   labelContent: "$425K",
  // labelAnchor: new google.maps.Point(22, 0),
   labelClass: "labels", // the CSS class for the label
   labelStyle: {opacity: 0.75} ,                           
                    //shadow: icon.shadow,
                    });

                    google.maps.event.addListener(marker, 'click', 
      function() {
                            infoWindow.setContent(html);
                            infoWindow.open(map, marker);
                          });                       
                //Opa... bora guardar as referências dos markers??
                markersArray.push(marker);              
                google.maps.event.addListener(marker, "click", function()    {});
                });
        });
    }
    google.setOnLoadCallback(initialize);

  </script>
  </head>
  <div id="map_canvas" style="position: absolute; top: 10%;  left: 0%; width: 100%; height: 765px"></div>
  <div id="log"></div>                      
   </div>

1 answer

-1

function initMap() 
      {
        var directionsDisplay = new google.maps.DirectionsRenderer;
        
        /*
        --  MUDA A COR DA POLYLINE -> var directionsDisplay = new google.maps.DirectionsRenderer({ polylineOptions: { strokeColor: "blue" } });
        */
        
        var directionsService = new google.maps.DirectionsService;        
        var map = new google.maps.Map(document.getElementById('map'), {
          
          disableDefaultUI: true,
          zoom: 14,
          zoomControl: false,
          scaleControl: false,
          durationInTraffic: true,
          streetViewControl: false,
          suppressMarkers: true,

          center: {lat: -23.565, lng: -46.652} // Paulista
        });
        
        directionsDisplay.setMap(map);
        calculateAndDisplayRoute(directionsService, directionsDisplay);
        
        //var trafficLayer = new google.maps.TrafficLayer();
        //trafficLayer.setMap(map);
    
        var noPoi = [
        {
            featureType: "poi",
            stylers: [
              { visibility: "off" }
            ]   
          }
        ];
        map.setOptions({styles: noPoi});
        
      }

      function calculateAndDisplayRoute(directionsService, directionsDisplay) {
        
        directionsService.route({
          origin: {lat: -23.5711798, lng: -46.644276},  // Paulista inicia.
          destination: {lat: -23.5617981, lng: -46.6560076},  // Paulista final.
          travelMode: google.maps.DirectionsTravelMode.DRIVING
       
        },function(response, status) {
          
          if (status == google.maps.DirectionsStatus.OK) {
              directionsDisplay.setOptions({ preserveViewport: true });
              directionsDisplay.setDirections(response);
          } else {
            window.alert('Directions request failed due to ' + status);
          }
        });
      }
<head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Teste GoogleMaps API</title>
    <style>
      
      #map {
        height: 100%;
      }
      
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      
    </style>
  </head>
  <body>
 
    
    <div id="map"></div>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBsBHQ9rNhqhjJQyrCmunAFixQzR_3K8RU&callback=initMap">
    </script>
    </body>

    

Browser other questions tagged

You are not signed in. Login or sign up in order to post.