How to query posts based on lat-lng coordinate as post meta?

I’m planning a custom WordPress theme where the Custom Post Type (CPT) will have latitude and longitude coordinate as it’s meta value. The latitude and longitude will be displayed as a Marker in a Google Map.

So far I don’t have any problem in showing the Google Map and the CPT as it’s Marker. That is if I query the CPT using the default order.

The problem occurs when I need n CPTs that is closest to a coordinate whether it is current user position or a location clicked on the map. Another situation is to query all CPTs that is in x km radius of a coordinate.

The question is : How do I query posts based on latitude-longitude value that is saved on the post meta?

I’m not really sure how to do it, but I think the latitude and longitude value should be saved in a separate custom field.

Thank you in advance.

4 s
4

This is a simple mathimatical problem.
You will indeed need access to both your longitude and latitude, so save it in a metafield.

than you will have to query your posts like this as a sql query.
Haven’t got a chance to test it. and or pour it into wordpress.
Don’t have access to my test env now.
But I guess you could do it yourself 🙂 if not I’ll do it later on when I can.

set @latitude = xxx; — center latitude
set @longitude = xxx; — center longitude
set @distance = xx; — search distance

select p.ID, p.post_name, ((ACOS(SIN(@latitude * PI() / 180) * SIN(`latitude.meta_value` * PI() / 180) + COS(@latitude * PI() / 180) * COS(`latitude.meta_value` * PI() / 180) * COS((@longitude – `longitude.meta_value`) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS distance
from wp_posts p
left join wp_postmeta latitude on latitude.post_id = p.ID and latitude.meta_key = ‘_latitude’
left join wp_postmeta longitude on longitude.post_id = p.ID and longitude.meta_key = ‘_longitude’
having distance < @distance;

Leave a Comment