Language: HTML | XAML

How to adjust the distance between location updates (HTML)

Applies to Windows and Windows Phone

Some apps need location updates only when the user has moved a large distance. This topic shows you how to create an app that lets the user adjust the distance between location updates. This distance is known as the movement threshold, and is the minimum change in position required to raise a location update event. By implementing a movement threshold, you can create an app that provides only local information, like news or weather, and may not need location updates unless the user's location has changed to a different city.

The code in this app updates a table each time a location update event is raised, by adding a row that contains the new coordinates and the distance that the user has moved since the last update. The distance moved is calculated with the haversine formula.

If a movement threshold is entered in the input box, you'll be able to see that the distanced moved each time an event is raised is always below the movement threshold.

What you need to know


  • Windows Runtime


  • You should be familiar with HTML and JavaScript.


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

Step 2: Open Microsoft Visual Studio

Open an instance of Microsoft Visual Studio.

Step 3: Create a New Project

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

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

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) {

                done(function () {

                    // Add an event handler to the button.

                    // Add an event handler to the button.



Step 6: Insert the code for creating the Geolocator and handling position updates

Insert the following code to handle the events when a button is pushed and to handle when the position changes.

var eventCount = 0; // The number of positionchanged events that have been raised.
var loc = null;

// Create the Geolocator, set movementThreshold if specified,
// and subscribe to events.
function trackloc() {
    if (loc == null) {
        loc = new Windows.Devices.Geolocation.Geolocator();
    if (loc != null) {
        // Set movementThreshold
        var threshold = document.getElementById("threshold").value;
        if (threshold >= 0) {
            loc.movementThreshold = threshold;
        loc.addEventListener("positionchanged", onPositionChanged);
        loc.addEventListener("statuschanged", onStatusChanged);
    else {
        document.getElementById('status').innerHTML = "Geolocator not found.";

function stoptracking() {
    if (loc != null) {
        loc.removeEventListener("positionchanged", onPositionChanged);
function onPositionChanged(args) {
    eventCount = eventCount + 1;
    var pos = args.position;
    addLatLong(pos.coordinate.point.position.latitude, pos.coordinate.point.position.longitude);

Step 7: Insert the code for updating the HTML table

Add the following code to update the HTML table of positions and total distances.

    // Add a table row containing the coordinates and distance moved.
// Add a table row containing the coordinates and distance moved.
function addLatLong(lat, long) {
    var tabBody = document.getElementById("inputtable");
    var row = document.createElement("TR");

    // First cell - latitude.
    var cell1 = document.createElement("TD");
    cell1.innerHTML = lat; = "latitude" + eventCount;
    // Second cell - longitude.
    var cell2 = document.createElement("TD");
    cell2.innerHTML = long; = "longitude" + eventCount;
    // Third cell - distance
    var cell3 = document.createElement("TD"); = "distance" + eventCount;
    if (eventCount < 2) {
        cell3.innerHTML = "0";
    else {
        var prevLat = document.getElementById("latitude" + (eventCount - 1)).innerHTML;
        var prevLong = document.getElementById("longitude" + (eventCount - 1)).innerHTML;
        // multiply Distance by 1000 to get meters from km
        cell3.innerHTML = Distance(prevLat, prevLong, lat, long) * 1000;

Step 8: Insert code for calculating distance

Insert this code to calculates the distance using the haversine formula.

// Calculates distance between two latitude/longitude coordinates in km,
// based on the haversine formula.
function Distance(prevLat, prevLong, currLat, currLong) {
    var degreesToRadians = Math.PI / 180;
    var earthRadius = 6371; // approximation in kilometers assuming earth to be spherical
    var previousRadianLat = prevLat * degreesToRadians;
    var previousRadianLong = prevLong * degreesToRadians;
    var currentRadianLat = currLat * degreesToRadians;
    var currentRadianLong = currLong * degreesToRadians;
    var latitudeRadianDelta = currentRadianLat - previousRadianLat;
    var longitudeRadianDelta = currentRadianLong - previousRadianLong;
    var expr1 = (Math.sin(latitudeRadianDelta / 2) * Math.sin(latitudeRadianDelta / 2)) +
                (Math.cos(previousRadianLat) * Math.cos(currentRadianLat) * Math.sin(longitudeRadianDelta / 2) * Math.sin(longitudeRadianDelta / 2));
    var expr2 = 2 * Math.atan2(Math.sqrt(expr1), Math.sqrt(1 - expr1));
    var distanceValue = earthRadius * expr2;
    return distanceValue;

Step 9: Insert code to display status messages

Insert the following code for displaying status messages.

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

function getStatusString(locStatus) {
    switch (locStatus) {
        case Windows.Devices.Geolocation.PositionStatus.ready:
            // Location data is available
            return "Location is available.";
        case Windows.Devices.Geolocation.PositionStatus.initializing:
            // This status indicates that a GPS is still acquiring a fix
            return "A GPS device is still initializing.";
        case Windows.Devices.Geolocation.PositionStatus.noData:
            // No location data is currently available
            return "Data from location services is currently unavailable.";
        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.";
        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.";
            return "Unknown status";

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

    <span>Geolocation Event Sample</span><br />
    <span id="MovementThresholdLabel">Movement Threshold in meters:</span><br />
    <input id="threshold" type="text" /><br />

    <button id="startTracking">Track Location</button><br />
    <br />
    <button id="stopTracking">Stop Tracking</button><br />

    <table style="border: solid; width:auto">
        <thead><tr><th>Latitude</th><th>Longitude</th><th>Distance (meters)</th></tr></thead>
        <tbody id="inputtable">
    <div id="geolocatorStatus"></div>

Step 11: Build the app

Choose Build > Build Solution to build the project.

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


Note  On Windows, the Windows Location Provider uses Wi-Fi information to determine location. If Wi-Fi is not available, it will use the IP Address instead. If your computer is not Wi-Fi enabled, you might not get any location update events, since IP Address data is not updated frequently.

Related topics

Geolocation Sample
Guidelines for Location-Aware Applications



© 2014 Microsoft