GeoIP2 JavaScript Tutorial

For API details, see our GeoIP2 JavaScript Client API documentation.

Application Flow

The MaxMind GeoIP2 JavaScript API is an asynchronous API. That means that the application flow is based on callbacks. You provide a function to be called when a particular event happens, rather than receiving a response directly from an API call.

Here is a flowchart that illustrates your application flow when using this API:


Click on the image for a larger version.

The steps are as follows:

1. Load the GeoIP2 JavaScript API

Your web page loads the API from the MaxMind server.

2. Your code calls an API method

You call one of the API’s public methods, such as,¬†onError). You should provide two functions. The first, onSuccess, will be called when the API has a geolocation to provide. The second is called for all errors. The possible error conditions are outlined below.

3. MaxMind web service is called
4.a. MaxMind web service returns a successful response

Your onSuccess callback is called with the response from the MaxMind web service.

4.b. MaxMind web service returns an error response

Your onError callback is called with the error from the MaxMind web service.


All examples are written using the JavaScript module pattern in order to limit the scope of the variables and functions they define.

The examples assume that you have loaded the geoip2.js from the MaxMind server:

Redirect Users to a Country-Specific Site

One use for the GeoIP2 JavaScript API is to redirect users to a country-specific site. While this can also be done at the server level, you may not always have control over the server, especially in a shared hosting situation. You can use the country API to do this.

When you call redirect(), the browser will ultimately be redirected to an appropriate country-specific site or the default site.

Put the User’s City Name in a Page

Although we use jQuery in this example, you do not need jQuery to use the GeoIP2 JavaScript API.

Another common use for the GeoIP2 JavaScript API is to dynamically add the user’s city to some text on a page. For our example, we’ll assume that we are a non-profit running multiple animal shelters around the state. We will update some text and links on the page so that the text mentions the user’s city and the links go to the nearest shelter’s page.

Here is the HTML we will work with:

Here is the JavaScript that fills in the city paragraph.

If we wanted to be more sophisticated, we could use the location.latitude and location.longitude values to find the nearest shelter location, and simply ignore users more than a certain distance away from the nearest shelter.