Your own database with geo located ip information

 

For those who wants to serve content based on viewers location, one good alternative is IP geolocalization, when the viewer or the aplication ins’t integrated with GPS.

There are some libs that we can use to geo locate viewers with IP information:

http://www.geoplugin.com
http://www.maxmind.com

Those applications doens’t offer 100% accurated information but they are a good start point. Let’s create our own Geo Database using MaxMind CityLite free Database.

First, download the CSV file from MaxMind Web Site:

http://www.maxmind.com/app/geolitecity

Then, we need to create 2 tables:

CREATE TABLE `geo_blocks` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`location_id` INT(10) UNSIGNED NOT NULL,
`ip_start` INT(10) UNSIGNED NOT NULL,
`ip_end` INT(10) UNSIGNED NOT NULL,
`index_geo` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (`id`),
INDEX `idx_start` (`ip_start`),
INDEX `idx_end` (`ip_end`),
INDEX `idx_geo` (`index_geo`)
);

CREATE TABLE `geoip`.`location` (
`locId` INT NOT NULL ,
`country` VARCHAR( 100 ) NOT NULL ,
`region` VARCHAR( 100 ) NOT NULL ,
`city` VARCHAR( 150 ) NOT NULL ,
`postalCode` VARCHAR( 20 ) NOT NULL ,
`latitude` VARCHAR( 10 ) NOT NULL ,
`longitude` VARCHAR( 10 ) NOT NULL ,
`metroCode` VARCHAR( 100 ) NOT NULL ,
`areaCode` VARCHAR( 100 ) NOT NULL ,
PRIMARY KEY ( `locId` )
) ENGINE = MYISAM ;

After that, you need to import the CSV files to the mysql:

load data local infile '/pathe/to/the/file/GeoLiteCity_20110802/GeoLiteCity-Blocks.csv'
into table geo_blocks
fields terminated by ',' enclosed by '"'
lines terminated by '\n' ignore 2 lines (ip_start, ip_end, location_id);

load data local infile '/pathe/to/the/file/GeoLiteCity_20110802/GeoLiteCity-Location.csv'
into table location
fields terminated by ',' enclosed by '"'
 lines terminated by '\n' ignore 2 lines (locId,country,region,city,postalCode,latitude,longitude,metroCode,areaCode) ;

That’s all, use it as you want :)

MaxMind has a small tutorial teaching how to use the CSV file also:
http://www.maxmind.com/app/csv

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>