Mapping your website visitors

This is a short tutorial on how I learned to map my website visitors by IP address and how you can do it too.

To do this you will need PHP, MySQL (or another database), and a Google Map API key.

First sign up for your Google Map API key at http://www.google.com/apis/maps/. When you are done, copy the key and the code for the basic google map and paste both in a text editor. You will need the key to use Google Maps on your site and the basic code will be useful for later if you ever want to do your own tweeks.

Then set up a table in your database called "GoogleMarkers" that has the following fields: IP, longitude, latitude, city, state, country.

Ok, you're half way there. Next, create a new PHP file called "tracker.php" and add the following code:

<?
// Connection Strings for MySQL
$username = "YOUR USERNAME";
$password = "YOUR PASSWORD";
$hostname = "localhost";
$dbConnect = mysql_connect($hostname, $username, $password) or die("Unable to connect to the Database, please try again.");
mysql_select_db("YOURDATABASENAME") or die(mysql_error());

// Check to see if we already have the location of this visitor's IP
$theSQL = "select * from GoogleMarkers where IP = '".$_SERVER['REMOTE_ADDR']."'";
$ipResults = mysql_query($theSQL) or die(mysql_error());
$ipCount = mysql_numrows($ipResults);
if ($ipCount == 0) {
  // New Visitor, get the location of their IP
  $data = file("http://geo.localsearchmaps.com/?by_ip=1&cb=IpLookup&ip=".$_SERVER['REMOTE_ADDR']);
  foreach ($data as $line) {
    $line = str_replace('IpLookup(', '',$line);
    $line = str_replace('alert(\'', '',$line);
    $line = str_replace('\');', '',$line);
    // If data is available, add it to our database
    if ($line != "ip address not found") {
      $line1 = explode(',',$line);
      $latitude = $line1[0];
      $longitude = $line1[1];
      $city = $line1[2];
      $city = str_replace('\'', '',$city);
      $state = $line1[3];
      $state = str_replace('\'', '',$state);
      $country = $line1[4];
      $country = str_replace('\'', '',$country);
      $theSQL = "insert into GoogleMarkers (IP, longitude, latitude, city, state, country) values ('".$_SERVER['REMOTE_ADDR']."','".$longitude."','".$latitude."','".$city."','".$state."','".$country."')";
      mysql_query($theSQL) or die(mysql_error());
    } else {
      // No data available, store IP anyway so we don't overload the localsearchmaps.com server with duplicate requests
      $theSQL = "insert into GoogleMarkers (IP, longitude, latitude, city, state, country) values ('".$_SERVER['REMOTE_ADDR']."','0','0','unknown','unknown','unknown')";
      mysql_query($theSQL) or die(mysql_error());
    }
  }
}
?>
	
Replace the "YOUR USERNAME", "YOUR PASSWORD" and "YOURDATABASENAME" with the correct info for your MySQL database.

Now we have a way to save the IP info for all of our site visitors, so let's include this on any page we want to track by adding

<? include("tracker.php"); ?>
to the PHP code of the page.

Then create a new PHP page called "markers.php" and add the following PHP code:

<?
header('Content-Type: text/xml');
// Connection Strings for MySQL
$username = "YOUR USERNAME";
$password = "YOUR PASSWORD";
$hostname = "localhost";
$dbConnect = mysql_connect($hostname, $username, $password) or die("Unable to connect to the Database, please try again.");
mysql_select_db("YOURDATABASENAME") or die(mysql_error());
echo "<markers>\n";
$theSQL = "select * from GoogleMarkers where longitude <> \"0\" order by longitude";
$kmlResults = mysql_query($theSQL) or die(mysql_error());
$kmlCount = mysql_numrows($kmlResults);
for ($i = 0; $i < $kmlCount; $i++) {
  if (mysql_result($kmlResults,$i,"city") != "unknown") {
    echo "  <marker lat=\"".mysql_result($kmlResults,$i,"latitude")."\" lng=\"".mysql_result($kmlResults,$i,"longitude")."\"/>\n";
  }
}
echo "</markers>\n";
?>
	
This will generate the XML file of all of our markers on the map.

Now open the page where you want our Google Map to appear and insert your map code. In the <head> section of your page add:

<script src="http://maps.google.com/maps?file=api&v=2&key=YOUR_GOOGLE_MAPS_API_KEY" type="text/javascript"></script>
<script type="text/javascript">

//<![CDATA[
function load() {
  if (GBrowserIsCompatible()) {
    var map = new GMap2(document.getElementById("map"));
    map.addControl(new GSmallMapControl());

    // Uncomment the next line to add Satellite & Hybred buttons
    //map.addControl(new GMapTypeControl());

    // You can play with the coordinates to adjust your map's starting location
    map.setCenter(new GLatLng(39, -97), 4);

    // Setting up your marker icon
    var icon = new GIcon();
    // Add the URL of your marker images below (21px X 22px is a good size)
    icon.image = "YOUR_MARKER_IMAGE_URL";
    icon.shadow = "YOUR_MARKER_SHADOW_URL";
    icon.iconSize = new GSize(21, 22);
    icon.shadowSize = new GSize(21, 22);
    icon.iconAnchor = new GPoint(9, 10);

    // This is where our markers are loaded. Adjust the location of the markers.php file as needed
    GDownloadUrl("markers.php", function(data) {
      var xml = GXml.parse(data);
      var markers = xml.documentElement.getElementsByTagName("marker");
      for (var i = 0; i < markers.length; i++) {
        var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
        map.addOverlay(new GMarker(point, icon));
      }
    });
  }
}
//]]>
</script>
	
Replace "YOUR_GOOGLE_MAPS_API_KEY" with... your api key. Then create two small images as your map markers. The images should be about 21x22 pixels in PNG format. Make them whatever you want. The shadow image is just a second PNG that is a "shadow" of the main image, to create this just open Photoshop and choose "Filter>Blur>Gaussian Blur..." and set the radius to around 4. Then choose "Image>Adjustments>Hue/Saturation..." and adjust the Saturation to -100. Save as the shadow image and upload both images to your website.

Now in your <body> tag edit it to look like: <body onload="load()" onunload="GUnload()">. and add <div id="map" style="width: 750px; height: 400px"></div> somewhere in the body of your page where you want your map to appear. You can adjust the height and width of the <div> to change the size of your map to fit your site's design.

Finally, go check our your page and see how your map works. Adjust things as needed for appearance and watch your site's traffic grow!

Special thanks to Emad Fanous for the geocoding data. If you get a chance be sure to visit his blog and tell him "Thanks!".