Home › Forums › Front-end Issues › WP Query closest locations by ACF Google Map values › Reply To: WP Query closest locations by ACF Google Map values
So, I posted a response with the solution but the site seems to have deleted it. Here it is again:
John, thanks for the response. You were correct in your assessment. Unfortunately WP Google Maps was not possible for this project, although I do use that plugin frequently (it’s great).
My Coworker Steve was able to solve this particular issue for me. I’ll post that solution below:
So the goal here was to display an archive of the closest 3 locations on the single page of the custom post type in question. Each post is using the ACF Google Map field and has associated Google Map data.
in functions.php (or mu-plugin):
function get_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);
$dist = $dist * 60 * 1.1515;
return $dist;
}
In the custom post type single page:
<?php
$current_post = get_the_ID();
$location = get_field('map_pin'); // Adjust to your Google Map field name
$current_post_lat = $location['lat'];
$current_post_long = $location['lng'];
$query = new WP_Query( array(
'post_type' => 'post-type-name',
'posts_per_page' => -1,
'post__not_in' => array($current_post)
)
);
$post_1_dist = 100;
$post_1 = "0";
$post_2_dist = 101;
$post_2 = "0";
$post_3_dist = 102;
$post_3 = "0";
while ($query->have_posts()) : $query->the_post();
$location = get_field('map_pin');
$dist = get_distance($current_post_lat, $current_post_long, $location['lat'], $location['lng']);
if ($dist < $post_1_dist){
$post_3 = $post_2;
$post_3_dist = $post_2_dist;
$post_2 = $post_1;
$post_2_dist = $post_1_dist;
$post_1 = get_the_ID();
$post_1_dist = $dist;
}
if (($dist < $post_2_dist) && ($dist > $post_1_dist)){
$post_3 = $post_2;
$post_3_dist = $post_2_dist;
$post_2 = get_the_ID();
$post_2_dist = $dist;
}
if (($dist < $post_3_dist) && ($dist > $post_1_dist) && ($dist > $post_2_dist)){
$post_3 = get_the_ID();
$post_3_dist = $dist;
}
endwhile; wp_reset_postdata(); ?>
//Results
<?php echo get_the_title($post_1); ?>
<?php echo get_the_title($post_2); ?>
<?php echo get_the_title($post_3); ?>
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.