Skip to content

Latest commit

 

History

History
52 lines (42 loc) · 2.73 KB

how-do-i-get-the-users-current-location-in-a-windows-8-app.md

File metadata and controls

52 lines (42 loc) · 2.73 KB
title authors intro types categories published updated status
How do I get the users current location in a Windows 8 app?
thebeebs
There are instances whilst developing Windows 8 ap...
shorts
win8at8
2012/08/07 12:00:00
2012/08/07 13:00:00
archived

There are instances whilst developing Windows 8 applications in HTML5 when you discover there are two ways to do the same thing. Geolocation is one of those examples. You can either do it the same way you would in a browser like IE9 or Chrome or you could do it the WinJS way.

By providing both methods it ensures that we retain all of the browser APIs from Internet Explorer so that code ported from a website will just work, whilst also ensuring JavaScript maintains the same WinRT features and namespaces that are available across C# and C++.

So the question arises... which should you use? The standard API or the WinJS version? My answer is: Use whichever you prefer.

The standards based way:

function getLocationBrowser() {
   if (navigator.geolocation != undefined) {
       navigator.geolocation.watchPosition(getPositionHandlerBrowser, errorHandler);
   }
}

function getPositionHandlerBrowser(pos) { document.getElementById('latitude').innerHTML = pos.coords.latitude; document.getElementById('longitude').innerHTML = pos.coords.longitude; document.getElementById('accuracy').innerHTML = pos.coords.accuracy;
}

The WinJS way

The main difference is that we use the promise pattern which enables us to more easily chain asynchronous calls. Also the pos object that gets passed to the getPositionHandler has different property names, specifically coords is called coordinate.

var loc = Windows.Devices.Geolocation.Geolocator();

function getLocation() { try { loc.getGeopositionAsync().then(getPositionHandler, errorHandler); } catch (e) { // Catch Errors }
}

function getPositionHandler(pos) { document.getElementById('latitude').innerHTML = pos.coordinate.latitude; document.getElementById('longitude').innerHTML = pos.coordinate.longitude; document.getElementById('accuracy').innerHTML = pos.coordinate.accuracy; }