Calculate distance between 2 points in Google maps

3

I do not have much experience with javascript and I have no idea how to get the result of this script and move to a <input text> field. This script calculates the distance and time between two points. So I wanted to take the time and distance and then save it in a database.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Calcular distancia entre cidades (mapas e rotas)</title>
<script src="http://code.jquery.com/jquery-1.8.1.js"type="text/javascript"></script>
</head>
<body>
<!-- Parâmetro sensor é utilizado somente em dispositivos com GPS -->
<script src="http://maps.google.com/maps/api/js?sensor=false"></script><scripttype="text/javascript">
    function CalculaDistancia() {
        $('#litResultado').html('Aguarde...');
        //Instanciar o DistanceMatrixService
        var service = new google.maps.DistanceMatrixService();
        //executar o DistanceMatrixService
        service.getDistanceMatrix(
          {
              //Origem
              origins: [$("#txtOrigem").val()],
              //Destino
              destinations: [$("#txtDestino").val()],
              //Modo (DRIVING | WALKING | BICYCLING)
              travelMode: google.maps.TravelMode.DRIVING,
              //Sistema de medida (METRIC | IMPERIAL)
              unitSystem: google.maps.UnitSystem.METRIC
              //Vai chamar o callback
          }, callback);
    }
    //Tratar o retorno do DistanceMatrixService
    function callback(response, status) {
        //Verificar o Status
        if (status != google.maps.DistanceMatrixStatus.OK)
            //Se o status não for "OK"
            $('#litResultado').html(status);
        else {
            //Se o status for OK
            //Endereço de origem = response.originAddresses
            //Endereço de destino = response.destinationAddresses
            //Distância = response.rows[0].elements[0].distance.text
            //Duração = response.rows[0].elements[0].duration.text
            var x = response.rows[0].elements[0].distance.text;
            $('#litResultado').html("<strong>Origem</strong>: " +    
 response.originAddresses +
                "<br /><strong>Destino:</strong> " + response.destinationAddresses +
                "<br /><strong>Distância</strong>: " +  
 response.rows[0].elements[0].distance.text +
                " <br /><strong>Duração</strong>: " + 
 response.rows[0].elements[0].duration.text
                );
            //Atualizar o mapa
            $("#map").attr("src", "https://maps.google.com/maps?saddr=" + 
    response.originAddresses + "&daddr=" + response.destinationAddresses +  
    "&output=embed");
        }
    }
   </script>

   <table width="100%" cellspacing="0" cellpadding="0" border="0">
       <label for="txtOrigem"><strong>Endere&ccedil;o de origem</strong></label>
       <input type="text" id="txtOrigem" class="field" style="width: 400px" />
       <label for="txtDestino"><strong>Endere&ccedil;o de destino</strong></label>
       <input type="text" style="width: 400px" class="field" id="txtDestino" />
       <input type="button" value="Calcular dist&acirc;ncia"  onclick="CalculaDistancia()" class="btnNew" />
  <div><span id="litResultado">&nbsp;</span></div>

  <!------------------------------------------------------------------->
    <input type="text" value="<? Variavel distancia?>"  
    <input type="text" value="<? Variavel tempo?>"  
  <!------------------------------------------------------------------->

 <div style="padding: 10px 0 0; clear: both">
    <iframe width="750" scrolling="no" height="350" frameborder="0" id="map" 
  marginheight="0" marginwidth="0" src="https://maps.google.com/maps?saddr=sãopaulo&daddr=riodejaneiro&output=embed"></iframe>
</div>
    
asked by anonymous 05.02.2015 / 05:07

1 answer

6

I think I've managed to resolve it.

First I have corrected problems with poorly formed HTML: The </body> and the </html> are missing at the end, which I added. You have a <table> element left over which is useless, and I've removed it. You're breaking line inside the src attribute of <iframe> and that's bad, and I did not break line there. Also I added <!DOCTYPE html> and <meta charset="utf-8"> . Finally I made some escapes that were missing (% from% to â and &acirc; to ã ).

