GOOGLE MATRIX API

Asked

Viewed 906 times

0

I am using the following method to calculate the distance between 2 cities using Google API Matrix:

  private function calculaDistancia () {

    $this->destino =  str_replace(" ","%20",$this->phpUtil->limpaCaracters($this->destino));


    $url = "https://maps.googleapis.com/maps/api/distancematrix/xml?origins=".$this->origem."-".$this->estadoOrigem."&destinations=".$this->destino."-".$this->estadoDestino."&mode=".$this->mode."&language=".$this->language."&sensor=false";   
   print $url;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FAILONERROR, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $data = curl_exec($ch);     

    $freteXML = simplexml_load_string($data);
    $distancia = $freteXML->row->element->distance->value;

    return $distancia;

  }

It actually works. And the search url is:

$url = "https://maps.googleapis.com/maps/api/distancematrix/xml?origins=".$this->origem."-".$this->estadoOrigem."&destinations=".$this->destino."-".$this->estadoDestino."&mode=".$this->mode."&language=".$this->language."&sensor=false";   

Well, the problem is that in a query I had the following input url:

https://maps.googleapis.com/maps/api/distancematrix/xml?origins=Muriae-MG&destinations=Macapá-AP&mode=driving&language=pt-BR&sensor=false

Who returned the next:

<DistanceMatrixResponse>
  <status>OK</status>
  <origin_address>Muriaé, MG, Brasil</origin_address>
  <destination_address>Macapá, AP, Brasil</destination_address>
   <row>
    <element>
      <status>ZERO_RESULTS</status>
    </element>
  </row>
</DistanceMatrixResponse>

Note that it identifies the cities but cannot calculate the gaps.

Some recourse?

  • Why don’t you just calculate the distance between two points on the planet? you don’t need this API... the only thing you need is to find the Longiture and Latitude of the two cities (lots of free Apis for that) and then use the formula of haversine (many examples in any language) ... is not 100% certain, because the formula calculates the distance of 2 points on a sphere, and the planet is not a sphere, but is very close...

1 answer

0

According to Google, not all routes have routes.

This is common when you search places far away or that do not have direct highways.

I don’t know if you tested it, but or directly on Google Maps it is possible to find a route, as can be seen in the image below:

inserir a descrição da imagem aqui

If you shorten the search a little and try to find a route between Belém and Macapá, you will see that Google shows only one route by plane.

I do not know if there is a balloon to cross the Amazon River, but if there is Google unknown (as I, rsrsr).

If you understand me correctly Santana Island to Macapá exists route. And Google shows that it’s only 15KM away. (I don’t even know if there’s anything there, kkkk)

