Mapping and getting mileage between two points

Asked

Viewed 15,796 times

9

I’m developing a web application, and I’m getting two addresses for a text field, and I’m using to calculate the distance the Matrix API from Google Maps, until then beauty, but I also wanted to generate a map showing this path, and that this path was exactly the same as the Matrix API used to calculate mileage. In short, I need to trace a path between two points, and obtain the mileage between it (to store in a variable). Just give me a north, that’s all I need. Thank you.

  • The direct path or even a map like Google Maps?

  • A map with google maps, tracing the real path between two points, for example: Salvador - São Paulo, show the path (gps type) and the mileage between the two cities.

  • Very interesting question, I think it would be nice to leave open to other Apis besides Google Maps (as Here, Openstreetmap, etc..)

  • If you solve my problem and the one you need can be in any API.

  • I don’t understand if you have already converted the address to coordinates, to get the route, if yes, put your js to see what you need to add and/or modify.

1 answer

9


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

Javascript + Html

<!DOCTYPE html>

<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>
    <script type="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
                $('#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">
        <tbody>
            <tr>
                <td>
                    <label for="txtOrigem"><strong>Endere&ccedil;o de origem</strong></label>
                    <input type="text" id="txtOrigem" class="field" style="width: 400px" />

                </td>
            </tr>
            <tr>
                <td>
                    <label for="txtDestino"><strong>Endere&ccedil;o de destino</strong></label>
                    <input type="text" style="width: 400px" class="field" id="txtDestino" />

                </td>
            </tr>
            <tr>
                <td>
                    <input type="button" value="Calcular dist&acirc;ncia" onclick="CalculaDistancia()" class="btnNew" />
                </td>
            </tr>
        </tbody>
    </table>
    <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="https://maps.google.com/maps?saddr=são paulo&daddr=rio de janeiro&output=embed"></iframe>
    </div>

Return of the 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 already used this example for an application and it worked... Just change what you need.

Source: http://cbsa.com.br/post/distancia-entre-cidades---google-maps-javascript-api-v3.aspx

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

Another site with detailed explanations of objects: http://tableless.com.br/api-google-maps-v3/

  • I managed to understand almost everything, but since I don’t have much knowledge of json it takes me a doubt, as I do to pass the value that it returns me to php, so I can manipulate the data?

  • This example solved my problem, I just really wanted to be able to pass to PHP the variable of the distance in KM, and another thing, in the map it also shows the time if it is by plane. Has to take out?

  • So, what happens is this, your php page will process and render the html, then javascript will activate. You would need to know how your application is to understand where the code could be inserted, you can post via ajax to save to a database via php for example. What is the purpose of sending to PHP, which you need to handle exactly?

  • My application is almost like this example, I have 3 fields, destination and origin and car, and I was looking to generate the map with the route and mileage, well, I have a table of cars in the database, with energy consumption and pollution, so I wanted to take a data of this ex: pollution, and multiply by the value of Kms to get a result and show to the user. That’s it.

  • Okay, you’re going to need a callback that triggers an http request via ajax, you’re going to pass the distance meter and the other parameters that you’re going to use for the calculation, but then, it’s content for one more question, because it seems a bit complex to answer without seeing the rest of the code, I do not know how is structured your comic and this other information to suggest you something more concrete.

  • Would the car be a select, with the registration id of the car, relating this other information? Or will the person type a model, and perform a search? This just got a little vague for me.

  • Ah, the car is in a combobox, it will choose the model and from there, will be made a select p return the database data.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.