image
author

William Dawson

Full Stack Developer

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.

geolocation in mobile apps

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 address.
  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 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. 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 web sites.

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 finds 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 track the person within a few meters of his/her exact location (permission required in the newer mobile operating systems).

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

How useful was this post?

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Please do Rate Us and Share!

Related Blogs

  • author
    Adam Davidson

    8 Best Examples of Data Science in Finance

    Data science in finance is aimed at extracting knowledge from a huge amount of data by employing mathematics and statistics. And many different techniques are employed to achieve this goal as good research leads to better outcomes leading to a profit for financial institutions. Data science has become extremely relevant in finance sector, which...

  • author
    Kela Casey

    Best Angular Projects for Beginners 2020

    Presenting the best angular projects for beginners list that will prepare you well with the basics and practical needs in angular development. Mentioning your experience in Angular projects can make your resume stand apart from other candidates. Angular Projects for Beginners Soundnode Notepad application Data binding in forms Customer service manager Angular Bare bones project Angular...

  • author
    Kela Casey

    Best Python IDEs & Code Editors for 2020

    In this post, we’ll discuss what is an IDE/ Code editor, the difference between IDE & Code editors, and some of the best Python IDEs & code editors, along with their best features. Python is a multi-faceted programming language that has been embraced globally with open arms. Python comes with innumerable useful features of...

image

About The Author

William is a CTO and a full-stack engineer with 10 years of experience. He has spent the past seven years doing web and mobile apps. He’s good at designing architecture and implementing agile development process. The technologies he’s worked with include: Node.js, Elixir, Rails, AngularJS, React, React Native, Objective-C, iOS, Java, Android. He’s also familiar with C++, Haskell, C#/.NET. He is an enthusiastic programmer and a great guy to know

Try our One-Week Risk Free Trial for Hiring a Coder

Know more Hire a Coder