Empowering Web Creativity

Back to Education Center Home:  Go Back        Font size:  Smaller  Larger         Font weight:  Lighter  Heavier 

Web Services Made Practical: Where Are Your Visitors From?

by Nathan Rohler


What exactly is a web service? In simple terms, it's a website designed for machines instead of people. We humans (sorry, Googlebot!) expect an interactive, aesthetically-pleasing experience when we use a website; machines, on the other hand, expect nothing more than a system for sending and receiving data in machine-readable form. We use web browsers to consume websites; computers use scripting languages to consume web services. One web server can talk to another web server via a web service in order to generate better or more complete web pages.

Some web services are for communication (talking to other computers or humans), others are for manipulation (mixing and crunching data), and still others are for retrieving data (getting information that would be tough or impossible to get on your own). What are some examples?

  • Communication: Web services for making purchases or sending text messages.
  • Manipulation: GeoIP services that translate IP adresses into geographic locations.
  • Retrieval: Government information services that provide updates on legislative activity; Twitter services that provide tweets and other social data.

Real World, Please!

While this is the kind of stuff that makes developers drool, I realize it can seem a little arcane to the average Joe or Jane. So let's make it practical.

Suppose you run a Google search right now for "pizza" without being logged in to your Google account. You'll be shown a bevy of pizza joints near where you live. Did you tell Google where you live? Nope. Did your web browser tell you where you live? Nope – at least not directly.

In this situation, all Google has is the IP address associated with the request your computer sent. Each group of IP addresses is owned or leased by an ISP or web host in a certain country, and this information is publicly available. Within these groups of addresses, individual blocks are often allocated geographically, meaning that an IP address of e.g. 123.45.xxx.xxx could be translated to Cucamonga or some other delightful area of the globe. Not all IP blocks can be traced directly to a state or city (and mobile devices can generate misleading results), but at least the country will always be available.

Google uses whatever information they do have to tailor your experience. If you type www.google.com into your browser in South Korea, for example, you'll be whisked to www.google.co.kr instead. If you search for pizza from a land-based internet connection, you'll be shown local pizza parlors.

How Can *I* Get this Wonderful Data?

How does one translate IPs into geographic locations? Well, you need a large GeoIP database that aggregates all of the information about which IPs correspond to which locations.You can roll your own, but it costs money to buy detailed (e.g. city-level) IP mapping information, and these mappings change regularly as IPs are transferred, allocated and re-allocated.

Enter the concept of a GeoIP web service. With this, we can let a dedicated service provider worry about aggregating and maintaining the complex database. Retrieval of geographic information requires nothing more than an IP address and a snap of the virtual fingers. Programming time, maintenance time and project complexity are all cut back.

A Real Project

Map pin

Let's apply this with a simple real-world project. We're going to create a webpage that determines the visitor's country and uses that information to display his or her country's flag. To do this, we first need to select a GeoIP web service. Both commercial and free options are available; we'll use a free one, FreeGeoIP.net, for this demo. While the pricetag means that the data isn't quite the freshest and may not be 100% accurate beyond the country level, it will certainly suffice for our needs.

The service offers several different formats, but we'll be using JSON (short for JavaScript Object Notation). This format allows for data structures to be passed as a simple string over the web, then re-assembled into a data structure in the receiving JavaScript code.

The service can be queried for any IP address, but we only need information about the current visitor's location. For this, no IP address needs to be passed. To see the data that's available for your current IP, load this URL in Chrome or Firefox:


You'll see something like this:

{"city": "Mountain View", "region_code": "CA", "region_name": "California", "metrocode": "807", "zipcode": "94043", "longitude": "-122.057", "latitude": "37.4192", "country_code": "US", "ip": "", "country_name": "United States"}

We will be using the jQuery JavaScript library to load this data into our page and process it. If you're not up to speed on JavaScript or jQuery, review Eloquent JavaScript and jQuery Fundamentals, two excellent and free eBooks linked in this article.

Building the Page

To start, create a new HTML file:

<html lang="en-US">
    <meta charset="UTF-8">
    <title>Where in the World Are You From?</title>


Next, let's add some CSS and markup for displaying the flag. We're going to use this freely-licensed flag set that's available on GitHub – it's a quick way to display flags based on just the country code. First, add this CSS to the page's <head>:

<link rel="stylesheet" type="text/css" href="http://cloud.github.com/downloads/lafeber/world-flags-sprite/flags32.css" />
<style type="text/css">
body {
   font: 13px/16px Arial,sans-serif;
#flagIcon {
   vertical-align: -11px;

Then, in the <body>, add this code:

<div class="f32">
   <i id="flagIcon" class="flag"></i> Thanks for visiting us from <span id="countryName"></span>!

To make a flag actually appear, we have to add the country code as a class to the <i> element. For example, to display Australia we need:

<i id="flagIcon" class="flag au"></i>

We'll use jQuery to add the appropriate class. We'll also update the #countryName div (id="countryName") with the actual name of the visitor's country, yielding e.g. Thanks for visiting us from Canada!

The JavaScript

Here's the code to add before the closing </body> tag:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$.get('http://freegeoip.net/json/', function(data)
// Get the country code and name
var countryCode = data.country_code.toLowerCase();
var countryName = data.country_name;

// If "United States", fix grammar to make it "the United States"
if (countryName == 'United States')
countryName = 'the United States';

// Now, update the interface
}, 'jsonp');

Before the primary JavaScript block, we include the jQuery library. The main JavaScript code is executed when the document is ready. It begins with a jQuery.get call to the FreeGeoIP web service. This method, one of the most simple yet powerful ones in jQuery, allows a page to retrieve all manner of data via AJAX or JSONP requests. (JSONP is a special approach for delivering JSON-formatted content; it allows for circumvention of browser restrictions against loading content via AJAX from one site to another. The final 'jsonp' paremeter tells jQuery that we will be loading in this format.) Within the load handler, we update the display via the addClass and text methods.

You can preview your page now; you'll see something like this:

Finished screenshot

Each visitor to the page will see their own flag and country name displayed. If your page doesn't work as expected, compare your page's source code against the demo page's source code to check for errors.

If you're ready for a "homework" assignment, try to update the JavaScript to also display the region_name value (this is the state name in the US).

Next Steps

You can also use GeoIP data to display localized text or image content for certain visitors. Suppose, for example, you wanted to display a Thanksgiving greeting on your site; running a GeoIP query would allow you to only show the greeting to US and Canadian visitors.

More generally, this article has shown you how fun and easy it can be to integrate web services into your projects. A few lines of code allow access to great amounts of information, opening up a world of possibilities. Look for more web service-related tutorials in the future!

Tell Others and Have Your Say

Customizable Google Maps Made Easy! Try EasyMapBuilder Now »
Log In
  Reset Password...
Why create an account?
  • Manage support tickets and purchases
  • Access to free extensions
  • Special discounts and offers
  • Access to member-only forums
Create Account
100% Spam-Free Guarantee

Use the following form to ask a question or submit a support request. An appropriate staff member will reply as soon as possible (usually within a few hours).
Contact Us / Create Support Ticket
To attach files, you must Sign Up or Log In.

You have no items in your basket.  Featured products:

XML Flash Slideshow v4 Flash Audio Kit for Dreamweaver

Home | Customer Satisfaction / Refund Policy | Privacy Policy | jQuery Slider | Top of Page

© 2003-2018 DWUser.com / Magnetic Marketing Corp.  All rights reserved.