Foros del Web » Programando para Internet » Javascript » Frameworks JS »

[SOLUCIONADO] unir marcadores con google maps

Estas en el tema de unir marcadores con google maps en el foro de Frameworks JS en Foros del Web. buenas estoy intentando marcar una ruta con el google maps... en mi formulario pido que se agreguen ciudades y quiero que cada vez que se ...
  #1 (permalink)  
Antiguo 20/09/2012, 13:41
Avatar de maximendez88  
Fecha de Ingreso: septiembre-2012
Ubicación: Montevideo
Mensajes: 131
Antigüedad: 11 años, 7 meses
Puntos: 3
Pregunta unir marcadores con google maps

buenas estoy intentando marcar una ruta con el google maps... en mi formulario pido que se agreguen ciudades y quiero que cada vez que se agrega una ciudad, este unida con una linea... he logrado que cada vez que agrego una ciudad lo haga en diferentes marcadores... lo que aun no puedo lograr es que estos marcadores esten unidos con una linea... alguien puede echarme una mano?

este es mi codigo de google maps

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>

  #2 (permalink)  
Antiguo 20/09/2012, 14:31
Avatar de Naahuel  
Fecha de Ingreso: marzo-2011
Ubicación: localhost
Mensajes: 796
Antigüedad: 13 años, 1 mes
Puntos: 192
Respuesta: unir marcadores con google maps

Me tomé el trabajo de ordenar tu código y convertirlo a la versión 3 de la API. Esto es porque en la versión que utilizas no se podía usar setPath() (o al menos yo no podía). Además la v3 es más limpia y moderna. Además comenté el código para hacer bien claro qué se hace paso a paso:

Código Javascript:
Ver original
  1. //variables y objetos globales
  2. var map             //mapa
  3. var geocoder;       //geocoder
  4. var _path = [];     // ruta
  5. var _poliLinea = new google.maps.Polyline({ //polilinea
  6.     path: _path,
  7.     strokeColor: '#FF0000',
  8.     strokeOpacity: 1.0,
  9.     strokeWeight: 2
  10. });
  11.  
  12. //inicializo
  13. initialize();
  14.  
  15. //cargo un par de ciudades de ejemplo
  16. showAddress('buenos aires');
  17. showAddress('montevideo');
  18. showAddress('sao paulo');
  19.  
  20. function initialize() {
  21.     //centrado
  22.     var myLatLng = new google.maps.LatLng(37.4419, -122.1419);
  23.     //opciones
  24.     var mapOptions = {
  25.         zoom: 1,
  26.         center: myLatLng,
  27.         mapTypeId: google.maps.MapTypeId.TERRAIN
  28.     };
  29.     //geocoder
  30.     geocoder = new google.maps.Geocoder();
  31.     //creo mapa
  32.     map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
  33.    
  34.     //asigno polilinea al mapa
  35.     _poliLinea.setMap(map);
  36. }
  37.  
  38. function showAddress(s_address) {
  39.     var address = s_address;
  40.     //busco la direccion dada
  41.     geocoder.geocode( { 'address': address}, function(results, status) {
  42.       if (status == google.maps.GeocoderStatus.OK) {
  43.         //centro el mapa en el resultado
  44.         map.setCenter(results[0].geometry.location);
  45.         //creo marcador
  46.         var marker = new google.maps.Marker({
  47.             map: map,
  48.             position: results[0].geometry.location
  49.         });
  50.         //agrego punto a la linea
  51.         agregarRuta(results[0].geometry.location)
  52.       } else {
  53.         alert('Error: ' + status);
  54.       }
  55.     });
  56.  }
  57.  
  58. function agregarRuta(o_punto){
  59.     //creo punto a partir de la dirección dada
  60.     var o_LL = new google.maps.LatLng(o_punto.Xa, o_punto.Ya)
  61.     //agrego el punto al array de la ruta
  62.     _path.push(o_LL);
  63.     //cargo la nueva ruta en la polilinea
  64.     _poliLinea.setPath(_path);
  65.     //centro el mapa en el último punto
  66.     map.setCenter(o_LL);
  67.     //Hago un poco de zoom
  68.     map.setZoom(6);
  69. }

-edit-
Este es el script que tenés que incluir ahora:
Código HTML:
Ver original
  1. <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>

Acá lo ves en funcionamiento: http://jsbin.com/uzizow/1/
__________________
nahueljose.com.ar

