Geolocation example


The index.html file, which contains an application that makes use of the Geolocation API functionality is listed below.

<!DOCTYPE html>
<html manifest="manifest.appcache">
  <head>
    <title>Geolocation API sample</title>
    <link rel="stylesheet" href="../assets/style.css" type="text/css" media="all"/>
    <script src="https://maps.googleapis.com/maps/api/js"></script>
    <script src="main.js"></script>
    <style>
      #map-canvas {
        width: *;
        height: 200px;
      }
    </style>
    
    <script type="text/javascript">
      window.onLaunchboxLoaded = function(startCause, willShow) {
        console.log('API Loaded');
        console.log('Build: ' + window.launchbox.Container.version);
        console.log('OS: ' + window.launchbox.Container.osName + ' ' 
          + window.launchbox.Container.osVersion);
        console.log('Network: ' + window.launchbox.Container.networkStatus.type);
        window.launchbox.SplashScreen.hide();
      };

      function printText(str) {
        var d = document.getElementById('results');
        d.innerHTML += "<br/>" + str;
        d.scrollTop = d.scrollHeight;
      }

      function clearText() {
        var d = document.getElementById('results');
        d.innerHTML = "";
      }

      google.maps.event.addDomListener(window, 'load', initialize);

    </script>
    
  </head>
  <body>
    <header>
      <h3>Pega Hybrid Container
        <span>w3c geolocation api example</span>
      </h3>
    </header>
    <div class="title">This Application demonstrates the use of w3c geolocation 
      API provided in Pega Hybrid Container.</div>
    <table width="100%">
      <tr>
        <td width="50%" style="border-right: 1px solid;" align="center">
          <div id="defaultAccuracy" onclick="setHighAccuracy(false);" 
            class="text-bold">DEFAULT ACCURACY</div>
        </td>
        <td width="50%" align="center">
          <div id="highAccuracy" onclick="setHighAccuracy(true);">HIGH ACCURACY</div>
        </td>
      </tr>
      <tr>
        <td width="50%" style="border-right: 1px solid;" align="center">
          Maximum age
        </td>
        <td width="50%" align="center">
          <input type="text" id="maximumAge" />
        </td>
      </tr>
      <tr>
        <td width="50%" style="border-right: 1px solid;" align="center">
          Timeout
        </td>
        <td width="50%" align="center">
          <input type="text" id="timeout" />
        </td>
      </tr>
    </table>
    <div style="display: block; padding: 10px;">
      <input type="button" onclick="getCurrentPosition();" value="Get current position" />
      <input type="button" id="watchPosition" onclick="watchPosition();" 
        value="Start watching" />
      <input type="button" id="stopWatching" onclick="stopWatching();" 
        value="Stop watching" disabled />
      <input type="button" onclick="saveResults();" value="Save results to csv" />
    </div>
    <div style="padding: 10px;margin-top:-20px;">
        <input type="button" onclick="clearText();" value="Clear all text"/>
    </div>
    <div id="map-canvas"></div>
    <div id="results"></div>
  </body>
</html>

The contents of the main.js file containing JavaScript used by the above application are listed below:

var enableHighAccuracy = false;
var maximumAge = 0;
var timeout = 9999999;
var watchId = undefined;
var map;
var marker;
var polyline;
var results;

function initialize() {
  var mapCanvas = document.getElementById('map-canvas');
  var mapOptions = {
    zoom: 14,
    center: { lat: 50.2868200, lng: 19.1038500 }
  };
  map = new google.maps.Map(mapCanvas, mapOptions);
}

function setHighAccuracy(accuracy) {
  enableHighAccuracy = accuracy;
  if (accuracy) {
    document.getElementById("highAccuracy").className = "text-bold";
    document.getElementById("defaultAccuracy").className = "";
  } else {
    document.getElementById("highAccuracy").className = "";
    document.getElementById("defaultAccuracy").className = "text-bold";
  }
}

function setLocationTimeout() {
  var newTimeout = parseInt(document.getElementById("timeout").value);
  if (!isNaN(newTimeout)) {
    timeout = parseInt(newTimeout);
  } else {
    timeout = 9999999;
  }
  printText("Setting timeout: " + timeout);
}

function setMaxAge() {
  var newMaxAge = parseInt(document.getElementById("maximumAge").value);
  if (!isNaN(newMaxAge)) {
    maximumAge = newMaxAge;
  } else {
    maximumAge = 0;
  }
  printText("Setting maximumAge: " + maximumAge);
}

