When you use location services you usually need to convert between raw location data (GPS position) and a real-world street address. In this article I’ll show you how to do just that, and in a follow-up post I’ll do the reverse (get the GPS co-ordinates for a given address).

Step 1: Get the Address from Co-ordinates

You can insert this code into any app using WinRT8.1. Of course it’s suited to phones more than PCs, but will work fine as long as your device can get accurate location information.

Add the following namespaces to your class:



using Windows.Devices.Geolocation;

using Windows.Services.Maps;



This method returns a string with the first address found at the given position (if an address is found!).



async Task<string> GetAddressFromCoordinatesAsync(Geoposition geoposition)

{

var mapLocationFinderResult = await MapLocationFinder.FindLocationsAtAsync(geoposition.Coordinate.Point);

if (mapLocationFinderResult.Status == MapLocationFinderStatus.Success)

{

// hard-coding to only view the first returned possible address ([0]). You might get more than one result, in which case check them against your requirements.

return mapLocationFinderResult.Locations[0].Address.StreetNumber + " " + mapLocationFinderResult.Locations[0].Address.Street;

}

return "not found";

}



Step 2: Call the Method

You need to pass a position to that method, so use this code in an async method to get the current position then call GetAddressFromCoordinatesAsync() :



// get the device's current location

var locator = new Geolocator();

var position = await locator.GetGeopositionAsync();

// get the first address that matches the current position

string address = await GetAddressFromCoordinatesAsync(position);

Console.WriteLine(address); // write out the address



GetAddressFromCoordinatesAsync() uses MapLocationFinder.FindLocationsAtAsync() to return a list of results matching the position. I have shown the Address.StreetNumber and Address.Street , but you can access other data, such as country or neighborhood.

What Next?

To test the functionality, open up the Windows Phone emulator and go to Additional Tools (1) and select Location (2). You can place a pin on the world map (3) and the phone emulator will act as if it’s in that place. It’s great for testing. Put the pin in your house, workplace, etc. and test the code.

In a follow-up post I’ll show how to get position co-ordinates from a text string address.