Última edición por Naahuel; 20/09/2012 a las 14:40
  #3 (permalink)  
Antiguo 20/09/2012, 15:13
Avatar de maximendez88  
Fecha de Ingreso: septiembre-2012
Ubicación: Montevideo
Mensajes: 131
Antigüedad: 11 años, 7 meses
Puntos: 3
Respuesta: unir marcadores con google maps

muchas gracias por la respuesta... el problema es que yo no mostre el html del codigo.... en realidad lo que intento hacer es mas complejo que solo mostrar una linea ya predefinida... o sea yo voy agregando sitios en un formulario con un input y aparte de eso... tmb tengo dos inputs abajo a los cuales le cargo la latitud y la longitud... te dejo mi html completo para que lo entiendas mejor lo que quiero hacer... y con respecto a la version 3 de google maps.... he intentado actualizar pero hay algo que hago mal.... en el script que me pasaste hay que poner la apikey?? saludos


te dejo mi html completo


Código HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Trip Minded - Add Site</title>





<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) {
				document.getElementById('add').disabled=false;
              alert(address + " not found");
            } else {
							
              map.setCenter(point, 6);
              var marker = new GMarker(point, {draggable: true});
              map.addOverlay(marker);		  
			  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>
















	<link rel="stylesheet" href="colorbox.css" />
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
		<script src="http://tripminded.com/app/circuits/colorbox/jquery.colorbox.js"></script>
		<script>
			$(document).ready(function(){
				//Examples of how to assign the ColorBox event to elements
				$(".group1").colorbox({rel:'group1'});
				$(".group2").colorbox({rel:'group2', transition:"fade"});
				$(".group3").colorbox({rel:'group3', transition:"none", width:"75%", height:"75%"});
				$(".group4").colorbox({rel:'group4', slideshow:true});
				$(".ajax").colorbox();
				$(".youtube").colorbox({iframe:true, innerWidth:425, innerHeight:344});
				$(".iframe").colorbox({iframe:true, width:"80%", height:"80%"});
				$(".inline").colorbox({inline:true, width:"50%"});
				$(".callbacks").colorbox({
					onOpen:function(){ alert('onOpen: colorbox is about to open'); },
					onLoad:function(){ alert('onLoad: colorbox has started to load the targeted content'); },
					onComplete:function(){ alert('onComplete: colorbox has displayed the loaded content'); },
					onCleanup:function(){ alert('onCleanup: colorbox has begun the close process'); },
					onClosed:function(){ alert('onClosed: colorbox has completely closed'); }
				});
				
				//Example of preserving a JavaScript event for inline calls.
				$("#click").click(function(){ 
					$('#click').css({"background-color":"#f00", "color":"#fff", "cursor":"inherit"}).text("Open this window again and this message will still be here.");
					return false;
				});
			});
			
			
			
			
		
			
			
		</script>





	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>



<script language="javascript">


$(function() {
		$( "#datepicker" ).datepicker({
			changeMonth: true,
			changeYear: true,
			yearRange: "1930:2010",
			dateFormat: "yy-mm-dd"
		});
		
		
		
	});




   function activar(){
      document.getElementById('more').disabled = false;
	  document.getElementById('add').disabled=true;
	  document.getElementById('savecity').disabled=false;
    }


   function othercity(){
      document.getElementById('add').disabled = false;
	  document.getElementById('address').value="Select other city";
	  document.getElementById('more').disabled=true;
	  document.getElementById('other').disabled=true;
	  
    }
	
	
	function save(){
		document.getElementById('other').disabled=false;
		document.getElementById('savecity').disabled=true;
		document.getElementById('more').disabled=true;
	}
	
	
	
	

</script>

























</head>

  <body onLoad="initialize()" onUnload="GUnload()">





<center>



<form action="#" onSubmit="showAddress(this.address.value); return false" method="post">

<table width="800" border="1">
  <tr>
    <th width="267" scope="row">&nbsp;</th>
    <td width="225"><div align="center"><strong class="s">Add Sites for your Circuit</strong></div></td>
    <td width="286">&nbsp;</td>
  </tr>
  <tr>
    <th scope="row">&nbsp;</th>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <th scope="row">Select your Destiny:</th>
    <td><input type="text" style="width:500px" name="address" id="address" value="Select your destiny" onfocus="javascript:this.value=''"  />
      <input type="submit" value="Add Site!" onClick="activar()" id="add" /></td>
    
    <td align="center"><a class='inline' href="#inline_content" style="text-decoration:none; font-weight:bold; font-size:18px;"><input type="button" value="+" id="more" disabled="disabled"  ></a>
        
        
        
		
		<!-- This contains the hidden content for inline calls -->
		<div style='display:none'>
			<div id='inline_content' style='padding:10px; background:#fff;'>
            
            
            <center>
            
		    <table>
    
    
    <tr>
    
    <td>Arrival Date:</td>
    <td><input type="text" name="arrival" id="datepicker" readonly="readonly"></td>
    
    
    </tr>
    
    
    <tr>
    
    <td>Departure Date:</td>
    
    <td><input type="text" name="departure" id="datepicker" readonly="readonly"></td>
    
    
    </tr>
    
    
    
    <td>Adjuntar una Foto</td>
    <td><input type="file" /></td>
    
    </table>
    
    
    </center>
    
			</div>
		</div>
    
    
    
    </td>
    
    
    
  </tr>
  <tr>
    <th scope="row">&nbsp;</th>
    <td><div id="map_canvas" style="width: 600px; height: 400px"></div> </td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <th scope="row">Latitud:</th>
    <td><input type="text" id="lat" name="lat" style="width:500px;" readonly="readonly" /></td>
    <td align="center"><input type="button" value="Add another city" id="other" onClick="othercity()" disabled="disabled" /> </td>
  </tr>
  <tr>
    <th scope="row">Longitud:</th>
    <td><input type="text" id="long" name="long" style="width:500px;" readonly="readonly" /></td>
    <td align="center">&nbsp;</td>
  </tr>
  <tr>
    <th scope="row">&nbsp;</th>
    <td>&nbsp;</td>
    <td><input type="button" value="Save City"  id="savecity" onclick="save()" disabled="disabled" /></td>
  </tr>
  <tr>
    <th scope="row">&nbsp;</th>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
</table>



</form>




</center>




</body>
</html>

  #4 (permalink)  
Antiguo 20/09/2012, 15:23
Avatar de Naahuel  
Fecha de Ingreso: marzo-2011
Ubicación: localhost
Mensajes: 796
Antigüedad: 13 años, 1 mes
Puntos: 192
Respuesta: unir marcadores con google maps

Era un ejemplo... no son predefinidos. Hasta dejé el mismo nombre de la función showAddress.

Con suerte, sólo tenés que reemplazar el código nuevo y cambiar a la versión v3.

Te paso un ejemplo más elaborado. La única modificación al script que te hice anteriormente es que le saqué las llamadas a showAddress() que eran de ejemplo. Agregué un input para poner el nombre de la ciudad e ir actualizando el mapa y la línea.

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

Ahí podés ver cómo se agrega la nueva versión de google maps. No hace falta Key, es uno de los cambios de la versión 3.

Estoy 100% seguro que se puede adaptar a tu código. Perdón, pero es toda la ayuda que te puedo dar. Creo que con el código comentado que te dí no vas a tener dudas sobre cómo hacerlo.
__________________
nahueljose.com.ar
  #5 (permalink)  
Antiguo 20/09/2012, 15:28
Avatar de maximendez88  
Fecha de Ingreso: septiembre-2012
Ubicación: Montevideo
Mensajes: 131
Antigüedad: 11 años, 7 meses
Puntos: 3
Respuesta: unir marcadores con google maps

muy grosso!! loco!!! muchas gracias!!! como quiero a los argentinos!! realmente somos hermanos!
  #6 (permalink)  
Antiguo 20/09/2012, 20:21
Avatar de Naahuel  
Fecha de Ingreso: marzo-2011
Ubicación: localhost
Mensajes: 796
Antigüedad: 13 años, 1 mes
Puntos: 192
Respuesta: unir marcadores con google maps

Un placer :)
__________________
nahueljose.com.ar
  #7 (permalink)  