function getCurrentPosition() {
  setLocationTimeout();
  setMaxAge();
  var startTime = (new Date()).getTime();
  window.navigator.geolocation.getCurrentPosition(
    function(position) {
      var endTime = (new Date()).getTime();
      printText("Received current position in " + (endTime - startTime) + "ms:");
      printText(stringifyPosition(position));
      centerMap(position);
      addMarker(position);
    },
    function(error) {
      printText("Failed to retrieve current position:");
      printText(JSON.stringify(error));
    },
    {
      maximumAge: maximumAge,
      timeout: timeout,
      enableHighAccuracy: enableHighAccuracy
    }
  );
}

function watchPosition() {
  setLocationTimeout();
  setMaxAge();
  document.getElementById("stopWatching").disabled = false;
  document.getElementById("watchPosition").disabled = true;
  startTracingRoute();
  watchId = window.navigator.geolocation.watchPosition(
    function(position) {
      printText("Received watched position:");
      printText(stringifyPosition(position));
      centerMap(position);
      addCoordinate(position);
      addMarker(position);
    },
    function(error) {
      printText("Failed to retrieve watched position:");
      printText(JSON.stringify(error));
    },
    {
      maximumAge: maximumAge,
      timeout: timeout,
      enableHighAccuracy: enableHighAccuracy
    }
  );
}

function stopWatching() {
  if (watchId !== undefined) {
    window.navigator.geolocation.clearWatch(watchId);
    printText("Clearing watch with id " + watchId);
  }
  document.getElementById("stopWatching").disabled = true;
  document.getElementById("watchPosition").disabled = false;
}

function centerMap(position) {
  var center = { lat: position.coords.latitude, lng: position.coords.longitude };
  map.panTo(center);
}

function addMarker(position) {
  if (marker !== undefined) {
    marker.setMap(null);
  }
  marker = new google.maps.Marker({
    position:  { lat: position.coords.latitude, lng: position.coords.longitude },
    map: map,
    title: 'Your position'
  });
}

function addCoordinate(position) {
  polyline.getPath().push(new google.maps.LatLng(position.coords.latitude,
    position.coords.longitude));
  results.push(position.coords.latitude + "," + position.coords.longitude 
    + "," + position.coords.accuracy +"\n");
}

function startTracingRoute() {
  results = [];
  results.push("latitude,longitude,accuracy\n");
  if (marker !== undefined) {
    marker.setMap(null);
  }
  if (polyline !== undefined) {
    polyline.setMap(null);
  }
  polyline = new google.maps.Polyline({
    geodesic: true,
    strokeColor: '#FF0000',
    strokeOpacity: 1.0,
    strokeWeight: 5
  });
  polyline.setMap(map);
}

function saveResults() {

  var blob = new Blob(results, {type : "text/plain"});

  var errorHandler = function (err) {
    alert("Failed to save results to file");
  };
  var where;

  if (window.launchbox.Container.osName == 'Android') {
    where = LocalFileSystem.EXTERNAL;
  } else {
    where = Window.PERSISTENT;
  }

  requestFileSystem(where, 10 * 1024 * 1024/*10MB*/, function (fs) {
    fs.root.getFile(
      'geolocation-results' + (new Date()).getTime() + '.csv',
      { 'create': true },
      function (fileEntry) {
        var writer = fileEntry.createWriter();
        writer.write(blob);

        writer.onwrite = function () {
          alert("Saved results as " + fileEntry.toURL());
        };
        writer.onerror = function () {
          alert("Failed to save results to file");
        }
      }, errorHandler);
  }, errorHandler);
}

function stringifyPosition(position) {
  // You cannot log native position object in Safari with JSON.stringify.
  // It must be converted to pojo first, because properties are implemented
  // on the prototype, not the object itself.
  var pojo = {
    timestamp: position.timestamp,
    coords: {
      accuracy: position.coords.accuracy,
      altitude: position.coords.altitude,
      altitudeAccuracy: position.coords.altitudeAccuracy,
      heading: position.coords.heading,
      latitude: position.coords.latitude,
      longitude: position.coords.longitude,
      speed: position.coords.speed
    }
  };
  return JSON.stringify(pojo, null, 4);
}

The contents of the cache manifest file called manifest.appcache for this application are listed below:

CACHE MANIFEST

CACHE:
index.html
main.js
../assets/pega-header.png
../assets/style.css

NETWORK:
*

The webapp-descriptor.xml file for this application is defined in the following way:

<?xml version="1.0" encoding="UTF-8"?>
<webapp-descriptor xmlns="http://www.antennasoftware.com/application-hosting/web-app-descriptor/2.0">
    <id>com.pega.sample.Geolocation</id>
    <version>1.0.0</version>
    <name>Sample api usage</name>
</webapp-descriptor>

Related topics

Public API reference
Geolocation
Legal notice | Copyright © 2016 and Confidential to Pegasystems Inc. All rights reserved
PDN | Hybrid Container | Feedback
Advanced...