HTML5 Zone is brought to you in partnership with:

Michael Crump is a Microsoft MVP, INETA Community Champion, and an author of several .NET Framework eBooks. He speaks at a variety of conferences and has written dozens of articles on .NET development. He currently works at Telerik with a focus on our XAML control suite. You can visit his blog at: MichaelCrump.Net or follow him on Twitter at: @mbcrump Michael is a DZone MVB and is not an employee of DZone and has posted 115 posts at DZone. You can read more from them at their website. View Full User Profile

2-Minute Location Awareness with Windows 8–HTML

09.26.2012
| 2592 views |
  • submit to reddit

I was working on a mapping application for Windows 8 – HTML using the Bing SDK and needed to pass the latitude and longitude into it. I began searching for a straightforward way to get the location and had to read through pages of documentation before finally finding it. Here it is in case you want to use it in your own apps.

Default.html

Just replace the <body> tag as shown below:

<body> 
    Latitude: <div id="latitude"></div><br />
    Longitude: <div id="longitude"></div><br />
    Accuracy: <div id="accuracy"></div><br /><br />
</body>

We have simply added a few divs that represent the latitude, longitude and accuracy.

default.js

// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
    "use strict";

    var loc;

    WinJS.Binding.optimizeBindingReferences = true;

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;
    loc = new Windows.Devices.Geolocation.Geolocator();
    loc.getGeopositionAsync().then(getPositionHandler, errorHandler);

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

    function errorHandler(e) {
        // TODO: Handle Error     
    }

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize
                // your application here.
            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }
            args.setPromise(WinJS.UI.processAll());
        }
    };

    app.oncheckpoint = function (args) {
        // TODO: This application is about to be suspended. Save any state
        // that needs to persist across suspensions here. You might use the
        // WinJS.Application.sessionState object, which is automatically
        // saved and restored across suspension. If you need to complete an
        // asynchronous operation before your application is suspended, call
        // args.setPromise().
    };

    app.start();
   

})();

From the default.js page, you can see that we declare loc as a variable, then create a new instance of Windows.Devices.Geolocation.Geolocator(). After that we make a call to getGeopositionAsync and pass it a function that will contain the position and another function that contains the error handler. The pos.coordinate.latitude, longitude and accuracy are simply added to our divs on the default.html.

Application Manifest

The last piece is placing a checkbox in the “Location” for capabilities which is found in the package.appxmanifest as shown below:

image

One thing to note here is that this does not require you to have a PC with various sensors like GPS. It is using Wi-Fi triangulation and IP address to determine where you are. From my test, it is very accurate!!!

Run it!

Now when we run our application, we will see the app asking permission to use our location. We should select “Allow” here.

image

Then we will see the latitude, longitude and accuracy in our Windows 8 –HTML Application. (I obfuscated my location because it was so accurate!)

image

Of course, your users may elect to turn off location at any point by using the Settings charms and toggling the Location switch as shown below:

image

Wrap-up

I am having a lot of fun with location and sensors at the moment. So much fun that I plan on creating a session around it for 2013. I’m just waiting for some solid hardware to come out. I hope this helped!

 

Published at DZone with permission of Michael Crump, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)