Are you a member? Register or Login

Detecting Location Using Google AJAX API

mapThere are times when one needs to find out which part of the world a particular visitor is coming from. There are plenty of IP-to-Location lookup providers out there, who offer this service at a reasonable cost (depending on how much detail you require).

Google’s AJAX Maps API offers this look up for you free of cost (so long your needs are non-commercial). You can even use the latitude and longitude information returned by the API to plot the user’s location on a Google Map. Nifty eh? Let’s now look at a simple example – we will be detecting the user’s location based on his IP address and rendering it on a map.

Before we begin, you might want to check out the demo.

The Ultimate Designer Toolkit: 2 Million+ Assets

Envato Elements gives you unlimited access to 2 million+ pro design resources, themes, templates, photos, graphics and more. Everything you'll ever need in your design resource toolkit.

Explore Envato Elements

You will first need to obtain an AJAX Search API Key (it’s free, just sign up using your domain name, and you will be given a unique key, which is applicable for all pages hosted within your domain). Once you have that ready, fire up your favorite editor. We don’t need any server side code to be able to use the Maps API – so a plain HTML document is enough.

First, let’s place the “hooks” in the page, where the map and a caption will appear.

The Google AJAX API consists of a collection of individual APIs. By using a

The load function above takes the API name, its version and an optional callback function (which is called once the Maps API has finished loading) as parameters. In the init() function, we will first define a default location to be displayed on the map, in case the Maps API is not able to decode the IP address of the visitor. Since the Maps API basically matches the user's IP address to a location, there might be instances when this mapping is not possible, and hence the need for a default.

Next, we check if the client location was filled in by the API loader. If properly filled, the google.loader.ClientLocation object has the following properities:

  • ClientLocation.latitude
  • ClientLocation.longitude
  • ClientLocation.address.city
  • ClientLocation.address.country
  • ClientLocation.address.country_code
  • ClientLocation.address.region

Using this information, we can easily load a map, centred on the user's location.

That's it, see it in action. As I have already stated above, the client location information returned by this API is not perfect, as IP mapping can often be tricky, and might result in incorrect, or partially accurate information. While you should consider going for an enterprise ready solution for serious uses, I hope this API will be handy for your personal needs!