As a member of the Facebook group Advanced WordPress I see a lot of interesting conversations coming by. Today I came across an interesting post from Fabrizio about setting up a relationship between a custom post types based on geographical locations.
I am not sure why, but I researched a bit about this topic a while ago, and remembered there actually is a formula to calculate the distance between two different GEO locations. As this was somewhere in the back of my mind, it soon sparked to become an interesting topic for me to find out.
The question from Fabrizio
Hello,
I’need to create relationships between some custom post type / contents based on their geographic position.
In example in the page Mario’s Restaurant (Florence) i have to be able to see a short list called “Other restaurants near this place” or “Other attractions near this place”.
Do you have any suggestions?
Thank you,
Fabrizio
What I’ve come up with
I started to develop a mini plugin, just to demonstrate how something like this could be done. In my demo plugin, I will calculate the distance between three Apple stores (Amsterdam, Hong Kong and New York). I’ve inserted a static latitude and longitude value of the starting position (the tip of Greenland, to keep it exciting which one will be closest :-p).
With a simple [closest_apple_store] shortcode you can display a little text saying which Apple store is closest by, and how far away it is.
The code
The result
As simple as the demo plugin is, its result is also very simple;
Tips
Of course there needs to be done A Lot of work before this is a full size workable plugin. Here are some tips to keep in account;
- Cache the result, although it is not slow at calculating, its better to cache the distance results.
- Save multiple locations In context of the question, you might want to save multiple locations instead of just returning the one closest by.
- Test with Amsterdam – I added some coordinates of Amsterdam too, just so you can test it out some more. Uncomment those coordinates at lines 43/45 to test it.