Antiguo 24/10/2012, 01:05
Avatar de maximendez88  
Fecha de Ingreso: septiembre-2012
Ubicación: Montevideo
Mensajes: 131
Antigüedad: 11 años, 7 meses
Puntos: 3
Respuesta: unir marcadores con google maps

amigo.. me habia servido a la perfeccion tu codigo... hasta que magicamente ahora no funciona... tenes idea de por q? saludos
  #8 (permalink)  
Antiguo 24/10/2012, 05:19
Avatar de Naahuel  
Fecha de Ingreso: marzo-2011
Ubicación: localhost
Mensajes: 796
Antigüedad: 13 años, 1 mes
Puntos: 192
Respuesta: unir marcadores con google maps

Buenas. A mi también me pareció muy extraño. Revisando el código, vi que Google había cambiado los nombres de sus objetos. Yo para obtener la Lat y Lng del punto usaba:
Código JavaScript:
Ver original
  1. o_punto.Xa, o_punto.Ya
Pero ahora esas propiedades ya no se llama más así, son Ya y Za, respectivamente. Leyendo descubrí que el error es mio por hacer referencia directamente a esas propiedades y no usar los métodos internos en su lugar. Correctamente, hay que hacer esto:
Código Javascript:
Ver original
  1. o_punto.lat(), o_punto.lng()

