Friday, September 24, 2010

Geo-Location using IP Address


Geo-Location using IP Address
Many web applications use IP address to find the geographical location of the web site visitors. It has uses from catering relevant advertisements to customizing the behavior of web site. Geo-location using IP address is normally done by using databases. There are two different options available: HostIP.info and MaxMind. HostIP.info has exposed its data through a web service. The access to the web service is free; however, the data is not very accurate. MaxMind offers both commercial solutions as well as free solutions. The free solutions also called the lite versions are not highly accurate but the commercial products are extremely accurate. The code presented in this article has been written to work with both MaxMind's database as well as HostIP.info's web service. The default is to use the HostIP.info. You can change the default, by setting NodeInfo.LocationService property.

//Use Maxmind's Getloaction
NodeInfo.LocationService = new Maxmind.NodeInfoLookupService();

//Use HostIP.info's Geolocation
NodeInfo.LocationService = new HostIP.NodeInfoLookupService();
The LocationService property is of the type INodeInfoLocationService which makes it easy to provide custom lookup services. In a later version the class name of the object to create can come from the configuration file. The INodeInfoLocationService is quite simple with just one method named Lookup.

bool Lookup(IPAddress address, NodeInfo nodeInfo);
The Lookup function takes an IP address and populates a NodeInfo object, which stores the latitude, longitude, city, region and the country name.

The HostIP.info web site exposes its API through HTTP GET at the URL: http://api.hostip.info/. For example, you can get the location of the IP address 207.12.0.9 using the following URL:

http://api.hostip.info?ip=207.12.0.9
The response is returned as XML. The XML gives the latitude, longitude, city, state and country. In the parser implemented in this article, the HTTP GET request is issued through the XMLDocument.Load method.

XmlDocument doc = new XmlDocument();
doc.Load(String.Format("http://api.hostip.info/?ip={0}", address));
The individual elements are extracted using XPath queries. For Example, the country name is extracted using the following query.

node = doc.SelectSingleNode("//hostip:countryName", manager);

if (node != null)
{
nodeInfo.Country = node.InnerText;
}
One element of detail to understand here is how namespaces works with XPath. The argument manager, passed to the SelectSingleNode method, is of type XmlNamespaceManager class. The namespace prefixes are indicated using the following code:

XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
manager.AddNamespace("gml", "http://www.opengis.net/gml");
manager.AddNamespace("hostip", "http://www.hostip.info/api");
The latitude, longitude, city and the state are extracted in the similar fashion using XPaths.

The MaxMind lookup service is much simpler. MaxMind provides source code of the library that can read its databases. The code can be downloaded from this URL: http://www.maxmind.com/app/api. The Maxmind.NodeInfoLookupService uses the LookupService class provided by MaxMind. I have only made minor changes to the MaxMind's code and most of the MaxMind's code is retained as it is. Here is the code for the wrapper around MaxMind's code.

LookupService svc = new LookupService(Path.Combine(
Path.GetDirectoryName(
this.GetType().Assembly.Location
),
"GeoLiteCity.dat")
);
Location loc = svc.getLocation(address);

if (loc != null)
{
nodeInfo.Region = loc.region;
nodeInfo.Longitude = loc.longitude;
}
You need to download and extract the GeoCity Lite database from MaxMind.com. The compressed archive of the database is available at the following URL: http://www.maxmind.com/app/geolitecity. The GeoLiteCity.dat must be placed in the same directory as the executable.

This was a brief description of the geo-location code. Now, let's examine how the Virtual Earth API is used in the code.

Using the Virtual Earth API
You can get the same mapping feature in your web applications as local.live.com using the Virtual earth API. The Virtual Earth API is JavaScript code and can be loaded in web pages by including a script:


Once the script is loaded, you can use Javascript classes available in the API. A comprehensive API reference is available at the following URL: http://dev.live.com/virtualearth/sdk/. Also, checkout the interactive SDK tutorial available at the same URL. To display the Virtual Earth map in your web page, you need to designate a
element where you want the map image to appear:


