使用php中的纬度和经度计算两点之间的道路距离

Below is the code I have used

function distance($lat1, $lon1, $lat2, $lon2, $unit) {

    $theta = $lon1 - $lon2;
    $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
    $dist = acos($dist);
    $dist = rad2deg($dist);
    $miles = $dist * 60 * 1.1515;
    $unit = strtoupper($unit);

    if ($unit == "K") {
        return ($miles * 1.609344);
    } else if ($unit == "N") {
        return ($miles * 0.8684);
    } else {
        return $miles;
    }
}

But it provides distance on fly and not by road. For ex: The function returns 2km as answer between two points but when checked the actual distance between those two area on google it returns 10km which is right.

Using google api I could able to find distance between two points. Just need to create http request URL and all done

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, 
        'http://maps.googleapis.com/maps/api/directions/json?origin=add_source&destination=add_destination&sensor=false'
    );
    $content = curl_exec($ch);
    echo $content;

It returns json response which also includes distance.