Developing for Modern Windows

Tips, tricks, and guides for developing on modern Windows platforms

Get a GPS Location from an Address String (WinRT 8.1 Universal)

In a Windows Universal 8.1 app it’s easy to find the GPS co-ordinates of a text address. This is a follow-up to my previous post where I showed how to get the text address for a GPS location.

How Does this Work?

The heavy lifting is done by MapLocationFinder.FindLocationsAsync, which returns a list of matching co-ordinates. You provide it with an address string, e.g. “17 Road Street”, and a ‘hint’ point (for the API to centre its search on). You can optionally add a desired number of results.

The Code

In this example I use the device’s current location as the search hint point, then pass an address to the method.

Note: Location services are all done asynchronously since they can take time.

The first chunk of the method gets the device’s current GPS position as a GeoPoint, which is what the API call needs.

This line does all the work, using the string address, the current location, and requesting 2 results:

var mapLocationFinderResult = await MapLocationFinder.FindLocationsAsync(address, point, 2);

Once that finishes, mapLocationFinderResult will hold an array of MapLocations matching the given address. Then the first match is returned.

When it Doesn’t Work

If the address is mistyped or the hint point isn’t close to a matching address you won’t get any responses, so take steps to avoid this. For examlpe if you try to find an address at the other side of the planet from your hint you won’t find it.

The method returns default(MapLocation) if no match was found.

The Full Code

public static async Task<MapLocation> GetPositionFromAddressAsync(string address)
{
    // get current location to use as a search start point
    var locator = new Geolocator();
    var position = await locator.GetGeopositionAsync();

    // convert current location to a GeoPoint
    var basicGeoposition = new BasicGeoposition();
    basicGeoposition.Latitude = position.Coordinate.Latitude;
    basicGeoposition.Longitude = position.Coordinate.Longitude;
    var point = new Geopoint(basicGeoposition);

    // using the address passed in as a parameter, search for MapLocations that match it
    var mapLocationFinderResult = await MapLocationFinder.FindLocationsAsync(address, point, 2);

    if (mapLocationFinderResult.Status == MapLocationFinderStatus.Success)
    {
        return mapLocationFinderResult.Locations[0];
    }

    return default(MapLocation);
}

Calling this Method

var addressLocation = await GetPositionFromAddressAsync("17 Road Street");

One Response to “Get a GPS Location from an Address String (WinRT 8.1 Universal)”

  1. nano says:

    Aparently this is only available for Win10, not 8.1 (only phones 8.1)

Leave a Reply

Your email address will not be published.