I've recently started working with Google Maps API and I need to turn the distance calculations into a function so that it can be used anywhere in my code but I have no idea on how to do that...
This is how the distance calculations are made:
$keyApi = 'xxxxx';
// Hidden value for safety reasons
$origin = $adresscep;
$destination = $deliverycep;
$url = 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=' . $origin. '&destinations='. $destination .'&mode=driving&language=en-US&sensor=false&key=' . $keyApi;
$ch = curl_init($url);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER , array( 'Accept: application/json' ) );
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $url);
$result = curl_exec( $ch );
$result = json_decode( $result, true );
$distanceCalculation = $result['rows'][0]['elements'][0]['distance']['value'];
// Returns INT in meters.
$remains= (double)$distanceCalculation%1000;
if($distanceCalculation<=1000) $distanceCalculation=1000;
// Below or equal to 1000m makes $distanceCalculation = 1000
if($remains>=500) {
// Above 500m in decimals, rounds it up to next INT value
$distanceCalculation= $distanceCalculation/1000;
$distanceCalculation= ceil($distanceCalculation);
$distanceCalculation*=1000;
}
else {
// Below 500m in decimals, rounds it up to previous INT value
$distanceCalculation= $cdistanceCalculation/1000;
$distanceCalculation= floor($distanceCalculation);
$distanceCalculation*=1000;