Mapping and getting mileage between two points


I'm developing a web application, and I'm getting two addresses for a text field, and I'm using it to calculate the distance to the Matrix API from Google Maps, so beauty, but I also wanted to generate a map showing that path, and that this path was exactly the same as the Matrix API used to calculate the mileage. In short, I need to draw a path between two points, and get the mileage between it (to save in a variable). Give me only one north, that's all I need. Thank you.

asked by anonymous 09.07.2014 / 01:41

1 answer


Using google maps API V3 , you can use this example, if you need only one north.

Javascript + Html

<!DOCTYPE html>

<html xmlns="">
    <title>Calcular distancia entre cidades (mapas e rotas)</title>
    <script src=""type="text/javascript"></script>
    <!-- Parâmetro sensor é utilizado somente em dispositivos com GPS -->
    <script src=""></script><scripttype="text/javascript">
        function CalculaDistancia() {
            //Instanciar o DistanceMatrixService
            var service = new google.maps.DistanceMatrixService();
            //executar o DistanceMatrixService
                  origins: [$("#txtOrigem").val()],
                  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"
            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
                $('#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", "" + response.originAddresses + "&daddr=" + response.destinationAddresses + "&output=embed");
    <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>
    <div style="padding: 10px 0 0; clear: both">
        <iframe width="750" scrolling="no" height="350" frameborder="0" id="map" marginheight="0" marginwidth="0" src="ãopaulo&daddr=riodejaneiro&output=embed"></iframe>

Return from Json

{ "destinationAddresses" : [ "Rio de Janeiro - RJ, República Federativa do Brasil" ],
       "originAddresses" : [ "São Paulo - SP, República Federativa do Brasil" ],
       "rows" : [ { "elements" : [ { "distance" : { "text" : "430 km",
              "value" : 430395
          "duration" : { "text" : "4 horas 42 minutos",
              "value" : 16942
          "status" : "OK"
        } ] } ]

I've already used this example for an application and it worked ... Just change what you need.

Source: link

If you have any questions, just talk, although it is well commented, you have some implementation details, note that the use of javascript objects is very strong in the API.

Another site with detailed explanations of the objects: link

09.07.2014 / 14:32