Tips, tricks, and guides for developing on modern Windows platforms
WinRT’s GeoLocation API gives your apps easy access to a device’s current location. This even works on devices that don’t have GPS built in (Windows can get an approximate location based on information available, such as WiFi signals, IP address, and so on).
Here I’ll show you how to get the longitude and latitude co-ordinates of your device. Though this is obviously more suited to phone apps, the code can be used on any Windows 8.1 + device.
Minimum Windows version (development environment): 8.1
Minimum target OS version: Windows 8.1 / Windows Phone 8.1 (WinRT)
Minimum Visual Studio version: Visual Studio 2013 (with Windows Phone SDK supporting WP8.1); free versions are adequate
Skill level: Intermediate – I will assume you know your way around Visual Studio and the basics of building WinRT apps.
By default, WinRT apps have very restricted permissions. This is a good thing, because it ensures apps only have access to certain features if they are required, and the user is notified of them when using the app. One of the restricted permissions is access to the device location (for privacy reasons).
You must activate this access in any app where you get location information. You also need network access
• Open Package.appxmanifest
• Select the Capabilities tab
• Tick the Location check box in the Capabilities list (you also need the Internet (Client & Server) capability, but that should be selected by default)
• Save Package.appxmanifest to apply the change.
You need to include the Windows.Devices.Geolocation namespace for accessing location, and also System.Threading.Tasks to enable async code:
using Windows.Devices.Geolocation; using System.Threading.Tasks;
// Geolocator is in the Windows.Devices.Geolocation namespace Geolocator geo = new Geolocator(); // await this because we don't know hpw long it will take to complete and we don't want to block the UI Geoposition pos = await geo.GetGeopositionAsync(); // get the raw geoposition data double lat = pos.Coordinate.Point.Position.Latitude; // current latitude double longt = pos.Coordinate.Point.Position.Longitude; // current longitude
Place that code anywhere (it must be within an async method), and you can get the current GPS longitude/latitude whenever you run the above code. You could run it periodically, for example, to track the user’s movement, or use it whenever a user wants to share their location.
If you want to test the functionality, you could set up a simple project that displays the current longitude and latitude when a button is pressed, then go for a walk or drive and test it.