Home > Uncategorized > Determine Geoposition from IP address on Windows Phone

Determine Geoposition from IP address on Windows Phone

On Windows Phone, you can determine the current user’s lat/lon position using code such as:

GeoCoordinateWatcher gwatcher = new GeoCoordinateWatcher();
GeoCoordinate PositionNow = gwatcher.Position.Location;

if (!PositionNow.IsUnknown)
{
MessageBox.Show(“lat/lon:” + PositionNow.Latitude+ “,” + PositionNow.Longitude);
}

However, the position may not be known, so you may need a failover system, getting the user’s rough location from the IP address of the device, for that, I’ve used api.ipinfodb.com – Create your own account there, since I’m not sharing my key!

Here’s the code I used:

public static void GetLocationFromIp(Action<GeoCoordinate> callback)
{
var wc = new WebClient();
var url = new Uri(“http://api.ipinfodb.com/v3/ip-city/?key=xxxx&format=xml&#8221;);
wc.DownloadStringAsync(url, callback);
wc.DownloadStringCompleted += (sender, args) =>
{
var xdoc = XDocument.Parse(args.Result);
var longitude = xdoc.Descendants(“longitude”).First().Value;
var latitude = xdoc.Descendants(“latitude”).First().Value;
var dLng = Convert.ToDouble(longitude, CultureInfo.InvariantCulture);
var dLat = Convert.ToDouble(latitude, CultureInfo.InvariantCulture);
var geo = new GeoCoordinate(dLat, dLng);
callback(geo);
};
}

Neat., all all in one function.

I’ve then expanded upon this to provide reverse geocoding using geonames.org:

public static void ReverseGeocode(Action<string> callback, GeoCoordinate geo)
{
var wc = new WebClient();
var strUrl = “http://api.geonames.org/findNearbyPlaceName?formatted=true&lat={0}&lng={1}&username=xxxxx”;
strUrl = string.Format(strUrl, geo.Latitude, geo.Longitude);
var url = new Uri(strUrl);
wc.DownloadStringAsync(url, callback);
wc.DownloadStringCompleted += (sender, args) =>
{
var xdoc = XDocument.Parse(args.Result);
var name = xdoc.Descendants(“name”).First().Value;
callback(name);
};

}

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: