Get geographical location (geolocation) by IP address using jQuery

Today I came across this post called “IP Address Geolocation Javascript API : JSON”. The author provides you with a free geolocation query URL. The API returns the geographical location of the queried IP address with some additional information such as:

{
       
'status':'ok',
       
'IP': '74.125.45.100',
       
'CountryCode': 'US',
       
'CountryName': 'United States',
       
'RegionName': 'California',
       
'ZipPostalCode': '94043',
       
'City': 'Mountain View',
       
'Latitude': '37.4192',
       
'Longitude': '-122.057'
}

// In case of an error
{
       
'status':'parent server not responding'
}

Update: the URL has been changed!

The JSON geolocation querying API’s address is:

http://iplocationtools.com/ip_query.php?output=json&ip=80.80.214.93

The URL above is dead, instead use this one:
http://www.geoplugin.net/json.gp?jsoncallback=?

And the great thing is, you can identify your website visitor’s IP and Geo location by simply querying the API without any parameters like this:

http://iplocationtools.com/ip_query.php?output=json

Knowing your users’ IP and/or location, you might add a behavior to your website that is specific to some location. For example, offering some advertising to US only visitors, or popup with special offer to European users.

Anyway, here is a sample jQuery code to query the API:

// Build the URL to query
var url = "http://iplocationtools.com/ip_query.php?output=json&callback=?&ip=";

// Utilize the JSONP API
$
.getJSON(url, function(data){
   
if(data['status'] == 'ok'){
       
// Do something with the data
        $
('#profile #ip')
           
.append(data['IP']);
        $
('#profile #country')
           
.append(data['CountryName']);
   
}
});

Here we are not specifying any IP address in the url variable that is why it is getting current user’s data.