google-mapsgeolocationpolylinegoogle-polylinegoogle-distancematrix-api

Calculate the distance between multi geolocations points


My application collects geolocation point from the user every certain amount of time, I am trying to use these points in order to calculate the distance from the first point through all of the points.

please note that when the user moves in a straight line, the geolocation points do not form a straight line, because the points I collect have a margin of error due to inaccuracy, thus I can't use something like Haversine formula because it will give incorrect value (longer distance than real distance)

and I can't use Google Maps Distance API because it calculates the distance between 2 points only, and it will be so expensive to call it 200 times to calculate distance through all points.

and I want to calculate this value on the server-side because of some security rules I have. so using the google maps SDK in the front end to calculate it is not an option either.

Any idea ...


Solution

  • for anyone facing the same problem,I have followed this link https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/roads/snap

    here is my code in PHP

    // snap the collected points from user to the nearest road using google API
    $fields = array(
        'path' => '60.170880,24.942795|60.170879,24.942796|60.170877,24.942796|60.170902,24.942654',
        'key' =>  '<YOUR_KEY_HERE>'
    );
    $url = "https://roads.googleapis.com/v1/snapToRoads?" . http_build_query($fields, '', '&');
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url );
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response  = curl_exec($ch);
    $response = json_decode($response);
    
    $totalDistance = 0;
    $previousPoint = null;
    foreach ($response->snappedPoints as $pointOnRoad) {
        if(!$previousPoint){
            $previousPoint = $pointOnRoad;
            continue;
        }
    
        $totalDistance += getDistance($pointOnRoad->location->latitude, $pointOnRoad->location->longitude,
                                      $previousPoint->location->latitude, $previousPoint->location->longitude);
    }
    
    echo $totalDistance;
    
    
    // calculate distance between 2 geo points
    function getDistance($latitude1, $longitude1, $latitude2, $longitude2) {
    
        $earth_radius = 6371;
    
        $dLat = deg2rad($latitude2 - $latitude1);
        $dLon = deg2rad($longitude2 - $longitude1);
    
        $a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * sin($dLon/2) * sin($dLon/2);
        $c = 2 * asin(sqrt($a));
        $d = $earth_radius * $c;
    
        return $d;
    }