The Archives

SEARCH

About There4

I build simple, clean, and maintainable internet applications. People should never need an owners manual to use software, I believe that applications can be easy to use while still being powerful. Applications should remain valuable through their entire lifespans, and should be flexible enough to grow and change as requirements shift.

I prefer to develop with Blueprint CSS, jQuery, and Cake PHP. I have extensive development history with PHP, MySQL, Microsoft SQL, and mixed Win32/Linux hosting environments.

Follow me on Twitter

Posting tweet...

Archive for March, 2010

Geolocation services with jQuery and IPInfoDB

Posted in: Blog, JavaScript, PHP by Craig Davis on March 18, 2010

I’m releasing a simple script that uses jQuery and a small proxy script to deliver location services via jQuery. You can see a simple example.

Geolocation with IPInfoDB

Requirements

Code and explanations

By placing this at the jQuery level it prevents any page blocking that may occur during loading, and the proxy script prevents any cross site scripting problems.

First, the javascript variables , with a small bit of PHP:

var ip = "<?php print $_SERVER['REMOTE_ADDR'];?>";
var geolocation = "./ip_proxy.php";
var cookiename = 'geo_location';
var cookieoptions = { path: '/', expires: 10 };

These variables setup the path to the proxy script, place the users IP address into a javascript variable, and establish our cookie parameters. Next, we setup our page initialization function:

$(function(){

  fetchlocation();

});
displaylocation = function(location) {
  if (location.Status == 'OK') {
    $('.city').text(location.City);
    $('.zip').text(location.ZipPostalCode);
    if(location.State != '--') {
      $('.state').text(location.State);
    } else {
      $('.state').text(location.RegionName);
    }
  }
}

fetchlocation = function() {
  // look in the cookie for the location data
  cookiedata = $.cookie(cookiename);
  if ('' != cookiedata) {
    locationinfo = $.evalJSON(cookiedata);
    if ((locationinfo != null) && (locationinfo.IP == ip)) {
      displaylocation(locationinfo);
      $.cookie(cookiename, cookiedata, cookieoptions);
      return;
    }
  }
  // it's not in the cookie, so fetch from the server
  $.getJSON(
    geolocation, {
      'timezone' : 'false', // set this to false to save the service 2 queries
      'ip'       : ip
    },
    function(data) {
      data.IP = ip;
      displaylocation(data);
      cookiedata = $.toJSON(data);
      $.cookie(cookiename, cookiedata, cookieoptions);
    }
  );
}

PHP code

The PHP code is well documented within the ip_proxy.php file. It acts as an intermediary between the jQuery script, and the IP producer. Note that the file can restrict based on hosts, and adds an extra State abbreviation variable to the data returned by the IPInfoDB API