使用Haversine公式根据用户位置显示帖子


Displaying post based on users location using the Haversine formula

我有一个名为"event"的自定义帖子类型,它具有带有纬度和经度的acf。我绑在与帖子相关的所有"事件"的距离我使用 geoplugin.com 来获取用户 Lat & long。

$geoplugin  = unserialize( file_get_contents('http://www.geoplugin.net/php.gp?ip=' . $_SERVER['REMOTE_ADDR']) );
    $geoiix    = $geoplugin['geoplugin_regionName'] ;
    $user_lat  = $geoplugin['geoplugin_latitude'];
    $user_long = $geoplugin['geoplugin_longitude'];
    $artist_id  = $tags[0]->term_id;
    $args = array(
        'post_type' => 'events',
        'orderby' => 'meta_value',
        'meta_key' => 'event_date',
        'tag__in' => array( $artist_id ),
         );
      $my_query = new WP_Query($args);
      if ($my_query->have_posts()) : while ($my_query->have_posts()) :
      $my_query->the_post();
       $event_lat  = get_field( 'gp_latitude' ); 
       $event_long = get_field( 'gp_longitude' ); 
       $earth_radius = 3960.00; # in miles
       $lat_1 = $event_lat;
       $lon_1 = $event_long;
       $lat_2 = $user_lat;
       $lon_2 = $user_long;
       $delta_lat = $lat_2 - $lat_1 ;
       $delta_lon = $lon_2 - $lon_1 ;
     function distance_haversine($lat1, $lon1, $lat2, $lon2) {
      global $earth_radius;
      global $delta_lat;
      global $delta_lon;
      $alpha    = $delta_lat/2;
      $beta     = $delta_lon/2;
       $a   = sin(deg2rad($alpha)) * sin(deg2rad($alpha)) + cos(deg2rad($lat1)) *           cos(deg2rad($lat2)) * sin(deg2rad($beta)) * sin(deg2rad($beta)) ;
      $c        = asin(min(1, sqrt($a)));
      $distance = 2*$earth_radius * $c;
      $distance = round($distance, 4);
      return $distance;
    }
     $hav_distance = distance_haversine($lat_1, $lon_1, $lat_2, $lon_2);
     echo $hav_distance;
     ?>

这段代码正在破坏其显示 1 结果,我似乎无法弄清楚原因。我想也许高级自定义字段插件不是存储经度和经度的最佳方式。

你的函数在你的循环中...每次它运行时,您都会重新声明引发PHP错误的函数(您可能关闭了PHP错误)

将 haversine 函数定义放在函数文件中。