How Geolocation Works to Calculate Distances on c4rt.uk
If you’ve had a play around with my shopping cart builder c4rt, you would have seen that I have given it the ability to restrict distances on orders people make and I wanted to write a little post explaining how all that works because I think it’s pretty cool.
I could have used the Google distance matrix API to complete these calculations but that would have meant calling the Google API to get the physical location of each address, and then make another call to calculate the distance and when I was first playing around with this software I found that you can make a lot of requests in a very short amount of time. I wanted to keep the costs as low as possible and as such, figured out a way of achieving this result but only having to make the one request per customer.
I use the postcode and country that each user puts in to send a request to the Google Geocoding API which returns the co-ordinates for that location. I find it really cool how you can get someone’s exact co-ordinates just from those two bits of information.
Anyway, once the customer inputs their address, it is then compared to the shop owners and the distance between the two points is calculated. I’ve included the calculations below just in case you find this stuff interesting.
The Haversine formula (returning the distance) is:
Where R is the Earth’s radius, φ is latitude & λ is longitude.
The function takes 4 inputs, lat1, lat2, lng1 and lng2 and returns the distance (d) which is then used to decide whether or not to let the transaction take place or not on the front-end website.
// in metres
// Obviously, I’m not actually that clever so I didn’t come up with all this stuff on my own and basically got a working version of the code from the Movable Type Scripts website but I just wanted to put it up here anyway.
To save cost even further, say a customer were to reorder again, when they login next the system will whiz them past the inputting address fields and go straight to the order confirmation page where they can then click the “edit” button to change their address if they wish to. The system will only make a call to get the co-ordinates if the address is different to the one in memory otherwise it will reuse the original co-ordinates. The difference this made, just in testing numbers alone was a change to from 6,000 API requests over a month, down to 140 requests over a month with the same amount of usage.
If you’d like to play around with this (and also a whole lot more) then feel free to create yourself a free account on my platform and create some test transactions using various configurations of settings. You can do that by visiting c4rt.