Let’s assume you are setting up a store locator or distance search system on WordPress. The client provided you with a spreadsheet of companies that you’ve already imported to a post type. The spreadsheet included business name, phone numbers, and the address.
Along the way you’ve realized the address alone will not work for putting a pin on Google Maps, or calculating the miles between a visitor’s zip code and the business address. You need the Latitude and Longitude, too, which your client probably does not have.
This tutorial will provide some code and explanation on how you can (mostly) automate Google’s GoeCoding API to get the latitude and longitude of addresses.
I’ll be honest – I don’t want to provide you a wordy explanation of every line of code like other websites. If you’re a developer you’ve probably already skimmed through looking for the code to copy. So let’s get right to it!
- Grab my script from Gist and upload it to your theme.
- Configure the options in the variable $ld_recalc. You need to set the post type, and set the different field keys or names.
- Include the file at the top of your functions.php script:
- Visit your site with this url parameter on the end of the url, such as:
- You should see a results screen like this, or some helpful errors if any settings are incorrect.
- Review one of the updated locations to ensure the map location looks correct.
- Refresh the page again to continue scanning locations. Note: Google Maps API will prevent you from scanning too quickly.
- Every time you visit the URL from Step 4, it will scan a certain amount of locations. If the lookup fails or it can’t save the results, it will abort at its current position. When you run it again, it will repeat the scan from the item that failed.
- When a scan is successful, the lat/lng is saved to the given google_map field as well as to custom fields named “latitude” and “longitude”.
- If you need to re-scan items that have already been scanned, just change the scan_identifier.
This information was originally published on the Advanced Custom Fields forums in 2015. It has been mysteriously deleted by a moderator.
great help here, thanks mate!!