Calculate distance between two points api google maps php

2

Having the points I need to calculate the distance between them to make a calculation of a price, how could I do it from php? Doing it from the frontend with the javascript api would be unsafe because they could inject a distance that is not correct

    
asked by Elias Tutungi 16.11.2017 в 13:57
source

3 answers

1

If you are using the Google Directions API, it will return it to you in the response. We have the next segment of code of a function that traces a route

function calculateAndDisplayRoute(map) {

        var directionsServiceTmp = new google.maps.DirectionsService;
        var directionsDisplayTmp = new google.maps.DirectionsRenderer;

        location_ini = 14.595188 + ',' + -90.5166266;
        location_fin = 14.641828 + ',' + -90.5152771;

        directionsServiceTmp.route({
            origin: location_ini,
            destination: location_fin,
            optimizeWaypoints: true,
            travelMode: 'DRIVING'
        }, function(response, status) {
            if (status === 'OK') {
                // Aqui con el response podemos acceder a la distancia como texto 
                console.log(response.routes[0].legs[0].distance.text);
                // Obtenemos la distancia como valor numerico en metros 
               console.log(response.routes[0].legs[0].distance.value);

                directionsDisplayTmp.setDirections(response);
            }
        });
        directionsDisplayTmp.setMap(map);
}
    
answered by 03.06.2018 в 05:09
0

to calculate the distance between 2 points you need to know the coordinates x and y knowing that the distance between the points is equal to the difference between the x and the difference between the and, so you would have to do something like that

<?php
   function calculaDistancia($longitud1, $latitud1, $longitud2, $latitud2){

       //calculamos la diferencia de entre la longitud de los dos puntos
       $diferenciaX = $longitud1 - $longitud2;

       //ahora calculamos la diferencia entre la latitud de los dos puntos
       $diferenciaY = $latitud1 -$latitud2;

       // ahora ponemos en practica el teorema de pitagora para calcular la distancia
       $distancia = sqrt(pow($diferenciaX,2) + pow($diferenciaY,2));
    }
?>

the function sqrt() serves to make the square root, while the function pow() serves to calculate the power

to obtain the coordinates you can use the google geocoding that you can find in this link

I hope it's useful for you

    
answered by 16.11.2017 в 15:09
0

Since the earth is a spheroid, the Cartesian distance between two points can not be used (except in very specific cases). What you want to do can be done in two ways.

  • With the Spherical law of cosines
  • With the Haversine formula
  • Let's start thinking that your points are

    $lat0 = 45.50;
    $lng0 = 15.47;
    $lat1 = 35.15;
    $lng1 = 16.12;
    

    And their respective transformations to radians (because later you'll see that you work with radians.

    $rlat0 = deg2rad($lat0);
    $rlng0 = deg2rad($lng0);
    $rlat1 = deg2rad($lat1);
    $rlng1 = deg2rad($lng1);
    

    And the difference between these values (also used later)

    $latDelta = $rlat1 - $rlat0;
    $lonDelta = $rlng1 - $rlng0;
    

    Using spherical law of cosines

    $distance = (6371 *
        acos(
            cos($rlat0) * cos($rlat1) * cos($lonDelta) +
            sin($rlat0) * sin($rlat1)
        )
    );
    
    echo 'distanct arcosine ' . $distance;
    

    Note that 6371 is the radius of the earth in KM. If you want the distance in meters, you put 6371000, and if you want the distance in miles, inches, etc ... well, you understand me.

    For the example, the resulting distance is 1152.1745200602 Km

    With Haversine's formula

    $distance2 = 6371 * 2 * asin(
        sqrt(
            cos($rlat0) * cos($rlat1) * pow(sin($lonDelta / 2), 2) +
            pow(sin($latDelta / 2), 2)
        )
    );
    
    echo 'distance haversine ' . $distance2;
    

    And the result, to our surprise, is also 1152.1745200602 Km

    (there are cases where the results differ, for example when the coordinates are antipodal to each other, or you are close to the poles).

    There is an approach using the equirectangular projection , but I do not understand that projection, I do not work with it, I do not know the formula and I prefer to pretend it does not exist.

    Disclaimer :

    Work with maps and GIS applications taken to the web using Google Maps and Leaflet as a base. The first prototype of the product had PHP as a backend. That's why I had to learn these things.

        
    answered by 17.11.2017 в 13:33