Then I added the fields where the result will be placed. I have also separated them from the fields where the research is conducted. I've made the result fields read-only to make sure their results actually come from Google (however do not rely on this if you're making it available to the general public). I put all of them inside a &atilde; with a submit button to be able to send to the server later:

    <form action="http://www.example.com/url" method="post">
      <div><span>Pesquisa:</span></div>
      <label for="txtOrigem"><strong>Endere&ccedil;o de origem</strong></label>
      <input name="pesquisaOrigem" type="text" id="txtOrigem" class="field" style="width: 400px" value="S&atilde;o Paulo" />
      <label for="txtDestino"><strong>Endere&ccedil;o de destino</strong></label>
      <input name="pesquisaDestino" type="text" id="txtDestino" class="field" style="width: 400px" value="Rio de Janeiro" />
      <input type="button" value="Calcular dist&acirc;ncia" onclick="CalculaDistancia()" class="btnNew" />
      <div><span id="litResultado">&nbsp;</span></div>

      <div><span>Resposta:</span></div>
      <label for="txtOrigemResultado"><strong>Endere&ccedil;o de origem</strong></label>
      <input name="resultadoOrigem" readonly="readonly" type="text" id="txtOrigemResultado" class="field" style="width: 400px" value="" />
      <label for="txtDestinoResultado"><strong>Endere&ccedil;o de destino</strong></label>
      <input name="resultadoDestino" readonly="readonly" type="text" id="txtDestinoResultado" class="field" style="width: 400px" value="" />
      <br />
      <label for="txtDistancia"><strong>Dist&acirc;ncia</strong></label>
      <input name="distancia" readonly="readonly" type="text" id="txtDistancia" value="" /> 
      <label for="txtTempo"><strong>Tempo</strong></label>
      <input name="tempo" readonly="readonly" type="text" id="txtTempo" value="" />
      <input type="submit" value="Enviar para o servidor" />
    </form>

I've set the javascript to populate these fields in the callback. I already took advantage to take the "wait" when the answer arrives and also translated the time into Portuguese.

      // Tratar o retorno do DistanceMatrixService
      function callback(response, status) {
        // Verificar o status.
        if (status != google.maps.DistanceMatrixStatus.OK) { // Se o status não for "OK".
            $("#litResultado").html(status);
        } else { // Se o status for "OK".
            $("#litResultado").html("&nbsp;"); // Remove o "aguarde".

            // Popula os campos.
            $("#txtOrigemResultado").val(response.originAddresses);
            $("#txtDestinoResultado").val(response.destinationAddresses);
            $("#txtDistancia").val(response.rows[0].elements[0].distance.text);
            var tempo = response.rows[0].elements[0].duration.text;
            tempo = tempo.replace("day", "dia").replace("hour", "hora").replace("min", "minuto");
            $("#txtTempo").val(tempo);

            //Atualizar o mapa.
            $("#map").attr("src", "https://maps.google.com/maps?saddr=" + response.originAddresses + "&daddr=" + response.destinationAddresses + "&output=embed");
        }
      }

