Free Information Technology Magazines and eBooks

Thursday, March 11, 2010

.NET Framework 4.0: Access the computer location using System.Device.Location Namespace

.NET Framework 4.0: Access the computer location using System.Device.Location NamespaceNow finding the physical location of a target computer is never been easy in the newest namespace of .NET Framework 4.0. With the System.Device.Location namespace, application developers can now easily access the computer's location information that may come from multiple providers, such as GPS, Wi-Fi triangulation, and cell phone tower triangulation. The System.Device.Location classes provide a single API to encapsulate the multiple location providers on a computer and supports seamless prioritization and transitioning between them. As application developer using this API, you won't need to know which location-sensing technologies are available on the target computer so you are freed from the burden of customizong your .NET app to a specific hardware configuration.


Here are some classes that System.Device.Location namespace have:
CivicAddress - can include fields such as street address, postal code, state/province, and country or region.
CivicAddressResolver - provides functionality for resolving a coordinate-based location to a civic address.
GeoCoordinate - Returns a geographical location determined by latitude and longitude coordinates.
GeoCoordinateWatcher - location data that is based on latitude and longitude coordinates

To show you how does the class work, take a look at this sample code from MSDN. (this code should run on the target/client machine)


using System;
using System.Device.Location;
namespace ResolveAddressSync
{
class Program
{
static void Main(string[] args)
{
ResolveAddressSync();
}
static void ResolveAddressSync()
{
GeoCoordinateWatcher watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
watcher.MovementThreshold = 1.0; // set to one meter
watcher.TryStart(false, TimeSpan.FromMilliseconds(1000));

CivicAddressResolver resolver = new CivicAddressResolver();

if (watcher.Position.Location.IsUnknown == false)
{
CivicAddress address = resolver.ResolveAddress(watcher.Position.Location);

if (!address.IsUnknown)
{
Console.WriteLine("Country: {0}, Zip: {1}",
address.CountryRegion,
address.PostalCode);
}
else
{
Console.WriteLine("Address unknown.");
}
}
}

}
}


Take note that to execute the above code successfully, you must have location sensor installed on the client machine.

For More Coding Tips & Tricks, subscribe now.

3 comments:

El Bruno said...

Great post .. can you suggest a location device to test this code ? for a laptop ?

thanks in advance

Salman Bhatti said...

Would this work if i do this on ASP.NET and access the code using iPhone 3G? I am trying to do it but I am not getting anything back from the app.

deadconcept said...

May I ask if you have tried this working successfully or did you just copy this code snippet in MSDN site