Nueva pregunta

Pregunta:

Fecha: 14-03-2015 12:58:08 (En Español)

Google maps ... trazar un recorrido entre vario puntos de una traza[Resuelta]

SOS

Tengo este script que dejo a continuación:
En el se ingresan 2 direcciones y se obtiene como resultado toda la información del recorrido.
Ahora bien, he leído en la api de Google maps que uno puede trazar las distintas paradas que pudiera tener en el mismo ...
Ejemplo tramo 1, tramo 2, tramo 3, tramo etc ... de un solo recorrido.
Eso no lo logre, solo se como determinar el trazo del recorrido y la información de un punto 1 a otro punto 2 ...
¿ Alguien que tenga alguna data como ayuda?

Demo: http://www.auditordigital.com.ar/tbd/tbd_ruta_vs2.php

Script
(Esta editado algo desprolijo, espero sepana disculparme)

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"  xmlns:v="urn:schemas-microsoft-com:vml">
  <head>
   <META HTTP-EQUIV="Content-Type" CONTENT="text/html;charset=ISO-8859-1">
    <link href='../img/web.png' rel='shortcut icon' type='image/png'>	
    <title>Calofatti & Asoc - Rutas</title>
    

     <link rel="stylesheet" type="text/css" href="../css/consultas.css">
		<script src=" http://maps.google.com/?file=api&amp;v=2.x&amp;key=ABQIAAAAUnJY3ChJhF0YgyTSDJuVfBTqu-zEVMNfNVaqfAe9FKyfKhfBExSs9LrIQ7GOuBeSnaddg05sRmEBxQ"
          type="text/javascript"></script>
        <script type="text/javascript">
     
        var map;
        var gdir;
        var geocoder = null;
        function load() {
            if (GBrowserIsCompatible()) {
                map = new GMap2(document.getElementById("map"));	
                gdir = new GDirections(map, document.getElementById("direcciones"));
                GEvent.addListener(gdir, "load", onGDirectionsLoad);
                GEvent.addListener(gdir, "error", mostrarError);	
                obtenerRuta("Av. Callao 322, Argentina", "Av. Callao 322, Argentina");	
            }
        }
            
        function obtenerRuta(desde, hasta) {
            var i;
            var tipo;
            //comprobar tipo trayecto seleccionado
            for (i=0;i<document.form_ruta.tipo.length;i++){ 
                if (document.form_ruta.tipo[i].checked){
                    break; 
                }
            } 
            tipo = document.form_ruta.tipo[i].value;
            if(tipo==1){
                //a pie
                gdir.load("from: " + desde + " to: " + hasta,
                    { "locale": "ar", "travelMode" : G_TRAVEL_MODE_WALKING });
            }else{
                //conduccion
                gdir.load("from: " + desde + " to: " + hasta,
                    { "locale": "ar", "travelMode" : G_TRAVEL_MODE_DRIVING });
            }
        }
        
        function onGDirectionsLoad(){ 
            //resumen de tiempo y distancia
            document.getElementById("getDistance").innerHTML =gdir.getSummaryHtml(); 
        } 
        
        function mostrarError(){
            if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
                alert("No se ha encontrado una ubicación geográfica que se corresponda con la dirección especificada.");
            else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
                alert("No se ha podido procesar correctamente la solicitud de ruta o de códigos geográficos, sin saberse el motivo exacto del fallo.");
            else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
                alert("Falta el parámetro HTTP q o no tiene valor alguno. En las solicitudes de códigos geográficos, esto significa que se ha especificado una dirección vacía.");
            else if (gdir.getStatus().code == G_GEO_BAD_KEY)
                alert("La clave proporcionada no es válida o no coincide con el dominio para el cual se ha indicado.");
            else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
                alert("No se ha podido analizar correctamente la solicitud de ruta.");
            else alert("Error desconocido.");
           
        }
        </script>
        
        <script type="text/javascript">
         function mostrar(){
         document.getElementById('oculto').style.display = 'block';}
         </script>    

		<style>
        div.centerTable{
                text-align: center;
        }
        
         
        
        div.centerTable table {
               margin:auto;
               text-align: left;
        }
        
        </style>

  </head>
  <body >
  
    <div id="contenedor" style="width:940px; height:100px; "> 
    
        <div style="width:940px; margin:auto; margin-top:20;"> 
     
         <br><p>Recorrido - Origen - Destino</p><br>
            <form action="#" name="form_ruta" onsubmit="obtenerRuta(this.desde.value, this.hasta.value); return false">
            
                <div>
                <label>Desde: </label><input type="text" class="input"  size="25" id="desde" name="desde" value="Domicilio, Argentina" style="width: 355px; padding-left:5px;"/>
                <label>Hasta: </label><input type="text" class="input"  size="25" id="hasta" name="hasta" value="Domicilio, Argentina" style="width: 355px; padding-left:5px;" /> 
                <input type="radio" name="tipo" id="tipo" value="2" checked style="visibility:hidden;"> 
                <input type="radio" name="tipo" id="tipo" value="1" style="visibility:hidden;"> 
                <input name="ruta" class="button" type="submit" value="Ver Recorrido" onclick="mostrar()"/>
                
                </div>
            
            <br>
            <hr style="border:solid 1px #99CCFF; background-color:#99CCFF;">
            
            </form>

        <div id='oculto' style='display:none; '><br>
    
    <div style=" border:solid 1px #99CCFF; border-radius:10px; padding:5px;" >


			Distancia y tiempo:<br>
           <a style="font-size:8px;">(El recorrido en el mapa es solamente sugerido)</a>
	</div>	   
        <div id="">

            <div id="direcciones" style="width: 450px; float:left;  margin:10px 0px 0px 0px; border:solid 1px #99CCFF; border-radius:10px; padding:5px;"></div>

            <div id="map" style="width: 455px; height: 400px; float:left; margin:10px 0px 0px 20px; border:solid 1px #99CCFF; border-radius:10px; "></div>

       </div>

	</body>