Here is the full HTML:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Calcular dist&acirc;ncia entre cidades (mapas e rotas)</title>
    <script src="http://code.jquery.com/jquery-1.8.1.js"type="text/javascript"></script>
  </head>
  <body>
    <!-- Parâmetro sensor é utilizado somente em dispositivos com GPS -->
    <script src="http://maps.google.com/maps/api/js?sensor=false"></script><scripttype="text/javascript">
      function CalculaDistancia() {
        $('#litResultado').html('Aguarde...');
        // Instancia o DistanceMatrixService.
        var service = new google.maps.DistanceMatrixService();
        // Executa o DistanceMatrixService.
        service.getDistanceMatrix({
            origins: [$("#txtOrigem").val()], // Origem
            destinations: [$("#txtDestino").val()], // Destino
            travelMode: google.maps.TravelMode.DRIVING, // Modo (DRIVING | WALKING | BICYCLING)
            unitSystem: google.maps.UnitSystem.METRIC // Sistema de medida (METRIC | IMPERIAL)
        }, callback); // Vai chamar o callback
      }

      // Tratar o retorno do DistanceMatrixService
      function callback(response, status) {
        // Verificar o status.
        if (status != google.maps.DistanceMatrixStatus.OK) { // Se o status não for "OK".
            $("#litResultado").html(status);
        } else { // Se o status for "OK".
            $("#litResultado").html("&nbsp;"); // Remove o "aguarde".

            // Popula os campos.
            $("#txtOrigemResultado").val(response.originAddresses);
            $("#txtDestinoResultado").val(response.destinationAddresses);
            $("#txtDistancia").val(response.rows[0].elements[0].distance.text);
            var tempo = response.rows[0].elements[0].duration.text;
            tempo = tempo.replace("day", "dia").replace("hour", "hora").replace("min", "minuto");
            $("#txtTempo").val(tempo);

            //Atualizar o mapa.
            $("#map").attr("src", "https://maps.google.com/maps?saddr=" + response.originAddresses + "&daddr=" + response.destinationAddresses + "&output=embed");
        }
      }
    </script>

    <form action="http://www.example.com/url" method="post">
      <div><span>Pesquisa:</span></div>
      <label for="txtOrigem"><strong>Endere&ccedil;o de origem</strong></label>
      <input name="pesquisaOrigem" type="text" id="txtOrigem" class="field" style="width: 400px" value="S&atilde;o Paulo" />
      <label for="txtDestino"><strong>Endere&ccedil;o de destino</strong></label>
      <input name="pesquisaDestino" type="text" id="txtDestino" class="field" style="width: 400px" value="Rio de Janeiro" />
      <input type="button" value="Calcular dist&acirc;ncia" onclick="CalculaDistancia()" class="btnNew" />
      <div><span id="litResultado">&nbsp;</span></div>

      <div><span>Resposta:</span></div>
      <label for="txtOrigemResultado"><strong>Endere&ccedil;o de origem</strong></label>
      <input name="resultadoOrigem" readonly="readonly" type="text" id="txtOrigemResultado" class="field" style="width: 400px" value="" />
      <label for="txtDestinoResultado"><strong>Endere&ccedil;o de destino</strong></label>
      <input name="resultadoDestino" readonly="readonly" type="text" id="txtDestinoResultado" class="field" style="width: 400px" value="" />
      <br />
      <label for="txtDistancia"><strong>Dist&acirc;ncia</strong></label>
      <input name="distancia" readonly="readonly" type="text" id="txtDistancia" value="" /> 
      <label for="txtTempo"><strong>Tempo</strong></label>
      <input name="tempo" readonly="readonly" type="text" id="txtTempo" value="" />
      <input type="submit" value="Enviar para o servidor" />
    </form>

    <div style="padding: 10px 0 0; clear: both">
      <iframe width="750" scrolling="no" height="350" frameborder="0" id="map" marginheight="0" marginwidth="0" src="https://maps.google.com/maps?saddr=S&atilde;oPaulo&daddr=RiodeJaneiro&output=embed"></iframe>
    </div>
  </head>
</html>

To use, you should proceed as follows:

  • You choose the desired places and fill them in the search fields.
  • Click the "Calculate Distance" button
  • Google will bring the result.
  • javascript will fill in the form fields with the results.
  • You click the "Send to server" button and the form data will be sent to the server.
  • On the server, you will receive a POST request containing the following form fields: <form> , pesquisaOrigem , pesquisaDestino , resultadoOrigem , resultadoDestino and distancia . The meaning of each is obvious. The URL responsible for receiving this service must be configured on your server and the tempo field of your action in the HTML should match it.

    If you prefer, you can have Google's OK response already submit the result via AJAX to your server automatically. Or you may want to put some more complex validation logic on your "Send to Server" button. In this case, if you have any questions about how to do this, you are already in the scope of another question, but nothing prevents you from adapting this process as you wish.

    On the server, you will run a prepared statement with a SQL statement something like this:

    INSERT INTO Distancias (pesquisaOrigem, pesquisaDestino, resultadoOrigem, resultadoDestino, distancia, tempo) VALUES (?, ?, ?, ?, ?, ?)
    

    Or just like this:

    INSERT INTO Distancias (origem, destino, distancia, tempo) VALUES (?, ?, ?, ?)
    

    And then just populate the parameters of your prepared statement with the data received from the form. However, before doing so, you may want to preprocess them to convert all times in minutes, convert all distances to numeric values (by eliminating the suffix <form> ), and perhaps by tidying up the source and destination if you want to delete information that you feel is unnecessary, such as street number, zip code, case sensitivity, or whatever you want.

        
    05.02.2015 / 06:57