Next you will use some JavaScript to load the map into the designated element:

map = new VEMap("mapContainer");
map.LoadMap();
Notice that so far I have only talked about Virtual earth API as a web based API. Since Tracert Map is a windows application, the question arises: how can we use Virtual Earth in windows application? The answer is simple: host the Internet Explorer in the desktop application. Luckily, the .Net Framework 2.0 provides the WebBrowser control. We need to create an HTML page where we can place all the HTML, JavaScript and CSS and load this page into the hosted web browser. An HTML page named tracert.htm needs to be placed in the directory of the executable, so as to make the following code work:

mapBrowser.Navigate(Path.Combine(Path.
GetDirectoryName(
this.GetType().Assembly.Location
),
"tracert.htm")
);
The code shown till now is sufficient to display the Map, but we need to control the map from C# code. The JavaScript code in the web page also needs to invoke C# code. Luckily, the web browser control has a property called ObjectForScripting for this purpose. This property can be assigned any object, the only catch is that the class needs to be marked with the COMVisible attribute.

[ComVisible(true)] //So that scripts can access the methods
public partial class TracertMapForm : Form
A public method in the class declared as public void MapLoaded() can be accessed from JavaScript using window.external.MapLoaded() statement. This is how JavaScript can use C# code, but how about C# code invoking JavaScript? This can be done by using the InvokeScript function. For Example, the code: mapBrowser.Document.InvokeScript("OnStartTrace"); invokes the JavaScript function OnStartTrace declared as: function OnStartTrace. Now that we know how two way communication between script and C# code can be achieved, let's look at the details of virtual earth API.

We will be using Virtual Earth API to mark nodes on the map. This is called a pushpin in the Virtual Earth terminology. In order to do that we need the latitude and the longitude of the node which was obtained by the geolocation service. To display the pushpin we also need the URL of the image which will be used as pushpin. Images of numbers circled in red can obtained at the following URL: http://local.live.com/i/pins/RedCircleXX.gif, where XX can be replaced by a number. For Example the URL http://local.live.com/i/pins/RedCircle10.gif is the image representation of number 10 enclosed in a RedCircle. To represent the nth node as a pushpin in the map, we use the URL: http://local.live.com/i/pins/RedCircle{n}.gif where {n} is replaced by the actual number. Another, interesting feature of a pushpin is that when the mouse hovers over the pushpin it shows a popup as shown in the screenshot below.


The IP address is displayed in the bold text as the title of the popup and the DNS name in lighter text as the body of the popup. Virtual Earth API takes care of displaying the popup. All we need to do is to specify the popup title and the body when creating the pushpin:

var location = new VELatLong(nodeInfo.Latitude, nodeInfo.Longitude);
var imageURL = "http://local.live.com/i/pins/RedCircle" + hopNo + ".gif";
var pushpin = new VEPushpin(hopNo,
location, //pushpin latitude and longitude
imageURL, //pushpin image
nodeInfo.Address, //Pushpin title
nodeInfo.HostName //Pushpin body
);
map.AddPushpin(pushpin);
The final aspect of the Virtual Earth API which is used in the tool is that of polylines. As seen in the first screenshot the nodes on the map are connected through a blue line. This can be created by using VEPolyline JavaScript object. The code to create a transparent blue polyline through an array of latitude and longitude pairs, named nodes, is shown below:

var poly = new VEPolyline("route", nodes);
poly.SetWidth(2);
poly.SetColor(new VEColor(0, 0, 255, 0.5));
map.AddPolyline(poly);
Final Words
I have described briefly how the tool works and its various elements. The tool is still under development and there are lots of features that need to be added. Please note that the pushpins may not represent the locations accurately. This is because the HostIP.info as well as MaxMind lite databases are not highly accurate. The HostIP.info site allows you to correct its database and I recommend you to correct the database and further improve the excellent and free GeoIP database.


No comments:

Post a Comment