</html>
<script>
	window.onload=load;
	window.onunload=GUnload;
</script>
</div>
Etiquetas: Google API - Google Maps - Maps - Pregunta Votos: 1 - Respuestas: 15 - Vistas: 33 Compartir en: Google Facebook Twitter LinkedIn Link
 

Respuestas:

  • Fecha: 15-03-2015 06:23:02 Hola Daniel, te pido si podes rever tu pregunta y ajustarla ya que tiene algunos problemas (podes editar tu pregunta haciendo click en el botón editar que esta al final de la misma).

    Por otro lado, te pido que leas este post:
    ¿Cómo cargar correctamente una nueva pregunta?

    Algunos detalles a mejorar:
    * Pregunta: no se entiende muy bien lo que preguntas, tal vez sea más comprensible: ¿Cómo trazar un recorrido con la API de Google Maps?
    * Código compartido: utilizanda las etiqueta BBCode.
    * Links/enlaces compartidos: utilizanda las etiqueta BBCode

    Muchas gracias.

    Saludos,
    Fernando
      Votos: 0 - Link respuesta
     
  • Fecha: 15-03-2015 06:50:46 Fernando, la respuesta de Txema, es correcta, la interpreto perfectamente, el envia 3 linck, lo que deseo hacer es como el lo expone en el 3ro de ellos.
    Por otra parte, espero que alla quedado editado bien mi script - Gracias por la demo

    2 Puntos Texema

    a) Trato de buscar quien me ayude con un script como el que publique pero con la API 3 y bajo las caracteristicas de la pagina que publicas como tu cosecha
    b) El ejemplo que planteas como cosecha propia, en varios lugar esta denunciado como virus, dado que cuesta eliminar de los navedadores (Mapasgalaxy) link http://www.mapsgalaxy.com/index.jhtml?spu=true&partner=UXxdm779&gclid=CPCcopnaqsQCFUojgQodzVEAew
      Votos: 1 - Link respuesta
     
  • Fecha: 15-03-2015 07:28:28 Hola Daniel, si, ahora quedo mucho más legible tu script, pero fijate que para poner los links también tenes una etiqueta BBCode "Link", lo que tienes que hacer es pintar el texto a convertir en un link, luego apretar el botón BBCode "Link" y completar en el popup la dirección del enlace (o sino, colocas cursor donde quieres incrustar el enlace, luego haces click en el botón BBCode "Link" y te va a pedir la dirección http y el texto del enlace, es otra forma de hacer lo mismo) <-- con esto tus enlaces serán clicleables dentro de tu pregunta/respuesta.

    Con respecto a la pregunta, no digo que este mal, solo me hace un poco de ruido que diga "recorrido recorrido". También hay que tener presente que las preguntas son enviadas vía email en un newsletter semanal, y solo se envía el titulo de la pregunta, por lo que tal vez sea mas claro algo como ¿Cómo trazar un recorrido con la API 3 de Google Maps? <-- fijate que ahí ya el titulo te da mucha más info.

    Muchas gracias de antemano por tu colaboración para ajustar la pregunta y ayudar a que la comunidad sea cada día más profesional.

    Saludos,
    Fernando
      Votos: 0 - Link respuesta
     
  • Fecha: 15-03-2015 12:22:24 Txema:

    Antes que nada, muchas gracias por el aporte y tu tiempo.
    He intentado con la API de Google maps y con el material que me pasaste armar este script que espongo a continuacion, pero no funciona, tengo un error y NO LO HE DETECTADO.
    Te solicito si podes revisarlo ... en agosto voy para españa, decime de donde sos y te llevo el Dom Perignon (Si me convidas una copa) ... Je

    Demo: http://www.auditordigital.com.ar/tbd/tbd_ruta_vs999.php?origen=Domicilio%2C+Argentina&detino=Domicilio%2C+Argentina&tipo=2&ruta=Ver+Recorrido#

    <!DOCTYPE html>
    <html>
      <head>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
        <meta charset="utf-8">
          <meta name="robots" content="noindex,nofollow">
        <title>Draggable directions</title>
     <link rel="stylesheet" type="text/css" href="../css/consultas.css"> 
        <style>
          html, body, #map-canvas {
            
    		width:85%;
    		height: 90%;
            margin: auto;
            padding: 0px
          }
        </style>
        <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
        <script>
    
    var rendererOptions = {
      draggable: false
    };
    
    var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);;
    var directionsService = new google.maps.DirectionsService();
    var map;
    
    var ba = new google.maps.LatLng(-34.796607,-58.466545);
    
    function initialize() {
    
      var mapOptions = {
        zoom: 6,
        center: ba
      };
      map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
      directionsDisplay.setMap(map);
      directionsDisplay.setPanel(document.getElementById('directionsPanel'));
    
      google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
        computeTotalDistance(directionsDisplay.getDirections());
      });
    
      calcRoute();
    }
    
    ////////////////////////////////////////////////////    
    
    
    // añadir y eliminar puntos intermedios
    function getPoints() {
        var waypts = new Array();
        var pointChildrens = document.getElementById("AllPoints").children;
        for (var i = 0; i < pointChildrens.length; i++) {
            var pointText = pointChildrens[i].children[0].value;
            if (pointText.trim() != '') {
                waypts.push({
                    location: pointText,
                    stopover: true
                });
            }
        }
        return waypts;
    };
    var totalPoints = 0;
    
    function AddNewPoint() {
        totalPoints = totalPoints + 1;
        var pointElem = document.getElementById('Waypoint');
        if (totalPoints == 1) {
            pointElem.style.display = 'block';
        } else {
            // btnAddWaypoint.innerHTML = "Nuevo punto";
            var divAllPoints = document.getElementById('AllPoints');
            var nextPoint = pointElem.cloneNode(true);
            // nextPoint.children[0].textContent = "Nuevo punto:";
            nextPoint.children[0].value = "";
            divAllPoints.appendChild(nextPoint);
        }
    };
    
    function DeletePoint(control) {
        totalPoints = totalPoints - 1;
        var divToDelete = control.parentNode;
        var divAllPoints = document.getElementById('AllPoints');
        if (totalPoints == 0) {
            divToDelete.style.display = 'none';
        } else {
            divAllPoints.removeChild(divToDelete);
        }
    };
    
    
    ////////////////////////////////////////////////////////////
    
    function calcRoute() {
    
      var request = {
          origin: start,
          destination: end,	  
        waypoints:[{location: 'Bourke, NSW'}, {location: 'Broken Hill, NSW'}],
        travelMode: google.maps.TravelMode.DRIVING
      };
      directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          directionsDisplay.setDirections(response);
        }
      });
    }
    
    function computeTotalDistance(result) {
      var total = 0;
      var myroute = result.routes[0];
      for (var i = 0; i < myroute.legs.length; i++) {
        total += myroute.legs[i].distance.value;
      }
      total = total / 1000.0;
      document.getElementById('total').innerHTML = total + ' km';
    }
    
    google.maps.event.addDomListener(window, 'load', initialize);
    
      
     function calcRuta() {
        var waypts = new Array();
        var pointsArray = document.getElementsByName('points');
        for (var i = 0; i < pointsArray.length; i++) {
            if (pointsArray[i].value != '') {
                waypts.push({
                    location: pointsArray[i].value,
                    stopover: true
                });
            }
        }
        var modo;  // todo lo descrito en modo es para tomar la elección de modo de ruta
        if (document.getElementById('driving').checked) {
            modo = google.maps.DirectionsTravelMode.DRIVING;
        } else if (document.getElementById('bicycling').checked) {
            modo = google.maps.DirectionsTravelMode.BICYCLING;
        } else if (document.getElementById('transit').checked) {
            modo = google.maps.DirectionsTravelMode.TRANSIT;
        } else if (document.getElementById('walking').checked) {
            modo = google.maps.DirectionsTravelMode.WALKING;
        } else {
            alert('Escoja un modo de ruta');
        }
        var request = {
            origin: document.getElementById("origen").value,
            destination: document.getElementById("destino").value,
            waypoints: waypts,  // aquí van los puntos intermedios generados
            travelMode: modo, // el modo de ruta elegido
            unitSystem: google.maps.UnitSystem.METRIC,  // traducirá la distancia a Kilómetros, 
            optimizeWaypoints: $("#optWaypoints").is(":checked"),  // optimiza la ruta si está chequeado
            provideRouteAlternatives: true,  // muestra automáticamente rutas alternativas
            avoidHighways: document.getElementById('autopista').checked,  // evita autopistas
            avoidTolls: document.getElementById('peaje').checked  // evita peajes
        };
        directionsService.route(request, function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setMap(map);
                directionsDisplay.setPanel(document.getElementById('direcciones'));
                directionsDisplay.setDirections(response);
            } else {
                alert("No existen rutas entre ambos puntos");
            }
        });
    }
    
        </script>    
    
      </head>
      <body>
      
             <div style="width:940px; margin:auto; margin-top:20;"> 
    
    <div Style="border:solid 1px #CCCCCC; border-radius:10px ; width:840px;height 300px font-family:arial; font-size:10px; margin:10px 0px 0px 20px;"><br>
          <div Style="family:arial; font-size:10px; margin:0px 0px 0px 10px;">      
          <label>Desde: <input type="text" size="20" id="stard" name="origen" value="" style="width: 355px; padding-left:5px;" ><label>
          <label>Hasta: <input type="text" size="20" id="end" name="destino" value="" style="width: 355px; padding-left:5px;"><label><br><br>       
          <div id="AllPoints">
            <div id="Waypoint" style="display:none">
              <input type="text" name="points" size="24" placeholder="Ciudad ..." onfocus="autocompletar()" style="width: 355px; padding-left:5px;"/>
              <button onclick="DeletePoint(this)">X</button>
            </div>
          </div>
    
           <button class="button" id="btnAddWaypoint" onclick="AddNewPoint()">Ingresar Paradas Intermedias</button>
          <br>
          <br> Opciones de ruta
          <input type="radio" name="travelMode" id="driving" value="DRIVING" checked onchange="calcRuta();">
          <label for="driving"><span></span> </label>
          <input type="radio" name="travelMode" id="bicycling" value="BICYCLING" onchange="calcRuta();">
          <label for="bicycling"><span></span> </label>
          <input type="radio" name="travelMode" id="transit" value="TRANSIT" onchange="calcRuta();">
          <label for="transit"><span></span> </label>
          <input type="radio" name="travelMode" id="walking" value="WALKING" onchange="calcRuta();">
          <label for="walking"><span></span> </label>
          <br>
          <input type="checkbox" id="trafico" onclick="estadotrafico();">
          <label for="trafico"><span></span> </label> Ver estado del tráfico
          <br>
          <input type="checkbox" id="autopista" onchange="calcRuta();">
          <label for="autopista"><span></span> Evitar autovías</label>
          <br>
          <input type="checkbox" id="peaje" onchange="calcRuta();">
          <label for="peaje"><span></span> Evitar peajes</label>
          <br>
          <input type="checkbox" name="optRuta" id="optWaypoints" onchange="calcRuta();">
          <label for="optWaypoints"><span></span> Optimizar etapas de ruta</label>
          <br>
          <input type="checkbox" name="nubes" id="nubes" value="nubes" onchange="meteo();">
          <label for="nubes"><span></span> Habilitar capa Nubes (Zoom 0-6)</label>
          <br>
          <input type="checkbox" name="temp" id="temp" value="temp" onchange="meteo();" />
          <label for="temp"><span></span> Temperaturas (Weather.com) (Zoom 0-12)</label>
          <br><br>
          <input type="button" class="button" onclick="reset();" value="Limpiar registros">
          <input type="button" class="button" onclick="calcRuta();" value="Ruta"> <br><br>
      </div>
      </div> 
    
      <div style="clear:both;"></div>
        
        <div id="map-canvas" style="width: 455px; height: 400px; float:left; margin:10px 0px 0px 20px; border:solid 1px #99CCFF; border-radius:10px; "></div>
        <div id="directionsPanel" style="float:right;width:30%;height 100%">
        <p>Total Distancia: <span id="total"></span></p>  
      
         </div>
    
    </body>
    </html>
      Votos: 0 - Link respuesta
     
  • Fecha: 15-03-2015 15:08:07 Txema:
    Seguire probando ...
    En el trabajo que estoy haciendo es muy importante lo que lograste con respecto a lo puntos intermedios, dado a que hago un trabajo para una empresa que de logistica y generalmente en los recorridos pueden hacer hasta 6 o 7 paradas intermedias.
    Lei en la AIP de Google Maps que soporta 8 puntos mas el de inicio y destino final (Es decir 10 puntos en un solo recorrido), si te pasas a bussimes llegas hasta 23.
    Mi proyecto es mas cercano la trabajo que me enviaste la primera vez ya que ese si cuenta con las paradas intermedias (Asi te lo presente en mi ultima demo fallida - ver linck anterior).
    Un saludo y muchas gracias.
      Votos: 1 - Link respuesta
     
  • Fecha: 15-03-2015 15:38:51 Excelente ...   Votos: 0 - Link respuesta
     
  • Fecha: 15-03-2015 20:15:24 Txema:
    Alguna vez oiste ese dicho que dice asi:
    "El burro no coje por lindo, sino por insistidor"
    Bueno, suelo utilizar esa practicas en programacion ...
    Me falta pulir el css, pero el script ya esta funcionando, seguramente posteriormente te moleste con alguna pregunat mas, pero aqui esta la criatura, ya camina ...

    <!DOCTYPE html>
    <html lang="es-ES">
    
    <head>
      <meta charset="utf-8">
      <meta name="robots" content="noindex,nofollow">
    
    
      <title>Crear rutas</title>
    
     <link rel="stylesheet" type="text/css" href="../css/consultas.css"> 
        <style>
          html, body, #map-canvas {
            
    		width:100%;
    		height: 100%;
            margin: auto;
            padding: 0px
          }
        </style>
    
      <meta name="description" content="Crear rutas con puntos intermedios y gráfico de altitudes">
      <meta name="keywords" content="Crear rutas con puntos intermedios y gráfico de altitudes">
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <script src="https://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places,weather&amp;language=es&amp;region=ES"></script>
    
    <script>
    
    var rendererOptions = {
      draggable: false
    };
    
    var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);;
    var directionsService = new google.maps.DirectionsService();
    var map;
    
    var ba = new google.maps.LatLng(-34.796607,-58.466545);
    
    function initialize() {
    
      var mapOptions = {
        zoom: 6,
        center: ba
      };
      map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
      directionsDisplay.setMap(map);
      directionsDisplay.setPanel(document.getElementById('directionsPanel'));
    
      google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
        computeTotalDistance(directionsDisplay.getDirections());
      });
    
      calcRoute();
    }
    
    //////////////////////////////////////////////////// 
    
    // añadir y eliminar puntos intermedios
    function getPoints() {
        var waypts = new Array();
        var pointChildrens = document.getElementById("AllPoints").children;
        for (var i = 0; i < pointChildrens.length; i++) {
            var pointText = pointChildrens[i].children[0].value;
            if (pointText.trim() != '') {
                waypts.push({
                    location: pointText,
                    stopover: true
                });
            }
        }
        return waypts;
    };
    var totalPoints = 0;
    
    function AddNewPoint() {
        totalPoints = totalPoints + 1;
        var pointElem = document.getElementById('Waypoint');
        if (totalPoints == 1) {
            pointElem.style.display = 'block';
        } else {
            // btnAddWaypoint.innerHTML = "Nuevo punto";
            var divAllPoints = document.getElementById('AllPoints');
            var nextPoint = pointElem.cloneNode(true);
            // nextPoint.children[0].textContent = "Nuevo punto:";
            nextPoint.children[0].value = "";
            divAllPoints.appendChild(nextPoint);
        }
    };
    
    function DeletePoint(control) {
        totalPoints = totalPoints - 1;
        var divToDelete = control.parentNode;
        var divAllPoints = document.getElementById('AllPoints');
        if (totalPoints == 0) {
            divToDelete.style.display = 'none';
        } else {
            divAllPoints.removeChild(divToDelete);
        }
    };
    
    function calcRuta() {
        var waypts = new Array();
        var pointsArray = document.getElementsByName('points');
        for (var i = 0; i < pointsArray.length; i++) {
            if (pointsArray[i].value != '') {
                waypts.push({
                    location: pointsArray[i].value,
                    stopover: true
                });
            }
        }
        var modo;  // todo lo descrito en modo es para tomar la elección de modo de ruta
        if (document.getElementById('driving').checked) {
            modo = google.maps.DirectionsTravelMode.DRIVING;
        } else if (document.getElementById('bicycling').checked) {
            modo = google.maps.DirectionsTravelMode.BICYCLING;
        } else if (document.getElementById('transit').checked) {
            modo = google.maps.DirectionsTravelMode.TRANSIT;
        } else if (document.getElementById('walking').checked) {
            modo = google.maps.DirectionsTravelMode.WALKING;
        } else {
            alert('Escoja un modo de ruta');
        }
        var request = {
            origin: document.getElementById("origen").value,
            destination: document.getElementById("destino").value,
            waypoints: waypts,  // aquí van los puntos intermedios generados
            travelMode: modo, // el modo de ruta elegido
            unitSystem: google.maps.UnitSystem.METRIC,  // traducirá la distancia a Kilómetros, 
            optimizeWaypoints: $("#optWaypoints").is(":checked"),  // optimiza la ruta si está chequeado
            provideRouteAlternatives: true,  // muestra automáticamente rutas alternativas
            avoidHighways: document.getElementById('autopista').checked,  // evita autopistas
            avoidTolls: document.getElementById('peaje').checked  // evita peajes
        };
        directionsService.route(request, function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setMap(map);
                directionsDisplay.setPanel(document.getElementById('direcciones'));
                directionsDisplay.setDirections(response);
            } else {
                alert("No existen rutas entre ambos puntos");
            }
        });
    }
    
    
    google.maps.event.addDomListener(window, 'load', initialize);
    
    
    </script>
    
            <script type="text/javascript">
             function mostrar(){
             document.getElementById('oculto').style.display = 'block';}
             </script>    
    
    </head>
    
    <body>
    
         <div style="width:940px; margin:auto; margin-top:20;"> 
        
        <div Style="border:solid 1px #CCCCCC; border-radius:10px ; width:width:890px;height 300px font-family:arial; font-size:10px; margin:10px 0px 0px 20px;"><br>
        
        <div Style="family:arial; font-size:10px; margin:0px 0px 0px 10px;"> 
          
        <label>Origen:  <input type="text" size="20" id="origen" name="origen" value="" style="width: 355px; padding-left:5px;" ></label>
    
        <label>Destino:  <input type="text" size="20" id="destino" name="destino" value="calle, numero, ciudad ..." onclick="this.value=''" style="width: 355px; padding-left:5px;"></label>   
       <br>
       <br>   
          <input type="button" class="button" onclick="getLocation();" value="Mi posición como origen">
       <br>
       <br>
    
          <b>Puntos intermedios:</b>
       <br>
       <br>      
          <div id="AllPoints">
            <div id="Waypoint" style="display:none">
              <input type="text" name="points" size="50" placeholder="Ciudad ..." onfocus="autocompletar()" />
              <button onclick="DeletePoint(this)">X</button>
            </div>
          </div>
           <button class="button" id="btnAddWaypoint" onclick="AddNewPoint()">Ingresar Paradas Intermedias</button>
       <br>
       <br> 
          <label>Opciones de ruta</label>
          <input type="radio" name="travelMode" id="driving" value="DRIVING" checked onchange="calcRuta();">
          <label for="driving"><span></span> </label>
          <input type="radio" name="travelMode" id="bicycling" value="BICYCLING" onchange="calcRuta();">
          <label for="bicycling"><span></span> </label>
          <input type="radio" name="travelMode" id="transit" value="TRANSIT" onchange="calcRuta();">
          <label for="transit"><span></span> </label>
          <input type="radio" name="travelMode" id="walking" value="WALKING" onchange="calcRuta();">
          <label for="walking"><span></span> </label>
          <br>
          <input type="checkbox" id="trafico" onclick="estadotrafico();">
          <label for="trafico"><span></span> Ver estado del tráfico </label>
          <br>
          <input type="checkbox" id="autopista" onchange="calcRuta();">
          <label for="autopista"><span></span> Evitar autovías</label>
          <br>
          <input type="checkbox" id="peaje" onchange="calcRuta();">
          <label for="peaje"><span></span> Evitar peajes</label>
          <br>
          <input type="checkbox" name="optRuta" id="optWaypoints" onchange="calcRuta();">
          <label for="optWaypoints"><span></span> Optimizar etapas de ruta</label>
          <br>
          <input type="checkbox" name="nubes" id="nubes" value="nubes" onchange="meteo();">
          <label for="nubes"><span></span> Habilitar capa Nubes</label>
          <br>
          <input type="checkbox" name="temp" id="temp" value="temp" onchange="meteo();" />
          <label for="temp"><span></span> Temperaturas</label>
          <br>
          <br>
          <input type="button" class="button" onclick="reset();" value="Limpiar todo">
          
          <input type="button" class="button" onclick="calcRuta(); mostrar()" value="Trazar la ruta"> 
       <br>
       <br>
       </div>
       </div>
       </div><br> 
       
       <div id='oculto' style='display:none; '>
       
        <div style=" border:solid 1px #99CCFF; border-radius:10px; padding:5px; width:940px; margin:auto;" >
        Distancia y tiempo:<br>
        <a style="font-size:8px;">(El recorrido en el mapa es solamente sugerido)</a>
    	</div>   
        <br>	
        </div> 
     <div id="">
    
            <div id="direcciones" style="width: 400px; height: auto; padding:5px; float:left; margin:20px 0px 0px 20px; border:solid 1px #99CCFF; border-radius:10px; "></div>
        <div id="map-canvas" style="width: 400px; height: 400px; float:left; margin:0px 0px 0px 20px; border:solid 1px #99CCFF; border-radius:10px; "></div>
                    
            <div><img src="images/trafico.png" alt="Control tráfico" id="controltrafico" style="display:none;" /> </div>	
        </div>
        </div> 
        </div>        	 
    </body>
    </html>
      Votos: 1 - Link respuesta
     
  • Fecha: 16-03-2015 06:20:19 Txema, hay un post donde podes incluir tus servicios.

    ¿Necesitas algo? y/o ¿puedes ofrecer algún servicio?

    Muy buenos tus aportes,
      Votos: 0 - Link respuesta
     
  • Fecha: 16-03-2015 12:27:47 Hola Txema, no, debió haber sido algun usuario que vio tu publicación, todos los emails del sistema se encuentran correctamente identificados, no fué phpcentral....   Votos: 0 - Link respuesta
     
  • Fecha: 16-03-2015 12:57:02 Txema:

    Te envie un mail yo desde la pagina (Contactos) ... cuando no me podia comunicar contigo ... ya fue ...
    Por otra parte, le aplique css y esta marchando muy bien todo, sigo con la prueba del mi BETA, pronto te lo paso y ven como va quedando ...
      Votos: 0 - Link respuesta
     
  • Fecha: 16-03-2015 21:08:31 Txema:

    Como siempre muchas gracias

    Bueno dentro de mi script hice algunos ajuste a mi medida
    1.- Lo hice Draggable y fijo
    2.- Redondeo la cantidad de Kilometros totales
    3.- Transito
    4.- Estado del Tiempo durante el recorrido
    5.- Nuves (No entiendo bien esa funcion para que sirve)
    6.- No logro hacer eliminar el primer punto intermedio (Lo oculta pero no le elimina, salvo que uno lo haga de manera manual, el resto OK)

    Link del BETA >>> http://www.auditordigital.com.ar/tbd/tbd_ruta_vs12.php

    SCRIPT PARA QUE LO REVISES

    <!DOCTYPE html>
    <html>
    
    <head>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
        <meta charset="utf-8">
        <meta name="robots" content="noindex,nofollow">
        <meta name="description" content="Crear rutas con puntos intermedios y gráfico de altitudes">
        <meta name="keywords" content="Crear rutas con puntos intermedios y gráfico de altitudes">    
        
       <title>Draggable directions</title>
       <link rel="stylesheet" type="text/css" href="../css/consultas.css">    
       <link rel="stylesheet" type="text/css" href="../css/veh_datos.css">
        <style>
            html,
            body,
            #map-canvas {
                width: 85%;
                height: 90%;
                margin: auto;
                padding: 0px
            }
        </style>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    	<script src="https://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places,weather&amp;language=es&amp;region=AR"></script> 
        <script src="https://developers.google.com/maps/documentation/javascript/reference?hl=es"></script>
        <script src="http://www.cadetill.com/gmlib/"></script>
        
        <script src="../js/ruta.min.js"></script>
        <script src="../js/trafico.js"></script>   
        <script src="../js/meteo.js"></script>	
        
         <script>
    //////////////////////////////////////////////////////	
    	
            var rendererOptions = {  
                draggable: true
            };
            var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);;
            var directionsService = new google.maps.DirectionsService();
            var map;
            var ba = new google.maps.LatLng(-34.796607, -58.466545);
    
    
            function initialize() {
                    var mapOptions = {
                        zoom: 5,
                        center: ba
                    };
                    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
                    directionsDisplay.setMap(map);
                    directionsDisplay.setPanel(document.getElementById('directionsPanel'));
                    google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
                        computeTotalDistance(directionsDisplay.getDirections());
                    });
                    calcRuta();
                }
                ////////////////////////////////////////////////////    
                // añadir y eliminar puntos intermedios
            function getPoints() {
                var waypts = new Array();
                var pointChildrens = document.getElementById("AllPoints").children;
                for (var i = 0; i < pointChildrens.length; i++) {
                    var pointText = pointChildrens[i].children[0].value;
                    if (pointText.trim() != '') {
                        waypts.push({
                            location: pointText,
                            stopover: true
                        });
                    }
                }
                return waypts;
            };
            var totalPoints = 0;
    
            function AddNewPoint() {
                totalPoints = totalPoints + 1;
                var pointElem = document.getElementById('Waypoint');
                if (totalPoints == 1) {
                    pointElem.style.display = 'block';
                } else {
                    // btnAddWaypoint.innerHTML = "Nuevo punto";
                    var divAllPoints = document.getElementById('AllPoints');
                    var nextPoint = pointElem.cloneNode(true);
                    // nextPoint.children[0].textContent = "Nuevo punto:";
                    nextPoint.children[0].value = "";
                    divAllPoints.appendChild(nextPoint);
                }
            };
    
            function DeletePoint(control) {
                totalPoints = totalPoints - 1;
                var divToDelete = control.parentNode;
                var divAllPoints = document.getElementById('AllPoints');
                if (totalPoints == 0) {
                    divToDelete.style.display = 'none';
                } else {
                    divAllPoints.removeChild(divToDelete);
                }
            };
    
            function computeTotalDistance(result) {
                var total = 0;
                var myroute = result.routes[0];
                for (var i = 0; i < myroute.legs.length; i++) {
                    total += myroute.legs[i].distance.value;
                }
    			
                total = Math.round(total / 1000.00);
                document.getElementById('total').innerHTML = total + ' km';
            }
            google.maps.event.addDomListener(window, 'load', initialize);
    
            function calcRuta() {
                var waypts = new Array();
                var pointsArray = document.getElementsByName('points');
                for (var i = 0; i < pointsArray.length; i++) {
                    if (pointsArray[i].value != '') {
                        waypts.push({
                            location: pointsArray[i].value,
                            stopover: true
                        });
                    }
                }
    
    //////////////////////////////////////////////////////////////////////////////
    
    		var weatherLayer = new google.maps.weather.WeatherLayer();
    		weatherLayer.setMap(null);
    		var cloudLayer = new google.maps.weather.CloudLayer();
    		cloudLayer.setMap(null);
    		
    		function meteo() {
    		  if ($('#nubes').is(':checked')) {
    			cloudLayer.setMap(map);
    		  } else {
    			cloudLayer.setMap(null);
    		  }
    		};  
    		function nu() {  
    		  
    		  if ($('#temp').is(':checked')) {
    			weatherLayer.setOptions({'temperatureUnits': google.maps.weather.TemperatureUnit.CELSIUS,'windSpeedUnits': google.maps.weather.WindSpeedUnit.KILOMETERS_PER_HOUR});
    			weatherLayer.setMap(map);
    		  } else {
    			weatherLayer.setMap(null);
    		  }
    		};
    		
    //////////////////////////////////////////////////////////////////////////////			
    			
    			
                var modo; // todo lo descrito en modo es para tomar la elección de modo de ruta
                if (document.getElementById('driving').checked) {
                    modo = google.maps.DirectionsTravelMode.DRIVING;
    
                } else {
                    alert('Escoja un modo de ruta');
                }
                var request = {
                    origin: document.getElementById("stard").value,
                    destination: document.getElementById("end").value,
                    waypoints: waypts, // aquí van los puntos intermedios generados
                    travelMode: modo, // el modo de ruta elegido
                    unitSystem: google.maps.UnitSystem.METRIC, // traducirá la distancia a Kilómetros, 
                    optimizeWaypoints: $("#optWaypoints").is(":checked"), // optimiza la ruta si está chequeado
                    provideRouteAlternatives: true, // muestra automáticamente rutas alternativas
                    avoidHighways: document.getElementById('autopista').checked, // evita autopistas
                    avoidTolls: document.getElementById('peaje').checked // evita peajes
                };
                directionsService.route(request, function(response, status) {
                    if (status == google.maps.DirectionsStatus.OK) {
                        directionsDisplay.setMap(map);
                        directionsDisplay.setPanel(document.getElementById('direcciones'));
                        directionsDisplay.setDirections(response);
                    } else {
                        alert("No existen rutas entre ambos puntos");
                    }
                });
            }
        </script>
    </head>
    
    <body>
        <div style="width:940px; margin:auto; margin-top:20;">
            <div Style="border:solid 1px #CCCCCC; border-radius:10px ; width:840px;height 300px font-family:arial; font-size:10px; margin:10px 0px 0px 20px;">
                <br>
                <div Style="family:arial; font-size:10px; margin:0px 0px 0px 10px;">
                    <label>Desde:
                        <input type="text" size="20" id="stard" class="input" name="origen" value="" style="width: 355px; padding-left:5px;">
                    </label>
                    <label>Hasta:
                        <input type="text" size="20" id="end" class="input"  name="destino" value="" style="width: 355px; padding-left:5px;">
                    </label>
                    <br>
                    <br>
                    <div id="AllPoints">
                        <div id="Waypoint" style="display:none">
                       
                            <input type="text" name="points" class="input"  size="24"   style="width: 355px; padding-left:5px;" />
                          
                            <button class="button" onclick="DeletePoint(this)">X</button>
                         
                        </div>
                    </div>
                    <button class="button" id="btnAddWaypoint" onclick="AddNewPoint()">Ingresar Paradas Intermedias</button>
                    <br>
                    <br>
                    <label> Opciones de ruta</label>
                    <br>
                    <input type="hidden" name="travelMode" id="driving" value="DRIVING" checked onchange="calcRuta();">
    
                    <br>
    
                    <input type="checkbox" class="css-checkbox" id="autopista" onchange="calcRuta();">
                    <label for="autopista"><span></span> Evitar autovías</label>
                   
                    <input type="checkbox" class="css-checkbox" id="peaje" onchange="calcRuta();">
                    <label for="peaje"><span></span> Evitar peajes</label>
                  
                    <input type="checkbox" class="css-checkbox" name="optRuta" id="optWaypoints" onchange="calcRuta();">
                    <label for="optWaypoints"><span></span> Optimizar etapas de ruta</label>
    
                    <input type="checkbox" id="trafico" onclick="estadotrafico();">
                    <label for="trafico"><span></span> Ver estado del tráfico</label> 
                   
                  <br>
                  <input type="checkbox" class="css-checkbox" name="nubes" id="nubes" value="nubes" onchange="nu();">
                  <label for="nubes"><span></span> Habilitar capa Nubes (Zoom 0-6)</label>
                  <br>
                  <input type="checkbox" class="css-checkbox" name="temp" id="temp" value="temp" onchange="meteo();" />
                  <label for="temp"><span></span> Temperaturas (Weather.com) (Zoom 0-12)</label>
                 
                    <br>
                    <br>               
                    <input type="button" class="button" onclick="reset();" value="Limpiar registros">
                    <input type="button"  class="button" onclick="calcRuta();" value="Ingresar el recorrido">
                    <br>
                    <br> </div>
            </div>
            <div style="clear:both;"></div>
    
            <div id="map-canvas" style="width: 455px; height: 400px; float:left; margin:10px 0px 0px 20px; border:solid 1px #99CCFF; border-radius:10px; ">
    
            </div>
           
            <div id="direcciones" style="float:right; width:38%; height:100%; float:left; margin:10px 0px 0px 20px; padding:5px 0px 5px 5px; border:solid 1px #99CCFF; border-radius:10px;">
            
              <div id="directions" style="float:left; width:38%; height:100%; margin:5px 0px 5px 5px;">
              Total Distancia: <span id="total"></span>
               </div><br>         
            
            </div>
    
        </div>
    </body>
    </html>
    
    
      Votos: 0 - Link respuesta
     
  • Fecha: 17-03-2015 11:15:24 Txema:

    Sin enfados.
    Ya elimine lo que me sugeriste (Por otra parte ese script solo es de prueba no esta en uso)
    Soy un novato en esto (autodidacta), si bien estoy estudiando PHP y Mysql (se poco de Javascript), mi profesion es la de contador, ingrese a este mundo con la finalidad de buscar soluciones, lejos de encontrarme con problemas.
    Nunca fue mi intencion usurpar tu autoria intelectua, solo pense que me pasaste el codigo para que lo reutilice, tengo 55 años y a esta altura no se me ocurren esas cosas.
    Empece aprendiendo algo sobre esto con Jesus Conte (Español que tiene videos tutoriales), fue de alli que me anime a armar programas para mi trabajo que me ayuden con mis tareas.
    Muchas veces alguien tira unas lineas de codigo y uno mediante prueba y error, no solo aprende, sino que a veces termina desarrollando algo util.
    Si en algo te he ofendido, te pido mil disculpas, nunca fue mi intencion.
    En este momento estoy en la API de Google Maps para ver que puedo sacar de bueno y darme la cabeza y rato contra las paredes.
    Te envio un saludo y gracias nuevamente.
      Votos: 0 - Link respuesta
     
  • Fecha: 19-03-2015 09:50:26 Txema:

    Me estoy devorando la API de Google Maps, pero hay algo que no encuentro y vos por ahí me indicas donde puedo ir a leerlo.

    a) Pretendo determinar donde exactamente están los peajes (En caso de pasar por ellos).
    b) Cuando uno traza un recorrido (Ejemplo 100 Km), cual seria el costo aproximado del combustible, obviamente dependiendo si funciona a Nafta, gasoil o gas

    ¿Tenes idea donde puedo leer sobre esto, ya que en la API no encontré nada que me ayudara?
    Pese a que hay una aplicación de Android que si lo hace distribuida por Google.

    Te mando un saludo
      Votos: 0 - Link respuesta
     
  • Fecha: 19-03-2015 13:07:56 Texema:

    Ante todo muchas gracias por tu amabilidad como siempre en contestarme.
    Peajes - Aqui en Argentina se llama peaje al pago que se hace en las casillas que estan sobre las autovias las cuales te cobran por el uso que haces de ellas. En los recorridos te indica si lo queres hacer por autovia con o sin peajes, yo lo que pretendo es al trazar un recorrido por una autovia con peajes, cuantos son ellos en ese trazo ... Ejemplo de A a X hay 4 peajes.

    En cuanto al consumo de combuestible, si es un ecuacion matematica que depende de
    Cilindrada del Vehiculo
    Velocidad desarrollada promedio durante el tramo
    Tipo de combustible
    Precio del tipo de combustible

    Por suerte las cilindradas de los vehiculos para este trabajo son solo 2 (1600 cc y 1800 cc)
    y el combustible a utilizar son 3 (Nafta, Gasoil y Gas).

    Voy a seguir buscando variables en esto y veo como sigo, si se te ocurre alguna idea, bienvenida sea
      Votos: 0 - Link respuesta
     
  • Fecha: 19-03-2015 20:01:50 Txema:

    En esto estoy ... ver aqui >>> http://www.auditordigital.com.ar/ayuda/know_how.pdf

    Ojo, esto es solo una pequeña parte que te muestro hay mucho mas desarrollado en PHP y Mysql por este novato autodidacta.

    Si te interesa, yo aqui estoy contactado con las empresas que brindan este servicio de transporte, dado a que asesoro a la Camara Empresaria, estoy embarcado solo en esto, hay mucho por hacer y yo algo cansado.

    Mi mail: calofatti@hotmail.com
      Votos: 0 - Link respuesta
     
Para participar activamente de la comunidad primero debes autenticarte, ingresa al sistema.Iniciar Sesión
 
frjcbbae garagebible.com