A couple of months ago we launched a new website with a footer that included the closest airport to our visitors and people went crazy about it!
Here's how it looks like:
This was something I had a ton of fun stitching together - so I thought about sharing the process and details around how I made this
To build this we needed 3 main components:
- Finding the location of our visitors
- Finding the coordinates of the biggest airports in the world
- Calculate the closest airport to our users
Finding the location of our visitors
What I needed to find the closest airport was some approximate longitude and latitude coordinates.
It was very surprising to learn that there are very cheap APIs to get the location of an IP address.
I found that IP Api provides pretty reliable outputs so I decided to use that.
So this part of the problem was figured out.
Finding the location of our visitors
Now that I had a way to get the coordinates of our visitors, the next step was getting a list of coordinates for airports around the world with their IATA airport code.
I had to look around the internet to find a good list, but I couldn't find anything that was extensive enough for my needs.
So I decided to build our own dataset of 100 airports around the world.
As I was googling airports and appending them into a .csv file, Github Copilot started suggesting airport coordinates.
So I ended up using Cursor's AI autocomplete to add rows in my CSV, so that I didn't even have to Google the coordinates of the airports I was looking for.
Within 15 minutes I had my list of 100 airports in 71 countries:
Finding the closest airport to our customers
The last step was to find the closest airport to our customers using their coordinates.
Using the haversine formula one can quickly get the approximate distance between two points on Earth.
I was pleasantly surprised to learn that Ruby has a library that includes every trigonometry function you need to write a function that calculates the distance between two coordinates.
Here's the implementation:
I then looped through all the airports in my list and pick the closest one and was surprised to see that it was good enough to ship! It turns out that computers are really fast at doing math and no further optimisation is required for my use-case.
The result is rendered in a JSON and displayed it on the site.
Conclusion
I think this is the kind of small things that you can build that can make you really feel the magic of the internet and programming.
As we launched the site, it was great to see that a lot of people were also enthusiastic and delighted about this small detail on our website.
I can't wait to do more and keep having fun with the next things we build.