June 5, 2016

WordPress Radius Calculation For Store Locator using Google Map



H
ave you ever had a chance work on the store locator project? Where you have to display the store using Google Map in given radius from the user's position (or say latitude longitude of user)? 
I recently had work on store locator project, Where in I have to customize the store locator functionality made using WordPress. 

The situation get worse when I found that the latitude and longitude of the store is stored in the `wp_meta`! This makes it more complex to calculate the distance of the stores.
After so much time spend in searching and thinking how to best fit the Google Map Distance calculation query with meta key and value format, I figure out the solutions. 

The solution was to not to use the lat, long meta data in the Google Map Distance calculation query for two reason.
  1. Its overwhelmingly complex to use meta value in Google Map Distance calculation query, (I know you know it, right?)
  2. The query will be incredibly slow while fetching the data, that will ultimately make your website look slow.

But, At the same time I cannot change the way lat and long are stored. 

The Solution I adopted was to use separate table for the lat long processing. 

This is comparatively very easy than earlier solution (with no change in current flow, off course). 

All I have done is to just use "save_post" hook and written code to save the post value in custom table. 

Like the example given below.
Write this code at the end of  `function.php` or you can make your own plugin (recommended).


Then you can apply the following query to get the store id for the given distance from the users latitude and longitude.

To search by kilometers instead of miles, replace 3959 with 6371 in the query.

That's it, thats all you need. Your store search should be working by now.

Do you find this article helpful? Don't forget to give your comment below.
Cheers.
GautamArya

Kindle Apps