Obtaining the Visitor's Location

This article is written for an old version of the Virtual Earth platform. While still available for reference purposes, it is unlikely to work if implemented.

In this tutorial I'll explain how you can obtain the location of the visitor viewing your page. I used this technique in my MapStats application.

Normally, you'd need to have a huge database to map ip addresses to their corresponding coordinates. However, obtaining such a database and keeping it updated can be quite hard. That's why we'll want to use another method.

We'll make something much like the 'Locate me' function at the official Virtual Earth website. We'll even be using the same webservice!

The locate me function gets its information from this URL: http://virtualearth.msn.com/WiFiIPService/locate.ashx.

This file outputs something like:

SetAutoLocateViewport(51.533333, 5.983333, 10, false, 'Virtual Earth has determined your location by using your computer\'s IP address.');

This is very useful information. We can now use this page by simply creating our own SetAutoLocateViewport function. We'll only need to use the first two parameters. It will look like this:

<script type="text/javascript">
function SetAutoLocateViewport(latitude, longitude, lvl, bl, msg)
{
  alert('You\'re positioned at:\nLatitude: '+latitude+'\nLongitude: '+longitude);
}
</script>

The function has now been defined. Now we'll need to make sure it gets called with the correct parameters. We can obviously do this by including Microsoft's locate me script file!

<script type="text/javascript" src="http://virtualearth.msn.com/WiFiIPService/locate.ashx"></script>

Of course, you can do many more things by modifying this script. You can easily change the SetAutoLocateViewport function to add a pushpin at your visitor's location for example.

Update: Tatham Oddie of Fuel Advance pointed out a problem which occurs when the Virtual Earth script can't obtain the correct location of the visitor (which is very rare). The Virtual Earth script then outputs something else:

ShowMessage("Virtual Earth cannot determine your current location. Try again later.");

Obviously we can easily create a handler for this function, which would look like this:

function ShowMessage(message)
{
  alert('VE locate message:' + message);
}

Good luck with your application!

Article contributed by Yousef El-Dardiry. Have you got something to contribute?

Copyright 2009. Sponsored by nsquared.   |  Terms Of Use  |  Privacy Statement
Content on this site is generated from the developer community and shared freely for your enjoyment and benefit. This site is run independently of Microsoft and does not express Microsoft's views in any way.