Geolocation In Web Applications: What It Does

Geolocation
Geolocation In Web Applications: What It Does

After developing a web app, there are various uses of geolocation. Like for statistical purposes and special cases like dynamically changing a user’s language when he/she migrates. Geolocation is a method of guessing a user’s location by looking at his/her IP address.

The IP address and geolocation

The IP addresses are the telephone numbers of the world wide web. They are usually a set of numbers separated by dots. An example is 212.45.683.23. Institutions obtain IP addresses in blocks. A particular IP address with 45.160, in the beginning, is one out of the IP address block belonging to Brazil. Pretty sure, this user is living somewhere in Brazil. Even more, IP address blocks are sold, transferred, and reallocated due to various factors.

Methods to implement IP-based geolocation

Commercial institutions like MaxMind provide large databases that map IP addresses at different levels of granularity (city, state, country of residence). One can download the database at a one-time fee. However, as stated above, IP address blocks change configurations frequently. So in order to maintain accuracy, one has to pay MaxMind for weekly or monthly database updates. You have to put technical effort to integrate the database and update it regularly (weekly/monthly).

Another option is to use a commercial service that offers geolocation as a service. You have your own web app, you send your visitor’s IP address to the API of the service. The service then replies with the visitor’s location and you can particularly customize the visitor’s experience.

A basic Python program featuring geolocation

Here is a Python web application written in 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 initializes 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 addresses.
  2. The request module we imported above handles the client connection requests (with an s), it is a completely different library that allows our server to make HTTP calls to third-party services. We’ll use this later to call the ip-api service.
  3. We initialize the app variable as a Flask web application and call app.run() right at the end of the script to make Flask listen to 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. USfor 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.

Consequently, it is possible to initiate a similar function in other languages designed for web applications and complex websites.

Other options and limits in IP-based geolocation

Geolocation is not 100% accurate. Generally, a web app should duly account for a user who has an IP address different from his/her real location. If your web application behaves differently in different countries, it is good to have flexibility in overriding location.

Other ways to track a visitor’s location are:

  • Using DNS host to find out the approximate location. Services like GeoDNS find the DNS host nearest to the visitor, and we can infer their estimated location.
  • We can find out a visitor’s location by locating the nearest cellphone towers and WiFi routers. Google has a geolocation API that offers these services.
  • Smartphones and some laptops come with a technology called GPS (Global Positioning System), which tracks the person within a few meters of his/her exact location (permission is required in the newer mobile operating systems).

Therefore we have now understood how to use geolocation in web apps.