Getting Visitor's Location using JavaScript

Recently, I've been trying to get Google Maps to work behind the Great Firewall of China. Google recommends using the http://maps.google.cn/ endpoint instead of the usual https://maps.googleapis.com/. But I was reluctant to do so because visitors accessing the site from outside China might experience a slower load time.

So is there a way to know where the visitor is from? There are two ways:

  • Geolocation API
  • IP Geolocation services
  • JavaScript library

Geolocation API

You can use the getCurrentPosition() method provided by the Geolocation API to obtain a Position object. The Position object itself contains a Coordinates object that gives the latitude, longitude, and altitude, amongst others.

// From https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition#Example
var options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};

function success(pos) {
  var crd = pos.coords;

  console.log('Your current position is:');
  console.log('Latitude : ' + crd.latitude);
  console.log('Longitude: ' + crd.longitude);
  console.log('More or less ' + crd.accuracy + ' meters.');
};

function error(err) {
  console.warn('ERROR(' + err.code + '): ' + err.message);
};

navigator.geolocation.getCurrentPosition(success, error, options);

There are two major downsides to this:

  1. For security reasons, the browser would have to request permission from the visitor to approve the usage of Geolocation. Apart from being annoying, users can set their browser to instantly reject all such requests.
  2. If you need to obtain an address, city, or country from those geo-coordinates, you'd have to do more work and use a Reverse geocoding service.

    Google

    Google provides a Google Maps Geocoding API which supports Reverse geocoding. But if make the request from China, this might not work.

    GeoNames

    GeoNames is the other more commonly-used service, which provides many different options for reverse geolocation.

    Texas A&M University Department of Geography

    Texas A&M University Department of Geography offers GeoServices, which includes a reverse geolocation service.

    It is free but can get a bit cumbersome if you make many requests, as you'd have to submit online forms to refill your quotas.

IP Geolocation

A better way is to use a free IP Geolocation service. They provide APIs that returns information about the user's location based on their IP address.

As of 30 December, all sites below can be accessed from within China, as tested using WebsitePulse's tool.

freegeoip.net

freegeoip.net is community-funded. It provides the CSV, XML and JSON formats, and provides a quota of 10000, which is unlikely to be reached by your client. Supports IPv4 and IPv6.

Like any other service, it can go down. However, it is open-source so you can run your own instance of the service yourself.

ipinfo.io (Recommended)

ipinfo.io is the other big name apart from freegeoip.net. It allows 1000 daily requests for free, with paid plans available.

As an edge over freegeoip.net, as it supports specifying the field itself in the query URL, which returns exactly what you're looking for without further processing.

$.getJSON('http://ipinfo.io/8.8.8.8/org', function(data){
    console.log(data); // AS15169 Google Inc.
})
Telize

Telize is similar to freegeoip but not as popular, and has since been taken down by the author due to abuse. Like freegeoip.net, it is open-source, so you can download the source code and run your own instance. Supports IPv4 and IPv6.

geoPlugin

geoPlugin provides a very comprehsive set of data, including currency. It returns data as either a JavaScript function, a Serialized PHP, XML, or JSON.

ip-api

ip-api supports the XML, JSON, CSV Newline Separated and Serialized PHP formats. It's limited to 150 requests per minute, and not allowed to be used commercially without approval.

Hostip.info

For completeness's sake - Hostip.info. Don't use it. It's unreliable.

MaxMind

geoPlugin, infoip.io and Hostip.info all use the GeoLite database of MaxMind as a source. So you can build your own service based on the database.

There are other databases out there, such as IP2Nation, but MaxMind seems to be the most accurate and up-to-date.

MaxMind also provides more accurate services through a paid plan. So if this is a critical part of your site and you need accurate information, using MaxMind's paid offerings might be the way to go.

JavaScript Libraries

There are many libraries that uses/wraps the Geolocation API; for reasons stated above, I do not recommend this and thus will only tell you about one popular library - onury/geolocator.

comments powered by Disqus