Cambiá eso y debería funcionar. Saludos!
__________________
nahueljose.com.ar
  #9 (permalink)  
Antiguo 24/10/2012, 06:21
Avatar de maximendez88  
Fecha de Ingreso: septiembre-2012
Ubicación: Montevideo
Mensajes: 131
Antigüedad: 11 años, 7 meses
Puntos: 3
Respuesta: unir marcadores con google maps

muchas gracias por la ayuda! la verdad casi me muero... cuando magicamente dejo de funcionar!!
  #10 (permalink)  
Antiguo 24/10/2012, 13:37
Avatar de maximendez88  
Fecha de Ingreso: septiembre-2012
Ubicación: Montevideo
Mensajes: 131
Antigüedad: 11 años, 7 meses
Puntos: 3
Respuesta: unir marcadores con google maps

tengo la pregunta del millon.... como se hace para guardar las rutas que voy creando? hay alguna forma? la necesito para mostrarla... en otra url... saludos
  #11 (permalink)  
Antiguo 24/10/2012, 14:39
txemaarbulo
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: unir marcadores con google maps

Cita:
Iniciado por maximendez88 Ver Mensaje
tengo la pregunta del millon.... como se hace para guardar las rutas que voy creando? hay alguna forma? la necesito para mostrarla... en otra url... saludos
Particularmente comenzaría por hacerme otras preguntas:
- ¿Me es útil una ruta trazada como polilínea con trazos rectos entre puntos? ¿O buscaría alternativas de rutas a pie, en coche, poder moldearlas a algo más próximo a la vida real?
- ¿Necesito otros datos alternativos?: redireccionamientos en rutas, gráficos de altitudes, ...
- ¿El usuario podrá actuar en búsqueda de rutas alternativas, prolongación de éllas desde o hacia su posición actual o hacia otras direcciones posteriores ... ?

Google maps te permite en "cómo llegar" generar rutas con puntos intermedios y guardar estos mapas para después llevarlos a tu web.

Estructurar tus propios mapas con tus rutas es trabajar con json, kml, base de datos u otro tipo de archivos y después leerlos desde tu página.

Existe abundante literatura para cada tipo de codificación.
  #12 (permalink)  
Antiguo 26/10/2012, 13:40
Avatar de maximendez88  
Fecha de Ingreso: septiembre-2012
Ubicación: Montevideo
Mensajes: 131
Antigüedad: 11 años, 7 meses
Puntos: 3
Respuesta: unir marcadores con google maps

Cita:
Iniciado por txemaarbulo Ver Mensaje
Particularmente comenzaría por hacerme otras preguntas:
- ¿Me es útil una ruta trazada como polilínea con trazos rectos entre puntos? ¿O buscaría alternativas de rutas a pie, en coche, poder moldearlas a algo más próximo a la vida real?
esa pregunta ya me la he hecho...... me gustaria mas que nada... lineas curvas en vez de lineas rectas.... pero... nunca encontre como llevarla a cabo... me gustaria tener ejemplos... practicos.... para hallarme un poco... soy nuevo en esto de google maps
  #13 (permalink)  
Antiguo 26/10/2012, 14:36
txemaarbulo
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: unir marcadores con google maps

Cita:
Iniciado por maximendez88 Ver Mensaje
... me gustaria tener ejemplos... practicos.... para hallarme un poco... soy nuevo en esto de google maps
Para ir entrando en tema puedes ver:
https://developers.google.com/maps/d...ript/reference
https://developers.google.com/maps/d...cript/examples
https://developers.google.com/maps/d...pt/demogallery

