Windows Dev Center

Detect the user's location (HTML)

[Some information relates to pre-released product which may be substantially modified before it's commercially released. Microsoft makes no warranties, express or implied, with respect to the information provided here.]

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

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

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

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();
})();

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

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

Windows 10 geolocation sample
Windows 8.1 geolocation sample
Bing Maps SDK Samples
Windows.Devices.Geolocation

 

 

Show:
© 2015 Microsoft