Foros del Web » Programando para Internet » Javascript »

Dibujar ruta para varios marcadores en Google Maps.

Estas en el tema de Dibujar ruta para varios marcadores en Google Maps. en el foro de Javascript en Foros del Web. Hola! Estoy haciendo un proyecto de la carrera y me encuentro con un problemilla que no sé resolver. Quiero sacar en un mapa varios marcadores ...
  #1 (permalink)  
Antiguo 11/08/2012, 04:58
 
Fecha de Ingreso: abril-2008
Mensajes: 20
Antigüedad: 16 años
Puntos: 0
Dibujar ruta para varios marcadores en Google Maps.

Hola!

Estoy haciendo un proyecto de la carrera y me encuentro con un problemilla que no sé resolver.

Quiero sacar en un mapa varios marcadores cuyas coordenadas tengo almacenadas en una base de datos, obtengo mediante la generación de un xml y voy sacando por javascript usando la API de Google Maps v3.

La parte javascript es algo como esto:

Código:
 var customIcons = {
     ....
    };

    function load() {
      var map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(37.176487, -3.597929),
        zoom: 13,
        mapTypeId: 'roadmap'
      });
      var infoWindow = new google.maps.InfoWindow;

      downloadUrl("genXML.php?id="+id, function(data) {
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName("marker");
        for (var i = 0; i < markers.length; i++) {
          var name = markers[i].getAttribute("name");
          var type = markers[i].getAttribute("type");
          var point = new google.maps.LatLng(
              parseFloat(markers[i].getAttribute("lat")),
              parseFloat(markers[i].getAttribute("lon")));
          var html = "<b>" + name + "</b> <br/>";
          var icon = customIcons[type] || {};
          var marker = new google.maps.Marker({
            map: map,
            position: point,
            icon: icon.icon,
            shadow: icon.shadow
          });
	  bindInfoWindow(marker, map, infoWindow, html);
        }
      });
    }

    function bindInfoWindow(marker, map, infoWindow, html) {
      google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(map, marker);
      });
    }

    function downloadUrl(url, callback) {
      var request = window.ActiveXObject ?
          new ActiveXObject('Microsoft.XMLHTTP') :
          new XMLHttpRequest;

      request.onreadystatechange = function() {
        if (request.readyState == 4) {
          request.onreadystatechange = doNothing;
          callback(request, request.status);
        }
      };

      request.open('GET', url, true);
      request.send(null);
    }

    function doNothing() {}
Esto me da como resultado mostrar en el mapa todos los marcadores correspondientes.

Ahora bien, lo que necesito, es unir esos marcadores de manera que tuviese una RUTA, he probado con el método polyline pero no me hago con él.

Alguien me puede ayudar?

Gracias!!!
  #2 (permalink)  
Antiguo 20/09/2012, 13:47
Avatar de maximendez88  
Fecha de Ingreso: septiembre-2012
Ubicación: Montevideo
Mensajes: 131
Antigüedad: 11 años, 7 meses
Puntos: 3
Sonrisa Respuesta: Dibujar ruta para varios marcadores en Google Maps.

tengo el mismo problema que tu.... logro insertar varios marcadores, pero lo que aun no puedo lograr es que estos esten unidos con una linea.... si llegas a saber de alguna solucion... espero que me avises.... dejo mi codigo de google maps por las dudas... que alguien se apiade de nuestras almas....


Código HTML:

    <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=AIzaSyA07VHJApYzXc3uJgFEk4l04KaSABLyaVA"
      type="text/javascript"></script>
    <script type="text/javascript">

    var map = null;
    var geocoder = null;
	
    function initialize() {
      if (GBrowserIsCompatible()) {
		  
        map = new GMap2(document.getElementById("map_canvas"));
        map.setCenter(new GLatLng(37.4419, -122.1419), 1);
		map.setMapType(G_HYBRID_MAP);
        map.setUIToDefault();
        geocoder = new GClientGeocoder();
      }
    }
	
	

    function showAddress(address) {
      if (geocoder) {
        geocoder.getLatLng(
          address,
          function(point) {
            if (!point) {
              alert(address + " not found");
            } else {
				
				
				
              map.setCenter(point, 6);
              var marker = new GMarker(point, {draggable: true});
              map.addOverlay(marker);
			  
			  
			  map.addOverlay(polyline);
			  
			  
			  
              
			  
			  
			  GEvent.addListener(marker, "dragend", function() {
                
				 document.getElementById('lat').value=marker.getPoint().lat();
                 document.getElementById('long').value=marker.getPoint().lng();
              });
              GEvent.addListener(marker, "click", function() {
                
				 document.getElementById('lat').value=marker.getPoint().lat();
                 document.getElementById('long').value=marker.getPoint().lng();
              });
			  
			  
			  
			  
	      GEvent.trigger(marker, "click");
            }
          }
        );
      }
    }
	
	
	
	
 

	
    </script>


  #3 (permalink)  