Si añades a la URL ?hl=es la tendrás en español (al estilo traductor google)

Después, por tu cuenta puedes ir probando y mezclando códigos.

Un ejemplo con rutas que me ayudó mucho cuando comenzaba fue
http://www.geocodezip.com/v3_elevati..._distance.html
Tienes cinco rutas y cuatro modos de ruta.
  #14 (permalink)  
Antiguo 06/11/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
Pregunta Respuesta: unir marcadores con google maps

Cita:
Iniciado por Naahuel Ver Mensaje
Era un ejemplo... no son predefinidos. Hasta dejé el mismo nombre de la función showAddress.

Con suerte, sólo tenés que reemplazar el código nuevo y cambiar a la versión v3.

Te paso un ejemplo más elaborado. La única modificación al script que te hice anteriormente es que le saqué las llamadas a showAddress() que eran de ejemplo. Agregué un input para poner el nombre de la ciudad e ir actualizando el mapa y la línea.

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

Ahí podés ver cómo se agrega la nueva versión de google maps. No hace falta Key, es uno de los cambios de la versión 3.

Estoy 100% seguro que se puede adaptar a tu código. Perdón, pero es toda la ayuda que te puedo dar. Creo que con el código comentado que te dí no vas a tener dudas sobre cómo hacerlo.


Como seria para que la linea que marca la ruta en vez de que sea recta... sea curva? saludos
  #15 (permalink)  
Antiguo 11/11/2012, 12:32
Avatar de Naahuel  
Fecha de Ingreso: marzo-2011
Ubicación: localhost
Mensajes: 796
Antigüedad: 13 años, 1 mes
Puntos: 192
Respuesta: unir marcadores con google maps

Tarde, pero seguro :P

Se podría usar el parámetro geodesic para las polilineas. Lo que hace es dibujar la distancia más corta tomando en cuenta la curvatura de la tierra. Sólo se notará la curvatura en distancias largas, eso si.

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

Te dejo un ejemplo de una posible solución para guardar las ubicaciones.

Código HTML:
Ver original
  1. <!DOCTYPE html>
  2. <meta charset="utf-8" />
  3.  <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
  4. <title>Test Google Maps</title>
  5. </head>
  6.     <!-- MAPA -->
  7.     <div id="map_canvas" style="width: 600px; height: 600px;"></div>
  8.     <input type="text" name="ciudad" id="ciudad" /> <button onclick="agregarCiudad();">Agregar</button>
  9.    
  10.     <!-- funcion para agregar ciudad. La separo porque es sólo ejemplo -->
  11.     <script type="text/javascript">
  12.         function agregarCiudad(){
  13.             showAddress(document.getElementById('ciudad').value);
  14.             document.getElementById('ciudad').value = '';
  15.         }
  16.     </script>
  17.    
  18.     <script type="text/javascript">
  19.     //variables y objetos globales
  20.     var map             //mapa
  21.     var geocoder;       //geocoder
  22.     var _path = [];     // ruta vacía
  23.     var _ciudades = new Array(); // ciudades que se cargaron para guardar
  24.  
  25.    
  26.     var _poliLinea = new google.maps.Polyline({ //polilinea
  27.         path: _path,
  28.         strokeColor: '#FF0000',
  29.         strokeOpacity: 1.0,
  30.         strokeWeight: 2
  31.     });
  32.  
  33.     //inicializo
  34.     initialize();
  35.  
  36.     function initialize() {
  37.         //centrado
  38.         var myLatLng = new google.maps.LatLng(37.4419, -122.1419);
  39.         //opciones
  40.         var mapOptions = {
  41.             zoom: 1,
  42.             center: myLatLng,
  43.             mapTypeId: google.maps.MapTypeId.TERRAIN
  44.         };
  45.         //geocoder
  46.         geocoder = new google.maps.Geocoder();
  47.         //creo mapa
  48.         map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
  49.        
  50.         //asigno polilinea al mapa
  51.         _poliLinea.setMap(map);
  52.  
  53.         //verifico si hay ciudades guardadas en localStorage
  54.         if(localStorage['ciudades']){
  55.             __ciudad = JSON.parse(localStorage['ciudades']);
  56.             //agrego cada ciudad que se guardó
  57.             for(i=0;i<__ciudad.length;i++){
  58.                showAddress(__ciudad[i]);
  59.            }
  60.        }
  61.  
  62.  
  63.    }
  64.  
  65.    function showAddress(s_address) {
  66.        var address = s_address;
  67.        //busco la direccion dada
  68.        geocoder.geocode( { 'address': address}, function(results, status) {
  69.          if (status == google.maps.GeocoderStatus.OK) {
  70.            //centro el mapa en el resultado
  71.            map.setCenter(results[0].geometry.location);
  72.            //creo marcador
  73.            var marker = new google.maps.Marker({
  74.                map: map,
  75.                position: results[0].geometry.location
  76.            });
  77.            //agrego punto a la linea
  78.            agregarRuta(results[0].geometry.location)
  79.            
  80.            //guardo la ciudad en LocalStorage
  81.            _ciudades.push(results[0].formatted_address);
  82.            localStorage['ciudades'] = JSON.stringify(_ciudades);
  83.  
  84.          } else {
  85.            alert('Error: ' + status);
  86.          }
  87.        });
  88.     }
  89.    
  90.    function agregarRuta(o_punto){
  91.  
  92.        //creo punto a partir de la dirección dada
  93.        var o_LL = new google.maps.LatLng(o_punto.lat(), o_punto.lng())
  94.        //agrego el punto al array de la ruta
  95.        _path.push(o_LL);
  96.        //cargo la nueva ruta en la polilinea
  97.        _poliLinea.setPath(_path);
  98.        //centro el mapa en el último punto
  99.        map.setCenter(o_LL);
  100.        //Hago un poco de zoom
  101.        map.setZoom(6);
  102.    }
  103.  
  104.    </script>
  105. </body>
  106. </html>

