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:

geoip2-js-api-flowchart

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 geoip2.country(onSuccess,¬†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.

Examples

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:

<script src="//js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js" type="text/javascript"></script>

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.

var redirect = (function () {
    /* This implements the actual redirection. */
    var redirectBrowser = function (site) {
        var uri = "http://" + site + ".example.com/";
        window.location = uri;
    };

    /* These are the country codes for the countries we have sites for.
     * We will check to see if a visitor is coming from one of these countries.
     * If they are, we redirect them to the country-specific site. If not, we
     * redirect them to world.example.com */
    var sites = {
        "de": true,
        "fr": true,
        "gb": true,
        "us": true
    };
    var defaultSite = "world";

    var onSuccess = function (geoipResponse) {
        /* There's no guarantee that a successful response object
         * has any particular property, so we need to code defensively. */
        if (!geoipResponse.country.iso_code) {
            redirectBrowser(defaultSite);
            return;
        }

        /* ISO country codes are in upper case. */
        var code = geoipResponse.country.iso_code.toLowerCase();

        if ( sites[code] ) {
            redirectBrowser(code);
        }
        else {
            redirectBrowser(defaultSite);
        }
    };

    /* We don't really care what the error is, we'll send them
     * to the default site. */
    var onError = function (error) {
        redirectBrowser(defaultSite);
    };

    return function () {
        geoip2.country( onSuccess, onError );
    };
}());

redirect();

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:


<!doctype html>
<html>

  <head>
    <title>Fictional Animal Shelters of the World</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
    <script src="//js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js"></script>
    <script>
      <!-- INCLUDE JAVASCRIPT HERE -->
    </script>
  </head>

  <body>
    <p>
      Hello, and welcome to Fictional Animal Shelters of Minnesota. If you're
      looking to adopt a new companion animal, we'd love to help you.
    </p>

    <p id="city"></p>

    <p>
      <a href="/about">Learn more about our work</a>.
    </p>

  </body>
</html>

Here is the JavaScript that fills in the city paragraph.


var fillInPage = (function () {
    var updateCityText = function (geoipResponse) {

        var link = "/shelter?lat=" + geoipResponse.location.latitude;
        link += "&lon=" +geoipResponse.location.longitude;

        /* It's possible that we won't have any names for this city */
        var cityName = geoipResponse.city.names.en || 'your city';

        /*
           most_specific_subdivision returns the smallest available
           subdivision (region) as defined in ISO 3166-2.
        */
        var regionName = geoipResponse.most_specific_subdivision.names.en;

        var cityHTML =
            '<a href="' + link + '">Find a great companion near '
            + cityName;

        if (cityName && regionName ) {
            cityHTML += ', ' + regionName;
        }
        cityHTML += '</a>.';

        $("#city").html(cityHTML);
    };

    var onSuccess = function (geoipResponse) {
        updateCityText(geoipResponse);
    };

    /* If we get an error we will */
    var onError = function (error) {
        return;
    };

    return function () {
        geoip2.city( onSuccess, onError );
    };
}());

fillInPage();

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.

* Latitude and longitude are not precise and should not be used to identify a particular street address or household.