On my Locations Template page, the location section is shown, and then below in a separate section, I want to show 3 x of the —nearest— locations to the currently shown Location Item.
Hey Craig, I feel like I answered this somewhere yesterday. Facebook maybe?
You have two good options here;
The simple approach is to create a multiref field and manually set the 3 nearest for each location.
If you really want it automated, you’ll have some scripting work to do, the approach is;
Determine your reference location lat & long
In a collection list, list all other locations with their lat & long ( I put these as custom attributes so they’re easily accessible ).
On page load, run a script that calculates distance as-the-crow-flies, and sets it as a 3rd custom attribute on those items.
Sort the list, shortest distance to longest
Limit the list to 3
Note, I usually hide the list on page load, and then unhide it after the script runs, so the user has a more elegant experience.
Also, if you have more than 100 items you’ll need multiple collection lists. If you have thousands, you may do better with an AJAX-style approach and a server-side API.