Geolocation example


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<!DOCTYPE html>
<html>
  <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() {
        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><span>w3c geolocation api example</span>
      </h3>
    </header>
    <div class="title">This Application demonstrates the use of w3c geolocation
      API.</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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
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:

1
2
3
4
5
6
7
8
9
10
CACHE MANIFEST
 
CACHE:
index.html
main.js
../assets/pega-header.png
../assets/style.css
 
NETWORK:
*

Related topics

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