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 â
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 ã
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ço de origem</strong></label>
<input name="pesquisaOrigem" type="text" id="txtOrigem" class="field" style="width: 400px" value="São Paulo" />
<label for="txtDestino"><strong>Endereç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ância" onclick="CalculaDistancia()" class="btnNew" />
<div><span id="litResultado"> </span></div>
<div><span>Resposta:</span></div>
<label for="txtOrigemResultado"><strong>Endereç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ç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â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(" "); // 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â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(" "); // 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ço de origem</strong></label>
<input name="pesquisaOrigem" type="text" id="txtOrigem" class="field" style="width: 400px" value="São Paulo" />
<label for="txtDestino"><strong>Endereç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ância" onclick="CalculaDistancia()" class="btnNew" />
<div><span id="litResultado"> </span></div>
<div><span>Resposta:</span></div>
<label for="txtOrigemResultado"><strong>Endereç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ç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â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ã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.