Track visitors using Google Maps

Create a table in your database, like 'visitor_map'. We will have these fields: id, ref, ip, location, longitude and latitude, execute the following code:

CREATE TABLE IF NOT EXISTS `visitor_map` ( `id` int(11) NOT NULL auto_increment, `ref` varchar(255) NOT NULL, `ip` varchar(15) NOT NULL, `location` varchar(32) NOT NULL, `longitude` float NOT NULL, `latitude` float NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;

For ease of use, we'll now create a configuration file. Create a file called config.php and insert the following, changing the constant values to suit your database setup and Google Maps API key.

define('DB_HOST', 'localhost'); // Database host define('DB_NAME', 'Database'); // Database being used define('DB_USER', 'user'); // Database user define('DB_PASS', 'password'); // Database user's password /* Your Google Maps API key */ define('API_KEY', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'); function IPtoCoords($ip) { $dom = new DOMDocument(); $ipcheck = ip2long($ip); if($ipcheck == -1 || $ipcheck === false) trigger_error('Invalid IP, what are you doing? :|', E_USER_ERROR); else $uri = 'http://api.hostip.info/?ip=' . $ip; $dom->load($uri); $location = (strpos($dom->getElementsByTagName('name')->item(1)->nodeValue, 'Unknown') === false) ? $dom->getElementsByTagName('name')->item(1)->nodeValue : $dom->getElementsByTagName('countryAbbrev')->item(0)->nodeValue; if($location == 'XX') return false; else { $dom->load('http://local.yahooapis.com/MapsService/V1/geocode?appid=' . Yahoo_Key . '&location=' . $location); $longitude = $dom->getElementsByTagName('Longitude')->item(0)->nodeValue; $latitude = $dom->getElementsByTagName('Latitude')->item(0)->nodeValue; return array('location' => $location, 'longitude' => $longitude, 'latitude' => $latitude); } }

Now that we can successfully gain the visitor's location, we can use this to build our finished visitor map.

Visitors map

Now paste this code to /templates/your_skin_dir_name/main/main.tpl and index.tpl

{php} require 'config.php'; mysql_connect(DB_HOST, DB_USER, DB_PASS); mysql_select_db(DB_NAME); $ref = $_SERVER["HTTP_REFERER"]; $ip = $_SERVER['REMOTE_ADDR']; $userinfo = IPtoCoords($ip); $user = mysql_query('SELECT `location` FROM `visitor_map` WHERE `location` = '' . $userinfo['location'] . '''); if(!mysql_fetch_row($user) && $userinfo) mysql_query('INSERT INTO `visitor_map` (`ref`, `ip`, `location`, `longitude`, `latitude`) VALUES ('' . mysql_real_escape_string($ref) . '', '' . mysql_real_escape_string($ip) . '', '' . $userinfo['location'] . '', ' . $userinfo['longitude'] . ', ' . $userinfo['latitude'] . ')') or die(mysql_error()); {/php}

06.07.2009. 09:21


Comments

rupali 14.09.2009. 05:01

i am using the same code but gettng an error like the fun iptocoords is not valid

Write a comment

* = required field

:

:

:


1 + 6 =