I am working on a project for myself whereby I am trying to search users within the WordPress database based on postcode/zip and radius but the code which I'm using takes forever to load and results in a timeout error even though there are only about 200 users. I am quite stumped by this so I am hoping someone out there can lead me in the right direction. Here is the code I have currently:
$url = "=".urlencode($_GET['postcode'])."&sensor=false&key=MY-API-KEY";
$result_string = file_get_contents($url);
$result = json_decode($result_string, true);
if(!empty($result['results'])){
$orig_lat = $result['results'][0]['geometry']['location']['lat'];
$orig_lon = $result['results'][0]['geometry']['location']['lng'];
}
$center_lat = $orig_lat; //insert the lat of where you are
$center_lng = $orig_lon; //insert the lng of where you are
$radius = $_SESSION['postcode_radius']; //insert the radius of KM that you want to search
$multiplier=3959; //miles
$multiplier=($multiplier*1.609344); //use km instead
$users = get_users( array( 'fields' => array( 'ID' ) ) );
//now we got all our users that have latitude (i assume they also have longitude ^^)
$nearbyusers = array();
foreach($users as $user){
$lat = get_user_meta($user->ID,'lat',TRUE); //assuming the user latitude is a meta field named "latitude"
$lng = get_user_meta($user->ID,'lng',TRUE); //assuming the user longitude is a meta field named "longitude"
$distance = ( $multiplier * acos( cos( deg2rad($center_lat) ) * cos( deg2rad( $lat ) ) * cos( deg2rad( $lng ) - deg2rad($center_lng) ) + sin( deg2rad($center_lat) ) * sin( deg2rad( $lat ) ) ) );
if($distance<$radius) {
$nearbyusers[] = $user;
}
}
print_r($nearbyusers);
Any ideas on this and why it doesn't work as expected?
Thanks!