I am struggling with getting post queries by coordinates. I have meta fields map_lat
and map_lng
for almost all post types. I am trying to return posts from one custom post type (“beaches” in this example):
function get_nearby_locations($lat, $long, $distance){
global $wpdb;
$nearbyLocations = $wpdb->get_results(
"SELECT DISTINCT
map_lat.post_id,
map_lat.meta_key,
map_lat.meta_value as locLat,
map_lng.meta_value as locLong,
((ACOS(SIN($lat * PI() / 180) * SIN(map_lat.meta_value * PI() / 180) + COS($lat * PI() / 180) * COS(map_lat.meta_value * PI() / 180) * COS(($long - map_lng.meta_value) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS distance,
wp_posts.post_title
FROM
wp_postmeta AS map_lat
LEFT JOIN wp_postmeta as map_lng ON map_lat.post_id = map_lng.post_id
INNER JOIN wp_posts ON wp_posts.ID = map_lat.post_id
WHERE map_lat.meta_key = 'map_lat' AND map_lng.meta_key = 'map_lng'
AND post_type="beaches"
HAVING distance < $distance
ORDER BY distance ASC;"
);
if($nearbyLocations){
return $nearbyLocations;
}
}
and im calling it with:
$nearbyLocation = get_nearby_cities(get_post_meta($post->ID, 'map_lat', true), get_post_meta($post->ID, 'map_lng', true), 25);
but it doesn’t return what I want.