Digo posible porque estoy usando una nueva funcionalidad llamada localStorage y JSON.parse() y JSON.stringify(). La primera permite almacenar contenido desde JavaScript en el navegador, el cual estará disponible después cuando yo lo necesite. Su soporte es relativamente bueno: http://www.html5rocks.com/en/features/storage

Si te fijás en el ejemplo, podés encontrar las líneas que guardan y que restauran lo que se guardo cuando se entre una segunda vez.

La otra opción podría ser usar cookies, pero eso requeriría también usar AJAX para guardar cada ciudad que se agregue en la cookie. Luego, al cargar la página, verificar si existe la cookie y cargar las ciudades que se guardaron.
__________________
nahueljose.com.ar
  #17 (permalink)  
Antiguo 26/11/2012, 18:44
Avatar de Naahuel  
Fecha de Ingreso: marzo-2011
Ubicación: localhost
Mensajes: 796
Antigüedad: 13 años, 1 mes
Puntos: 192
Respuesta: unir marcadores con google maps

Me olvidé de mencionar, que para que el ejemplo funcione con localStorage en IE (8+) este debe estar ejecutándose en un servidor.
__________________
nahueljose.com.ar
  #18 (permalink)  
Antiguo 27/11/2012, 10:38
Avatar de maximendez88  
Fecha de Ingreso: septiembre-2012
Ubicación: Montevideo
Mensajes: 131
Antigüedad: 11 años, 7 meses
Puntos: 3
Respuesta: unir marcadores con google maps

excelente!!! gracias por la respuesta voy a probar a usar lo que me enseñaste... a ver como me va...
  #19 (permalink)  
Antiguo 05/12/2012, 10:20
Avatar de maximendez88  
Fecha de Ingreso: septiembre-2012
Ubicación: Montevideo
Mensajes: 131
Antigüedad: 11 años, 7 meses
Puntos: 3
Sonrisa Respuesta: unir marcadores con google maps

