Quickstart: detecting the user's location (HTML)

Applies to Windows and Windows Phone

This tutorial discusses the steps that are required to detect a user's geographical location by using the Windows Runtime Geolocation API.

Objective: You will learn the simplest way to detect a user's geographical location. In this tutorial, you create a simple app that makes a one-time request for location data. Calling getGeoPositionAsync only once, as this example does, may be sufficient for apps that use location for a one-time task, such as geotagging an email message. If location is essential for your app, or if your app requires location updates, your app should handle location events as discussed in How to respond to location updates.

Prerequisites

You should be familiar with HTML and JavaScript.

Instructions

1. Verify that location is enabled

Make sure that the device has access to your location. You can find this setting on Windows by going to the Settings charm, selecting Change PC Settings, then Privacy, then Location. On Windows Phone, go to Settings, select location and set Location services to on.

2. Open Microsoft Visual Studio

Open an instance of Microsoft Visual Studio.

3. Create a New Project

Create a new project, choosing a Blank App from the JavaScript/Store Apps project types.

4. Declare the Location Capability

Double click on package.appxmanifest in Solution Explorer for both the Windows and Windows Phone projects. Select the Capabilities tab. Check Location in the Capabilities list.

5. Replace the JavaScript code

In the Shared project, open default.js (/js/default.js). Replace the code in the file with the following.


(function () {
    "use strict";

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {

            args.setPromise(WinJS.UI.processAll().
                done(function () {

                    // Add an event handler to the button.
                    document.querySelector("#getLocation").addEventListener("click",
                        getLoc);
                }));
        }
    };

    var loc = null;

    function getLoc() {
        if (loc == null) {
            loc = new Windows.Devices.Geolocation.Geolocator();
        }
        if (loc != null) {
            loc.getGeopositionAsync().then(getPositionHandler, errorHandler);
        }
    }

    function getPositionHandler(pos) {
        document.getElementById('latitude').innerHTML = pos.coordinate.point.position.latitude;
        document.getElementById('longitude').innerHTML = pos.coordinate.point.position.longitude;
        document.getElementById('accuracy').innerHTML = pos.coordinate.accuracy;
        document.getElementById('geolocatorStatus').innerHTML =
            getStatusString(loc.locationStatus);
    }

    function errorHandler(e) {        
        document.getElementById('errormsg').innerHTML = e.message;
        // Display an appropriate error message based on the location status.
        document.getElementById('geolocatorStatus').innerHTML =
            getStatusString(loc.locationStatus);    
    }

    function getStatusString(locStatus) {
        switch (locStatus) {
            case Windows.Devices.Geolocation.PositionStatus.ready:
                // Location data is available
                return "Location is available.";        
                break;
            case Windows.Devices.Geolocation.PositionStatus.initializing:
                // This status indicates that a GPS is still acquiring a fix
                return "A GPS device is still initializing."; 
                break;
            case Windows.Devices.Geolocation.PositionStatus.noData:
                // No location data is currently available 
                return "Data from location services is currently unavailable.";       
                break;
            case Windows.Devices.Geolocation.PositionStatus.disabled:
                // The app doesn't have permission to access location,
                // either because location has been turned off.
                return "Your location is currently turned off. " +
                    "Change your settings through the Settings charm " +
                    " to turn it back on.";
                break;
            case Windows.Devices.Geolocation.PositionStatus.notInitialized:
                // This status indicates that the app has not yet requested
                // location data by calling GetGeolocationAsync() or 
                // registering an event handler for the positionChanged event. 
                return "Location status is not initialized because " +
                    "the app has not requested location data.";
                break;
            case Windows.Devices.Geolocation.PositionStatus.notAvailable:
                // Location is not available on this version of Windows
                return "You do not have the required location services " +
                    "present on your system.";
                break;
            default:
                break;
        }
    }

    app.start();
})();

Inside the immediately-invoked anonymous function inside default.js, add the following code.

6. Add the HTML for the apps

Open the default.html file for the Windows and Windows Phone projects, and copy the following HTML into inside the BODY tags of the file.


<div>
    <p>Click "Get Location" to get geolocation data.</p>
    <br />
    <button id="getLocation">getLocation</button> <br />
</div>
<br/>
<div>
    Latitude: <span id="latitude"></span><br />
    Longitude: <span id="longitude"></span><br />
    Accuracy (in meters): <span id="accuracy"></span><br />
    Location Status: <span id="geolocatorStatus"></span><br />
    Error Message: <span id="errormsg"></span><br />
</div>

7. Build the App

On the Build menu, click Build Solution to build the project.

8. Build the app

Choose Build > Build Solution to build the project.

9. Test the app

  1. On the Debug menu, click Start Debugging to test the solution.
  2. On Windows, the first time you run the sample, you'll get a prompt that asks if the app can use your location. Choose the Allow option.
  3. Click the Get Location button to get the current location.

Note  If location data doesn't display, check the following:

  • Make sure you've enabled access to location by opening package.appxmanifest in Solution Explorer and checking Location in the Capabilities tab.
  • On Windows, if an administrator has disabled location services, your app won't be able to access the user's location. In the desktop Control Panel, open Change Location Settings and check if Turn on the Windows Location platform is checked.
  • On Windows Phone, the user can disable location in the Settings app. Go to the Settings app, select location and make sure that the Location services switch is toggled on.

Summary

In this quickstart, you created a simple app for detecting the user's current location.

The request for location is initiated in the following code, which creates a Geolocator object, calls getGeoPositionAsync, and specifies handlers for success and failure:


function getloc() {
    if (loc == null) {
        loc = new Windows.Devices.Geolocation.Geolocator();
    }
    if (loc != null) {
        loc.getGeopositionAsync().then(getPositionHandler, errorHandler);
    }
}

The getPositionHandler function displays the latitude, longitude, and accuracy if location is available:


function getPositionHandler(pos) {
    document.getElementById('latitude').innerHTML = pos.coordinate.point.position.latitude;
    document.getElementById('longitude').innerHTML = pos.coordinate.point.position.longitude;
    document.getElementById('accuracy').innerHTML = pos.coordinate.accuracy;
    document.getElementById('geolocatorStatus').innerHTML =
            getStatusString(loc.locationStatus);
}

The errorHandler function calls the helper function getStatusString to display an appropriate status message if location detection is unsuccessful:


function errorHandler(e) {        
    document.getElementById('errormsg').innerHTML = e.message;
    // Display an appropriate error message based on the location status.
    document.getElementById('geolocatorStatus').innerHTML =
        getStatusString(loc.locationStatus);    
}

Related topics

Geolocation Sample
Bing Maps SDK Samples
Windows.Devices.Geolocation

 

 

Show:
© 2014 Microsoft