如何在循环中处理多个距离矩阵API请求,以减少负载和请求时间?

时间:2018-03-23 作者:Sarvesh Verma
if ($query->have_posts()) : 
    while ($query->have_posts()) : $query->the_post();

 $school_address =str_replace(\' \',\'+\',$school_address );

     $school_address =str_replace(\',\',\'\',$school_address);

      $zipcodeaddress =str_replace(\' \',\'+\',$zipcodeaddress );

     $zipcodeaddress =str_replace(\',\',\'\',$zipcodeaddress);


    $fare = file_get_contents(\'https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=\'.$school_address.\'&destinations=\'.$zipcodeaddress.\'&key=KEY\');
//here im making api request in loop which is taking to long to load 
// what will be the best solution to calculate the distnace in loop.... correcponting to ther office address

    $data = json_decode($fare);
    $data = (array)$data;

    $result = (array)$data[\'rows\'][\'0\'];
    $result = (array)$result[\'elements\'][\'0\'];

    $distance = (array)$result[\'distance\'];
    $duration = (array)$result[\'duration\'];

    $distance = str_replace(\'mi\', \'\', $distance);
endwhile;
endif;
1 个回复
SO网友:Sarvesh Verma

I need to pass the lat and long for two address    
函数calculate\\u distance($lat1,$lon1,$lat2,$lon2,$单位){

  $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;
      }
}

echo calculate_distance(32.9697, -96.80322, 29.46786, -98.53506, "M") . " Miles<br>";

结束

相关推荐