Like you said in his comment that wanted only the site script and that would adapt to PHP, the site script indicated is this:

 <script type="text/javascript">
            var map;
            var geocoder;
            var directionsDisplay;
            var directionsService = new google.maps.DirectionsService();
            var path = new google.maps.Polyline();
            var pageLoaded = false;

            function setLatLngByInput(origem, destino) {
                if (origem == "" || destino == "") {
                    $(".div_info").hide("slow");
                    return false;
                }

                //apaga o mapa
                path.setMap(null);
                directionsDisplay.setMap(null);

                //declara as variaveis locais
                var start;
                var end;

                //obtem a latitude de origem e de destino
                geocoder.geocode({'address': origem}, function(results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        start = results[0].geometry.location;
                        gOrigemlat = results[0].geometry.location.lat();
                        gOrigemlng = results[0].geometry.location.lng();


                        geocoder.geocode({'address': destino}, function(results, status) {
                            if (status == google.maps.GeocoderStatus.OK) {
                                end = results[0].geometry.location;
                                gDestinolat = results[0].geometry.location.lat();
                                gDestinolng = results[0].geometry.location.lng();

                                //Calcula a rota
                                var request = {
                                    origin: start,
                                    destination: end,
                                    travelMode: google.maps.DirectionsTravelMode.DRIVING
                                };
                                directionsService.route(request, function(response, status) {
                                    if (status == google.maps.DirectionsStatus.OK) {
                                        var distanciaRuta = response.routes[0].legs[0].distance.text;
                                        $("#distanciarota").html(distanciaRuta);

                                        var tiempo = response.routes[0].legs[0].duration.text;
                                        $("#tempoviajem").html(tiempo);
                                        directionsDisplay.setDirections(response);
                                        directionsDisplay.setMap(map);
                                    }
                                });


                                //Calcula a linha
                                dist = Math.round(((google.maps.geometry.spherical.computeDistanceBetween(start, end, 6378137)) / 1000) * 100) / 100;
                                $("#kmlinhareta").html(dist);

                                var route =
                                        [
                                            start, end
                                        ];

                                path = new google.maps.Polyline(
                                        {
                                            path: route,
                                            strokeColor: "#00711D",
                                            strokeOpacity: 0.5,
                                            strokeWeight: 3,
                                            geodesic: false
                                        });
                                path.setMap(map);
                                $(".div_info").show("slow");

                                if (pageLoaded)
                                    $('html, body').animate({scrollTop: $("#gotomapa").offset().top}, 2500);
                                else
                                    pageLoaded = true;

                            } else {
                                alert('não foi possível encontrar o destino!');
                                $(".div_info").hide("slow");
                                return false;
                            }
                        });
                    }
                    else {
                        alert('não foi possível encontrar a origem!');
                        $(".div_info").hide("slow");
                        return false;
                    }
                });
            }

            function setRout() {
                //obtem a string de origem e de destino
                var origem = $("#origem").val();
                var destino = $("#destino").val();
                setLatLngByInput(origem, destino);
            }

            function initialize() {
                directionsDisplay = new google.maps.DirectionsRenderer();
                geocoder = new google.maps.Geocoder();

                var mapOptions = {
                    center: new google.maps.LatLng(-18.388765859930732, -49.114726562499975),
                    zoom: 4,
                    scrollwheel: false,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
                directionsDisplay.setMap(map);

                var adUnitDiv = document.createElement('div');
                var adUnitOptions = {format: google.maps.adsense.AdFormat.LEADERBOARD, position: google.maps.ControlPosition.BOTTOM_CENTER, publisherId: 'ca-pub-9874183828883904', map: map, visible: true};
                var adUnit = new google.maps.adsense.AdUnit(adUnitDiv, adUnitOptions);

                setLatLngByInput($("#origem").val(), $("#destino").val());

                var origem = document.getElementById('origem');
                var fromAutocomplete = new google.maps.places.Autocomplete(origem);

                var destino = document.getElementById('destino');
                var toAutocomplete = new google.maps.places.Autocomplete(destino);
            }

            function recalcOnLoadPage() {
                var fieldOrigem = $("#origem").val();
                var fieldDestino = $("#destino").val();

                var issetOrigem = fieldOrigem != "";
                var issetDestino = fieldDestino != "";

                var preenchido = issetOrigem && issetDestino;

                if (preenchido) {
                    if ($("#distanciarota").val() == "")
                        setRout();
                } else {
                    return false;
                }
            }

            $(document).ready(function() {
                $('#origem').keypress(function(e) {
                    if (e.which == 13) {
                        $("#destino").focus();
                    }
                });

                $('#destino').keypress(function(e) {
                    if (e.which == 13) {
                        $(".setrout").focus();
                    }
                });

                if ($("#origem").val() == "null") {
                    $("#origem").val("São Paulo, República Federativa do Brasil");
                }

                if ($("#destino").val() == "null") {
                    $("#destino").val("Rio de Janeiro, República Federativa do Brasil");
                }

                //$('html, body').animate({ scrollTop: $("#gotomapa").offset().top }, 4500);

                initialize();

            });
        </script>

Good Luck with the adaptation. However, if you really want to learn how to use the Google API, read to and I will be happy to help you with any questions

  • It is. But what most intrigues me is that this site, http://www.entrecidadesdistancia.com.br/, is using the same API and returns. Only in JS

  • @Carlosrocha This site is calculating the distance straight between the two cities. The API you are using is calculating the distance travelled, that is, by roads and not in a straight line.

  • Yes, but in case one fails, I use the other. I am in doubt about the implementation because its code mixes. If I find exactly the js that makes this calculation, then migrate it to php

  • Looking again, he does: "The distance by highways is approximately:..."

  • @Carlosrocha Play on Google Maps and see if that’s it. Specifically the distance between Muriaé and Macapá.

  • On the site, the guy says he is using the DNIT database. But I did not find any API of them.

  • I want help with php. What I need to add to my code (or modify) to calculate?]

  • @carlosrocha no, the code clearly shows that it just checks if it has route, if there is it put a straight line. If you want some help on how to do this, I advise you to create another question and explain it better. In this question just about zero_results. Are subjects of the red

  • If he uses it for something else, there’s no way for me to know. However, the code shows that he does everything for the Google API

  • Okay, let me ask you another question. But answer me this: If we are using the same API, and in his answer has the distance on the roads as well, why did his work and mine not? Just being using JS and I php?

  • You are using the data returned from a url. At no time does Voce actually use the Google API. If you observe the code, you will see that it is commented something like Calculates the route and Calculates the line. Using the libraries that Google has created, this is relatively simple. Doing everything "at hand" that requires more work.

  • I’m kind of not sure how to create another question and talk about almost the same thing, like: API MATRIX GOOGLE PHP?

  • I created another question: http://answall.com/questions/166211/erro-ao-receivedistance-da-api-do-google-matrix-distance

Show 8 more comments

Browser other questions tagged

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