Código HTML:
Ver original
  1. <!DOCTYPE html>
  2. <meta charset="utf-8" />
  3.  <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
  4. <title>Test Google Maps</title>
  5. </head>
  6.     <!-- MAPA -->
  7.     <div id="map_canvas" style="width: 600px; height: 600px;"></div>
  8.     <input type="text" name="ciudad" id="ciudad" /> <button onclick="agregarCiudad();">Agregar</button>
  9.    
  10.     <!-- funcion para agregar ciudad. La separo porque es sólo ejemplo -->
  11.     <script type="text/javascript">
  12.         function agregarCiudad(){
  13.             showAddress(document.getElementById('ciudad').value);
  14.             document.getElementById('ciudad').value = '';
  15.         }
  16.     </script>
  17.    
  18.     <script type="text/javascript">
  19.     //variables y objetos globales
  20.     var map             //mapa
  21.     var geocoder;       //geocoder
  22.     var _path = [];     // ruta vacía
  23.     var _ciudades = new Array(); // ciudades que se cargaron para guardar
  24.  
  25.    
  26.     var _poliLinea = new google.maps.Polyline({ //polilinea
  27.         path: _path,
  28.         strokeColor: '#FF0000',
  29.         strokeOpacity: 1.0,
  30.         strokeWeight: 2
  31.     });
  32.  
  33.     //inicializo
  34.     initialize();
  35.  
  36.     function initialize() {
  37.         //centrado
  38.         var myLatLng = new google.maps.LatLng(37.4419, -122.1419);
  39.         //opciones
  40.         var mapOptions = {
  41.             zoom: 1,
  42.             center: myLatLng,
  43.             mapTypeId: google.maps.MapTypeId.TERRAIN
  44.         };
  45.         //geocoder
  46.         geocoder = new google.maps.Geocoder();
  47.         //creo mapa
  48.         map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
  49.        
  50.         //asigno polilinea al mapa
  51.         _poliLinea.setMap(map);
  52.  
  53.         //verifico si hay ciudades guardadas en localStorage
  54.         if(localStorage['ciudades']){
  55.             __ciudad = JSON.parse(localStorage['ciudades']);
  56.             //agrego cada ciudad que se guardó
  57.             for(i=0;i<__ciudad.length;i++){
  58.                showAddress(__ciudad[i]);
  59.            }
  60.        }
  61.  
  62.  
  63.    }
  64.  
  65.    function showAddress(s_address) {
  66.        var address = s_address;
  67.        //busco la direccion dada
  68.        geocoder.geocode( { 'address': address}, function(results, status) {
  69.          if (status == google.maps.GeocoderStatus.OK) {
  70.            //centro el mapa en el resultado
  71.            map.setCenter(results[0].geometry.location);
  72.            //creo marcador
  73.            var marker = new google.maps.Marker({
  74.                map: map,
  75.                position: results[0].geometry.location
  76.            });
  77.            //agrego punto a la linea
  78.            agregarRuta(results[0].geometry.location)
  79.            
  80.            //guardo la ciudad en LocalStorage
  81.            _ciudades.push(results[0].formatted_address);
  82.            localStorage['ciudades'] = JSON.stringify(_ciudades);
  83.  
  84.          } else {
  85.            alert('Error: ' + status);
  86.          }
  87.        });
  88.     }
  89.    
  90.    function agregarRuta(o_punto){
  91.  
  92.        //creo punto a partir de la dirección dada
  93.        var o_LL = new google.maps.LatLng(o_punto.lat(), o_punto.lng())
  94.        //agrego el punto al array de la ruta
  95.        _path.push(o_LL);
  96.        //cargo la nueva ruta en la polilinea
  97.        _poliLinea.setPath(_path);
  98.        //centro el mapa en el último punto
  99.        map.setCenter(o_LL);
  100.        //Hago un poco de zoom
  101.        map.setZoom(6);
  102.    }
  103.  
  104.    </script>
  105. </body>
  106. </html>

bueno, he estado utilizando el código que me pasaste...localmente me funciono, solo que cuando lo pruebo en mi servidor no funciona... cada vez que actualizo el navegador pierdo la ruta que fui marcando...
  #20 (permalink)  
Antiguo 08/12/2012, 06:40
Avatar de Naahuel  
Fecha de Ingreso: marzo-2011
Ubicación: localhost
Mensajes: 796
Antigüedad: 13 años, 1 mes
Puntos: 192
Respuesta: unir marcadores con google maps

A mi me funciona perfecto en el servidor:
http://nahueljose.com.ar/ejemplos/go...ne/index2.html
__________________
nahueljose.com.ar
  #21 (permalink)  
Antiguo 14/12/2012, 12:01
Avatar de maximendez88  
Fecha de Ingreso: septiembre-2012
Ubicación: Montevideo
Mensajes: 131
Antigüedad: 11 años, 7 meses
Puntos: 3
De acuerdo Respuesta: unir marcadores con google maps

al final lo logre!!! muchas gracias por tu tiempo y por tu ayuda excelente!!

:a rriba:

Última edición por maximendez88; 14/12/2012 a las 13:26

Etiquetas: formulario, google, javascript, maps, marcadores
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.
Respuesta




La zona horaria es GMT -6. Ahora son las 19:18.