Adding Geolocation to Your Web App

When you build a web application, it’s useful to know where on the globe people are located. Either for general statistical purposes (e.g. 40% of sales came from France this month) or for specific cases (e.g. this visitor comes from France, so dynamically change the website's greeting from Hello to Bonjour).

There are various ways to automatically guess where your visitors are coming from, but none of them are 100% reliable. One common way is to look at your visitor's IP address and perform IP Geolocation, which involves using their IP address to guess the location.

In this post, we'll look at IP-based Geolocation in depth and explain the different ways it can be implemented. We'll provide a minimal Python web application that can guess the location of its visitors and conclude by looking at some other Geolocation strategies.

Understanding IP addresses and geolocation

IP addresses usually consist of four groups of numbers, separated by full stops. An example IP address is 165.165.219.54. These addresses can be thought of as the telephone numbers of the world wide web. Similarly to how you might know your friend's name but need to look up their phone number in your contacts, you probably also know google.com but not Google's IP address, 216.58.223.14. When you type google.com into your web browser, the browser looks up Google's IP address in a large global database that matches domain names, google.com, to IP addresses, 216.58.223.14. Then the browser visits the server identified by that IP address. If you want, you can copy that IP address into your web browser and you should be directed to the Google homepage.

IP addresses are assigned to institutions in blocks. The Internet Assigned Numbers Authority (IANA) can assign IP address blocks to various regions, who can, in turn, assign these blocks of IP addresses to governments or other institutions such as universities, ISPs, or large businesses. For example, any IP address that starts with 41.61 is part of a IP address block that belongs to South Africa. So if your visitor's IP address starts with 41.61, you can be fairly sure that they are in South Africa.

However, IP address blocks also get sold, transferred and reallocated based on various factors. In order to guess locations from IP addresses, it's necessary to keep up with all of these changes. Various databases and online services track these changes and map an IP address to the geographical location. Let's take a look at some of these options:

Understanding different IP geolocation services

If you want to add IP-based geolocation to your web application, the two primary options to consider are:

​ a) downloading a large database that maps IP address to locations, or

​ b) integrating an online API that provides IP-based geolocation as a service.

Both options usually offer free-tier usage, depending on your need for scale and accuracy.

Downloading a database of IP geolocation information

Commercial institutions, such as MaxMind, provide large databases that map IP addresses at different levels of granularity (e.g. to determine the city, country, or continent of your visitor). One can download the database for a one-time fee and integrate this into your web application. However, as mentioned above, IP address blocks change hands fairly frequently, so for good accuracy, one would need to pay MaxMind for weekly or monthly updates of the database. This approach would also require non-trivial technical effort to integrate the database and to install the updates regularly.

Using IP-based Geolocation as a service via an API

There are dozens of commercial services that offer geolocation as a service. Using this method, you program your own web application to send your visitor's IP address to the API of these services. The service replies with the location of that IP address, and you can adjust that particular visitor's experience appropriately. We cannot offer a thorough comparison of all services here, but two examples, both which have a free tier, are:

  • ipstack: This requires you to sign up and get a unique API key beforehand. The free tier limits you to 10000 requests per month.
  • ip-api: This does not require an API key and has a free tier which includes 150 requests per minute.

Beyond IP-based geolocation, another powerful tool in the arsenal of app developers is geofencing. Geofencing uses GPS or RFID technology to create a virtual geographic boundary. Through geolocation as a service, it enables software to trigger a response when a mobile device enters or exits a particular area. This functionality opens a realm of possibilities for personalized user experiences.

An app can send push notifications to users' devices when they enter a predefined geographic region. For instance, retailers can switch an app to 'in-store' mode. This can allow them to offer special deals and personalized shopping experiences when a customer approaches the store.

Writing a proof of concept web application

With the above information, let's take a look at how we might write a very basic and naive web application that is location aware.

The following shows a minimal Python web application written with the Flask web framework.

from flask import Flask 
from flask import request

import requests

app = Flask(__name__)

def get_country(ip_address):
    try:
        response = requests.get("http://ip-api.com/json/{}".format(ip_address))
        js = response.json()
        country = js['countryCode']
        return country
    except Exception as e:
        return "Unknown"

@app.route("/")
def home():
    ip_address = request.remote_addr
    country = get_country(ip_address)
    # number of countries where the largest number of speakers are French
    # data from http://download.geonames.org/export/dump/countryInfo.txt
    if country in ('BL', 'MF', 'TF', 'BF', 'BI', 'BJ', 'CD', 'CF', 'CG', 'CI', 'DJ', 'FR', 'GA', 'GF', 'GN', 'GP', 'MC', 'MG', 'ML', 'MQ', 'NC'):
        return "Bonjour"
    return "Hello"

if __name__ == "__main__":
    app.run()

Let's break down what it does and how it works:

  1. We import the main Flask module, which initialises our script as a web application. We also import the request module from Flask, which will allow us to get various data about our visitors, including their IP address.
  2. The request module we imported above handles the client connection requests (with an s), it is a completely different library which allows our server to make HTTP calls to third-party services. We’ll use this later to call the ip-api service.
  3. We initialise the app variable as a Flask web application and call app.run() right at the end of the script to make Flask listen for visitors and serve the web pages.
  4. The get_country function takes in an IP address, calls the ip-api service and extracts the ISO two-letter country code (e.g. US for the United States, DE for Germany) from the response that IP-API sends us. This response includes a bunch of other information that ip-api can guess from the IP address, but we’re only interested in the country code for now.
  5. Flask uses the @app.route("/") decorator to map specific URLs to specific functions in our code. In this case, the default "/" route is what will automatically trigger when a visitor loads our site.
  6. Our home function finds the visitor's IP address (this can get more complicated, but it should work in many cases), passes it along to our get_country function, checks whether or not the user is from a country where the majority of residents speak French, and returns Bonjour or Hello based on this.

Of course, a real web application would do other things than simply detect the visitor's country and return a greeting, but this example shows a minimal location-aware web application. It should be possible to adapt this example to any other language that is designed for web applications and to integrate similar functionality into larger and more complex web sites.

Looking at alternatives and limits to IP-based geolocation

As we discussed earlier, IP-based geolocation is not 100% accurate. Your application should gracefully account for cases where the user is using an IP address that is not associated with their true location. Similarly, international travel is as popular as ever, so it's important to think about the fact that, for example, an American tourist in France might not appreciate that you automatically translate your entire website to French because of his IP address, leaving him no option to view the site in English.

In general, it's good to provide sensible defaults and allow your users to override their location manually if your web application behaves differently in different countries.

If you do need more reliable location information about your visitors there are some other methods to investigate, too. While looking up IP addresses in large databases can provide an approximate position, one alternative is that the user's location can be calculated dynamically by looking at which DNS host services the user’s request. Services like GeoDNS will find the DNS host nearest to the user and thereby, infer their approximate location. Similarly, it is possible to triangulate the user's location with cellphone towers or wifi routers the user is closest to. Google provides a Geolocation API that uses these techniques.

Finally, more and more devices — such as phones and some laptops — now contain GPS chips, allowing web and mobile applications to track users within a few meters of their exact location (this often requires explicit permission from users beforehand). Functionality to do this is now included directly within HTML5.

Hopefully, you have a better idea of how to add geolocation to your web app after this article. If you have any questions or comments, leave them down below.

Last updated on Nov 24, 2023