Respond to location updates (HTML)

This topic explains how to respond to changes in the user's location.

What you need to know

Technologies

  • Windows Runtime

Prerequisites

You should be familiar with HTML and JavaScript.

Instructions

Step 1: Verify that location is enabled

Before your app can access location, Location must be enabled on the device. In the Settings app, check that the following location privacy settings are turned on:

  • Location for this device... is turned on (not applicable in Windows 10 Mobile)
  • The location services setting, Location, is turned on
  • Under Choose apps that can use your location, your app is set to on

Step 2: Open Microsoft Visual Studio

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

Step 3: Create a New Project

In the New Project dialog box, choose a blank application from the JavaScript project types.

Step 4: Enable the location capability

Double click on package.appxmanifest in Solution Explorer for both the Windows and Windows Phone projects, and select the Capabilities tab. Then check Location in the Capabilities list. This adds the Location device capability to the package manifest file.

  <Capabilities>
    <!-- DeviceCapability elements must follow Capability elements (if present) -->
    <DeviceCapability Name="location"/>
  </Capabilities>

Step 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("#startTracking").addEventListener("click",
                        trackloc);

                    // Add an event handler to the button.
                    document.querySelector("#stopTracking").addEventListener("click",
                        stoptracking);

                }));
        }
    };

    var loc = null;

    function trackloc() {
        if (loc == null) {
            loc = new Windows.Devices.Geolocation.Geolocator();
        }
        if (loc != null) {
            loc.addEventListener("positionchanged", onPositionChanged);
            loc.addEventListener("statuschanged", onStatusChanged);
            // display initial status, in case location is turned off.
            document.getElementById('geolocatorStatus').innerHTML =
                getStatusString(loc.locationStatus);
        }
    }

    function stoptracking() {
        if (loc != null) {
            loc.removeEventListener("positionchanged", onPositionChanged);
        }
    }

    function onPositionChanged(args) {
        var pos = args.position;
        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);
    }

    // Handle change in status to display an appropriate message.        
    function onStatusChanged(args) {
        var newStatus = args.status;
        document.getElementById('geolocatorStatus').innerHTML =
            getStatusString(newStatus);
    }

    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.";
            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:
                return "Unknown status.";
        }
    }

    app.start();
})();

Step 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.

    <p>Geolocation Event Sample</p><br />
    <span id="status"></span><br />
    <button id="startTracking">Track Location</button><br />
    <br />
    <button id="stopTracking">Stop Tracking</button><br />
    Latitude: <span id="latitude">Waiting for update...</span><br />
    Longitude:  <span id="longitude">Waiting for update...</span><br />
    Accuracy (in meters): <span id="accuracy">Waiting for update...</span><br />
    Location Status: <span id="geolocatorStatus"></span><br />

Step 7: Build the app

Choose Build > Build Solution to build the project.

Step 8: Test the app

  1. On the Debug menu, click Start Debugging to test the solution.
  2. 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.

Remarks

Location services uses a number of different sources to determine location. If GPS, cell towers, and Wi-Fi are unavailable, it will use the IP Address instead. In that case, note that you might not get any location update events, because IP Address data is not updated frequently.

If your application needs to get location data only once, rather than subscribing to updates, use the GetGeopositionAsync method as described in Quickstart: Detecting the user's location.

Windows 10 geolocation sample

Windows 8.1 geolocation sample

Windows.Devices.Geolocation