Antiguo 19/11/2012, 13:52
Avatar de maximendez88  
Fecha de Ingreso: septiembre-2012
Ubicación: Montevideo
Mensajes: 131
Antigüedad: 11 años, 7 meses
Puntos: 3
Respuesta: Dibujar ruta para varios marcadores en Google Maps.

te dejo un ejemplo que me pasaron que fue muy util... por las dudas que aun sigas con el mismo problema


Código HTML:
Ver original
  1. <meta charset="utf-8" />
  2.  <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
  3. <title>Test Google Maps</title>
  4. </head>
  5.     <!-- MAPA -->
  6.     <div id="map_canvas" style="width: 600px; height: 600px;"></div>
  7.     <input type="text" name="ciudad" id="ciudad" /> <button onclick="agregarCiudad();">Agregar</button>
  8.    
  9.     <!-- funcion para agregar ciudad. La separo porque es sólo ejemplo -->
  10.     <script type="text/javascript">
  11.         function agregarCiudad(){
  12.             showAddress(document.getElementById('ciudad').value);
  13.             document.getElementById('ciudad').value = '';
  14.         }
  15.     </script>
  16.    
  17.     <script type="text/javascript">
  18.     //variables y objetos globales
  19.     var map             //mapa
  20.     var geocoder;       //geocoder
  21.     var _path = [];     // ruta
  22.     var _poliLinea = new google.maps.Polyline({ //polilinea
  23.         path: _path,
  24.         strokeColor: '#FF0000',
  25.         strokeOpacity: 1.0,
  26.         strokeWeight: 2
  27.     });
  28.  
  29.     //inicializo
  30.     initialize();
  31.  
  32.     function initialize() {
  33.         //centrado
  34.         var myLatLng = new google.maps.LatLng(37.4419, -122.1419);
  35.         //opciones
  36.         var mapOptions = {
  37.             zoom: 1,
  38.             center: myLatLng,
  39.             mapTypeId: google.maps.MapTypeId.TERRAIN
  40.         };
  41.         //geocoder
  42.         geocoder = new google.maps.Geocoder();
  43.         //creo mapa
  44.         map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
  45.        
  46.         //asigno polilinea al mapa
  47.         _poliLinea.setMap(map);
  48.     }
  49.  
  50.     function showAddress(s_address) {
  51.         var address = s_address;
  52.         //busco la direccion dada
  53.         geocoder.geocode( { 'address': address}, function(results, status) {
  54.           if (status == google.maps.GeocoderStatus.OK) {
  55.             //centro el mapa en el resultado
  56.             map.setCenter(results[0].geometry.location);
  57.             //creo marcador
  58.             var marker = new google.maps.Marker({
  59.                 map: map,
  60.                 position: results[0].geometry.location
  61.             });
  62.             //agrego punto a la linea
  63.             agregarRuta(results[0].geometry.location)
  64.           } else {
  65.             alert('Error: ' + status);
  66.           }
  67.         });
  68.      }
  69.      
  70.     function agregarRuta(o_punto){
  71.         //creo punto a partir de la dirección dada
  72.         var o_LL = new google.maps.LatLng(o_punto.Xa, o_punto.Ya)
  73.         //agrego el punto al array de la ruta
  74.         _path.push(o_LL);
  75.         //cargo la nueva ruta en la polilinea
  76.         _poliLinea.setPath(_path);
  77.         //centro el mapa en el último punto
  78.         map.setCenter(o_LL);
  79.         //Hago un poco de zoom
  80.         map.setZoom(6);
  81.     }
  82.     </script>
  83. </body>
  84. </html>
  #4 (permalink)  
Antiguo 22/01/2014, 09:54
 
Fecha de Ingreso: enero-2014
Ubicación: Barcelona
Mensajes: 2
Antigüedad: 10 años, 3 meses
Puntos: 0
Respuesta: Dibujar ruta para varios marcadores en Google Maps.

Busco hacer lo mismo me podríais informar de como la habéis echo .
Muchas gracias

Etiquetas: dibujar, google, html, marcadores, php, ruta
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Tema Cerrado




La zona horaria es GMT -6. Ahora son las 21:43.