Website Visitor Dashboard

The Website Visitor Dashboard takes IP Address log information and converts it into geographic data. An analytics software product could use this code to display where website visitors are located.

APIs used

Download the code

website-visitor-dashboard.zip

App Overview

  1. Constructing the query: Infochimps Digital Element IP Intelligence Geolocation API Request
  2. Rendering the geolocation results in a table
  3. Rendering the geolocation results on a map

1. Constructing the Query: Infochimps Digital Element IP Intelligence Geolocation API Request

Our example Rails app has one controller and a twos view for displaying results. The visitordashboard controller has two methods: table which displays our results in a table and map which display our results on a Google Map.

The API call requires an API_KEY and ip. Here is our constructed query we use for each IP address in the visitordashboard_controller:

/app/controllers/visitordashboard_controller.rb

  require 'open-uri'

class VisitordashboardController < ApplicationController

  # Your Infochimps API Key
  API_KEY = 'XXXXXXXXXXXXXXXXXXX'  

  # A hash of IP addresses that recently visited our website
  IPADDRESSES = %w{ 67.78.118.7 199.4.18.2 74.9.83.42 204.244.193.106 166.205.138.190 63.98.59.239 128.135.100.112 24.9.104.151 199.73.71.5 76.181.77.57 }

  # Use the Infochimps Digital Element IP Intelligence Geolocation API
  # Render the results in a table
  # localhost/visitordashboard/table
  def table 
    @table = []    

    IPADDRESSES.each do |ip|
      query = 'http://api.infochimps.com/web/analytics/ip_mapping/digital_element/geo?apikey=' + API_KEY + '&ip=' + ip

Example JSON response

  {
  "city": "austin",
  "region": "tx",
  "latitude": 30.2716,
  "zip": "78745",
  "country_code": 840,
  "country": "usa",
  "zip_country": "usa",
  "in_dst": "n",
  "area_code": 512,
  "city_code": 73,
  "postal_code": "78701",
  "continent_code": 6,
  "region_code": 44,
  "gmt_offset": -600,
  "two_letter_country": "us",
  "conn_speed": "cable",
  "internal_code": 9,
  "longitude": -97.7419,
  "metro_code": 635,
  "zip_code_ignored": 78745
}

For the code above to work, you will have to replace the API_KEY variable with your Infochimps API key.

2. Rendering the geolocation results in a table

Our first method table retrieves the latitude, longitude, city, region, and zip for each example IP address and places the results in the @table array. We receive these values from the Infochimps Digital Element IP Intelligence Geolocation API. After retrieving results for each IP address, we present the results in a table view.

/app/controllers/visitordashboard_controller.rb

  def table 
  @table = []    

  IPADDRESSES.each do |ip|    
    query = 'http://api.infochimps.com/web/analytics/ip_mapping/digital_element/geo?apikey=' + API_KEY + '&ip=' + ip
    buffer = open(query).read
    result = JSON.parse(buffer)
    @table << [ip, result['latitude'], result['longitude'], result['city'], result['region'], result['zip'] ]          
  end

  render 'visitordashboard/table'
end

The @table array is then displayed in the table view.

/app/views/visitordashboard/table.html.erb

  <table>
  <thead>
    <tr>
      <th>IP address</th>
      <th>Longitude</th>
      <th>Latitude</th>
      <th>City</th>
      <th>Region</th>
      <th>Postal Code</th>
    </tr>
  </thead>
  <tbody>
    <% @table.each do |t| %>
      <tr>
        <td><%= t[0] %></td>
        <td><%= t[1] %></td>
        <td><%= t[2] %></td>
        <td><%= t[3] %></td>
        <td><%= t[4] %></td>
        <td><%= t[5] %></td>  
      </tr>  
    <% end %>
  </tbody>
</table>

To view the results of this method, start your Rails server and point your browser to http://localhost:3000/visitordashboard/table.

3. Rendering the geolocation results on a map

Our second way to display geolocation results is to place them as latitude and longitude markers on a map. We will use the Google Maps JavaScript API to create a map and place markers for each result on the map.

In the initialize() JavaScript function, we create a Google map and then request data for the markers using the jQuery $.post('/visitordashboard/mapdata', function(data) method.

/app/views/visitordashboard/map.html.erb

  <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
  html { height: 100% }
  body { height: 100%; margin: 0; padding: 0 }
  #map_canvas { height: 100% }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
<script type="text/javascript">
  function initialize() {
    var latlng = new google.maps.LatLng(38.26, -97.73);
    var myOptions = {
      zoom: 4,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    //Initialize the map
    var map = new google.maps.Map(document.getElementById("map_canvas"),
    myOptions);

    //Add markers to the map!     
    $.post('/visitordashboard/mapdata', function(data) {      
      for (var i = 0; i < data['results'].length; i++) {      
        var content = '<strong>' + data['results'][i]['city'] + ', ' + data['results'][i]['region'] + '</strong><p>' + data['results'][i]['latitude'] + ', ' + data['results'][i]['longitude'] + '</p>';        
        addMarker( data['results'][i]['latitude'], data['results'][i]['longitude'], data['results'][i]['city'], content );        
      }
    });

when the $.post('/visitordashboard/mapdata', function(data) is called, our app requests data from mapdata. mapdata retrieves the same data as the table method, but places instead of placing the results in an array, we place the results in a hash named @data.

/app/controllers/visitordashboard_controller.rb

  # Use the Infochimps Digital Element IP Intelligence Geolocation API
# Provide data for map method
def mapdata
  @data = { 'results' => [] }

  IPADDRESSES.each do |ip|    
    query = 'http://api.infochimps.com/web/analytics/ip_mapping/digital_element/geo?apikey=' + API_KEY + '&ip=' + ip
    buffer = open(query).read
    result = JSON.parse(buffer)
    @data['results'] << { 'ip' => ip, 'latitude' => result['latitude'], 'longitude' => result['longitude'], 'city' => result['city'], 'region' => result['region'], 'zip' => result['zip'] }
  end

  render :json => @data
end

We render the results in JSON, which our JavaScript code will use to add markers to the map.

/app/views/visitordashboard/map.html.erb

      //Add markers to the map!     
    $.post('/visitordashboard/mapdata', function(data) {      
      for (var i = 0; i < data['results'].length; i++) {      
        var content = '<strong>' + data['results'][i]['city'] + ', ' + data['results'][i]['region'] + '</strong><p>' + data['results'][i]['latitude'] + ', ' + data['results'][i]['longitude'] + '</p>';        
        addMarker( data['results'][i]['latitude'], data['results'][i]['longitude'], data['results'][i]['city'], content );        
      }
    });

    function addMarker(lat,lng,city,content) {      
      var myLatlng = new google.maps.LatLng(lat,lng);
      var marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        title: city      
      })        
      var infoWindow = new google.maps.InfoWindow({
        content: content        
      })      
      google.maps.event.addListener(marker, 'click', function() {
        infoWindow.open(map, marker);        
      });      
    }    
  }
</script>
</head>

<body onload="initialize()">
  <div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html> 

Point your browser to http://localhost:3000/visitordashboard/map to see the map in action!