GOOGLE MATRIX API

0

I'm 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;

  }

In fact it 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 one query I had the following url of input:

link

You have returned the following:

<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 cities but can not calculate the degrees.

Any feature?

    
asked by anonymous 17.11.2016 / 21:04

1 answer

0

According to Google, not all routes will have routes.

This is common to happen when you search places far away or do not have direct roads.

I do not know if you've ever tested, but #

Ifyoushortenthesearchabitandtrytofindaroutebetween#

I do not know if there are any scales to cross the Amazon River, but if there is Google, it is not known (just like me, rsrsr).

If you understand correctly, neither Ilha de Santana for Macapá there is a route . And look that google shows that they are only 15KM away. (I do not know if there is anything there, kkkk)

As you said in your comment that you only wanted the script of the site 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 and I'll be happy to help you with any doubt

    
17.11.2016 / 22:31