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

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