Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

132
Views
Creating a function from API response

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;
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!