-
Notifications
You must be signed in to change notification settings - Fork 142
/
Copy pathappcache-features.html
810 lines (688 loc) · 36.4 KB
/
appcache-features.html
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
<!DOCTYPE html>
<!--<html manifest="appcache-features.appcache">-->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!--The viewport meta tag is used to improve the presentation and behavior of the samples
on iOS devices-->
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<!--
This sample demonstrates using an application manifest to store features and tiles locally with a custom-built
editor widget. If you are planning on using one of Esri's pre-built widgets such as the AttributeInspector
then you'll need to use a different pattern for reconstituting the feature layer. See the How-To for more details:
https://github.com/Esri/offline-editor-js/blob/master/doc/howtouseeditlibrary.md
The use cases for using this sample are to ensure you can reload and restart you application
while it is offline and then continue working.
It is strongly recommended that you use your own optimized build of the ArcGIS API for JavaScript
using the Web Optimizer: http://jso.arcgis.com/. You can reference the CDN or host it on your
own web server.
Here is the list of contents for the optimized ArcGIS JS API file used in this sample app:
https://github.com/Esri/offline-editor-js/issues/284
Use the Grunt task in the /samples directory to help generate the manifest file. There is manual
work involved in determining which files need to go into the manifest. The included manifest
file should work with this sample to give you an idea of what goes into the manifest.
A few things to know about manifest files:
- You cannot load an online url that has a redirect.
- If there is an error encountered, the manifest file will stop loading
- The /utils/appCacheManager.js library will auto detect if the manifest changed and
ask if you want to reload the application.
HINT: When testing be sure you allow for browser caching. If you are using Chrome make sure you have NOT
checked Network Tab > Disable cache.
-->
<title>AppCache Tiles and Features</title>
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="../samples/widgets/modal/css/modal-popup.css">
<link rel="stylesheet" href="//js.arcgis.com/3.14/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="//js.arcgis.com/3.14/esri/css/esri.css">
<link rel="stylesheet" href="//esri.github.io/bootstrap-map-js/src/css/bootstrapmap.css">
<script>
// DO NOT DELETE!
// Listen for application cache update events
// We want to place this as early in the application life-cycle as possible!
window.addEventListener('load', function(evt) {
window.applicationCache.addEventListener('updateready', function(evt) {
if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
// Browser downloaded a new app cache.
if (confirm('A new version of this cache is available.')) {
window.location.reload();
console.log("App cache reloaded");
}
} else {
// Manifest didn't changed. Nothing new to server.
console.log("App cache no change");
}
}, false);
}, false);
// Reserved for debugging on Safari desktop and mobile
// Uncomment when doing any debugging on Safari 8 (or previous versions that support App Cache).
// To delete the application cache file on Safari refer to the following url then close/restart browser:
// http://stackoverflow.com/questions/5615266/how-do-you-clear-the-offline-cache-for-web-apps-in-safari
// function logEvent(event) {
// console.log("Checking for Application Cache Event: " + event.type);
// }
//
// window.applicationCache.addEventListener('checking',logEvent,false);
// window.applicationCache.addEventListener('noupdate',logEvent,false);
// window.applicationCache.addEventListener('downloading',logEvent,false);
// window.applicationCache.addEventListener('cached',logEvent,false);
// window.applicationCache.addEventListener('updateready',logEvent,false);
// window.applicationCache.addEventListener('obsolete',logEvent,false);
//
// // If you need to catch AppCache errors as early as possible to troubleshoot errors.
// // You should delete this for production use.
// window.applicationCache.addEventListener("error",function(err){
// console.log("ApplicationCache listener: " + err.toString() + ", " + JSON.stringify(err));
// if (confirm('There was a problem setting this app up for offline. Reload?')) {
// window.location.reload();
// console.log("App cache reloaded");
// }
// },false);
</script>
<style>
#mapDiv {
min-height: 400px;
max-height: 1000px;
}
body {
background-color: #ffffff;
overflow: hidden;
font-family: "Trebuchet MS";
}
#loader-gif{
visibility: hidden;
}
/* Override mod-popup default */
.mod-popup-stop-input {color: black;}
.span-pending {color: blue; padding-left: 1em;}
.floatRight { float: right;}
.container { padding: 20px; width: 100%;}
</style>
<script src="//github.hubspot.com/offline/offline.min.js"></script>
<script>
var locationPath = location.pathname.replace(/\/[^/]+$/, "");
var dojoConfig = {
paths: {
vendor: locationPath + "/../vendor",
utils: locationPath + "/../utils",
widgets: locationPath + "/widgets"
}
}
</script>
<!--
Include a reference to IndexedDBShim for library to work on Safari 7.x.
May not be required for all Safari browsers.
-->
<!--<script src="//nparashuram.com/IndexedDBShim/dist/indexeddbshim.min.js"></script>-->
<!--
This is a locally hosted optimized build of the ArcGIS JS API.
The optimizer creates a single JavaScript file that you can host yourself.
To create your own optimized build go to: http://http://jso.arcgis.com/
-->
<script src="../samples/jsolib/dojo.js" data-dojo-config="async: true"></script>
</head>
<body>
<!-- Our buttons and online/offline indicator -->
<div class="container">
<div class="row">
<div class="col-xs-10">
<div class="form form-group btn-group" data-toggle="buttons">
<button class="btn btn-primary" id="btn-get-tiles">1. Download Tiles</button>
<button class="btn btn-primary" id="btn-online-offline">2. Go Offline</button>
</div>
<span class="span-pending">Pending Edits <span id="span-pending-edits" class="badge">0</span></span>
<img id="loader-gif" src="images/loading.gif"/>
</div>
<div class="col-xs-2">
<!-- this indicates whether app is offline (down) or online (up) -->
<button id="btn-state" class="btn btn-success btn-large floatRight">
<span id="state-span" class="glyphicon glyphicon-link"> Up</span>
</button>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div id="mapDiv"></div>
</div>
</div>
</div>
<!-- Stub for modal editing popup -->
<div id="modal-popup"></div>
<script>
require(["esri/map","esri/layers/FeatureLayer",
"esri/renderers/SimpleRenderer","esri/symbols/SimpleMarkerSymbol",
"esri/Color",
"esri/tasks/query",
"dojo/on",
"esri/graphic","esri/geometry/Extent", "esri/SpatialReference",
"widgets/modal/popup",
"//esri.github.io/bootstrap-map-js/src/js/bootstrapmap.js",
"../dist/offline-tiles-advanced-src.js",
"../dist/offline-edit-advanced-src.js",
"dojo/domReady!"],
function(Map,FeatureLayer,
SimpleRenderer,SimpleMarkerSymbol,Color,Query,
on,Graphic,Extent,SpatialReference,ModalPopup,BootstrapMap) {
var map = null;
var _isOnline = true;
var defaultSymbol;
var _listener;
// Variables for editing handling
var currentFeature, busStopFeatureLayer = null, offlineEdit = null;
var pendingEdits = document.getElementById("span-pending-edits");
var imgOfflineIndicator = document.getElementById("state-span");
var btnState = document.getElementById("btn-state");
// Variables for handling tiles
var tileLayer;
var _currentExtent = null;
var _wantToCancel;
var globalState = {};
var btnGetTiles = document.getElementById("btn-get-tiles");
var btnOnlineOffline = document.getElementById("btn-online-offline");
// Important settings for determining which tile layers gets stored for offline use.
var minZoomAdjust = -1, maxZoomAdjust = 1;
var EXTENT_BUFFER = 0; //buffers the map extent in meters
// Misc.
var loading = document.getElementById("loader-gif");
// Variables for modal popup
var popup,closeBtn,saveBtn,deleteBtn,stopMainID,stopID,stopRoutes,stopNames;
mediaQueries();
initModalPopup();
/**
* NOTE: This is the entry point into the application. The very first thing
* we need to do is check if the application is online or offline.
*
* There have been a few bugs in the offline detection library (offline.min.js)
* This is a utility check to 100% validate if the application is online or
* offline prior to launching any map functionality.
*/
validateOnline(function(result) {
if(result) {
_isOnline = true;
setUIOnline();
}
else {
_isOnline = false;
setUIOffline();
}
startMap();
});
function initModalPopup() {
popup = new ModalPopup({animation: true, animationDuration: 1},"modal-popup");
// Variables for modal popup
closeBtn = document.getElementById("mod-popup-close-btn");
saveBtn = document.getElementById("mod-popup-save-btn");
deleteBtn = document.getElementById("mod-popup-delete-btn");
stopMainID = document.getElementById("stop-main-id");
stopID = document.getElementById("stop-id");
stopRoutes = document.getElementById("stop-routes");
stopNames = document.getElementById("stop-names");
}
/**
* Modify symbol size to devices. Make them easier to touch on.
* Feel free to tweak this based on your requirements
*/
function mediaQueries() {
var widthQuery = window.matchMedia("(max-width: 768px)");
var orientation = window.matchMedia("(orientation:portrait)");
if(widthQuery.matches && orientation.matches){
defaultSymbol= new SimpleMarkerSymbol().setStyle(
SimpleMarkerSymbol.STYLE_DIAMOND).setColor(
new Color([255,0,0,0.5])).setSize(35);
}
else{
defaultSymbol= new SimpleMarkerSymbol().setStyle(
SimpleMarkerSymbol.STYLE_DIAMOND).setColor(
new Color([255,0,0,0.5])).setSize(20);
}
}
/**
* We run this code both online and offline.
*/
function startMap() {
tileLayer = new O.esri.Tiles.OfflineTilesAdvanced("http://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer",function(evt){
console.log("Tile Layer initialized for offline. App state is: " + Offline.state);
},_isOnline);
// We don't need a proxy. All ArcGIS Online Service are CORS enabled.
tileLayer.offline.proxyPath = null;
// We are using Esri bootstrap-map-js to create a responsive mapping app
map = BootstrapMap.create("mapDiv",{
center: [-104.99,39.75], // long, lat
zoom: 17,
sliderStyle: "small"
});
map.on("load",function(evt) {
_currentExtent = evt.map.extent;
});
// Add our offline enabled tile layer to the map
map.addLayer(tileLayer);
// Initialize our feature layer like we normally would
busStopFeatureLayer = new FeatureLayer("http://services1.arcgis.com/M8KJPUwAXP8jhtnM/arcgis/rest/services/Denver_Bus_Stops/FeatureServer/0", {
mode: FeatureLayer.MODE_SNAPSHOT,
outFields: ["GlobalID","BSID","ROUTES","STOPNAME"]
});
//Set the graphics to red boxes to make it easy to click on them
//on a mobile device.
busStopFeatureLayer.setRenderer(new SimpleRenderer(defaultSymbol));
_listener = busStopFeatureLayer.on("update-end",initFeatureUpdateEndListener);
map.addLayer(busStopFeatureLayer);
}
/**
* If we are offline then the attempt to add the feature layer will fail. The error
* will show up in the 'update-end' event.
* Having that error is okay because we want to explicitly control the order in which events happen.
* In production usage it would be a best practices to check any other errors and handle them appropriately.
*/
function initFeatureUpdateEndListener() {
_listener.remove();
//**************************************************
//
// This is where we detect an offline condition
// within the lifecycle of the "mapping" application.
// If we are offline then run our offline
// specific code for reconstituting our map.
//
//**************************************************
//
// Extend the feature layer with offline capabilities.
//
initOfflineEdits();
// If app is online then we ONLY need to extend the feature layer.
if(_isOnline){
extendFeatureLayer(_isOnline, function(success) {
if(success){
// Set click listeners
on(btnGetTiles,"click",downloadTiles);
on(btnOnlineOffline, 'click', goOnlineOffline);
initPanZoomListeners();
setFeatureLayerClickHandler();
setModalPopupClickListeners();
}
else{
alert("There was a problem initializing the map for offline.");
}
});
}
// If the app is offline then we need to retrieve the dataStore from OfflineEditAdvanced
// and then extend the feature layer using that information.
else {
loadFeatureLayerOffline(function(success) {
if(success) {
extendFeatureLayer(_isOnline, function(success) {
console.log("Feature Layer extended successfully OFFLINE!");
});
}
else {
alert("There was a problem initializing the map for offline.");
}
});
}
}
/**
* **********************************************
* EVENT LISTENER MANAGEMENT CODE
* **********************************************
*/
/**
* When panning or zooming let's update certain properties in our offline featureLayerJSON dataStore. This
* dataStore is available once a feature layer has been extended.
*/
function initPanZoomListeners() {
updateOfflineUsage();
updateStatus();
map.on("zoom-end",function(evt) {
_currentExtent = evt.extent;
updateFeatureLayerJSON();
});
map.on("pan-end",function(evt) {
_currentExtent = evt.extent;
updateFeatureLayerJSON();
});
}
/**
* Load the feature while offline using information stored in database
*/
function loadFeatureLayerOffline(callback) {
offlineEdit.getFeatureLayerJSONDataStore(function(success,dataStore) {
if(success){
// Use the feature layer returns from getFeatureDefinition() to reconstitute the layer
// We don't have to set any other properties on the layer because we are using it
// in SNAPSHOT mode which downloads all features within the given extent.
busStopFeatureLayer = new FeatureLayer(JSON.parse(dataStore.featureLayerCollection));
if(busStopFeatureLayer.url == null){
busStopFeatureLayer.url = dataStore.featureLayerUrl;
}
// Set the graphic symbols to red diamond to make it easy to click on them
// on a mobile device.
busStopFeatureLayer.setRenderer(new SimpleRenderer(defaultSymbol));
map.addLayer(busStopFeatureLayer);
console.log("Feature has been added back to the map while offline.");
on(btnGetTiles,"click",downloadTiles);
on(btnOnlineOffline, 'click', goOnlineOffline);
setFeatureLayerClickHandler();
setModalPopupClickListeners();
map.centerAt(dataStore.centerPt);
map.setZoom(dataStore.zoom);
callback(true);
}
else{
alert("There was a problem retrieving feature layer options object. " + dataStore);
callback(false);
}
})
}
/**
* **********************************************
* FEATURE LAYER MANAGEMENT CODE
* **********************************************
*/
function initOfflineEdits() {
offlineEdit = new O.esri.Edit.OfflineEditAdvanced();
// IMPORTANT!!!
// This tells the database which graphic.attribute property to use as a unique identifier
// You can look this information up in your feature service directory under the "Fields" category.
// Example: http://services1.arcgis.com/M8KJPUwAXP8jhtnM/arcgis/rest/services/Denver_Bus_Stops/FeatureServer/0
offlineEdit.DB_UID = "FID";
// IMPORTANT!!!
// A proxy page may be required to upload attachments.
// If you are using a CORS enabled feature service you can ignore this.
// If your feature service is not CORS-enabled then you will need to configure this.
// Refer to "Using the Proxy Page" for more information: https://developers.arcgis.com/en/javascript/jshelp/ags_proxy.html
offlineEdit.proxyPath = null;
offlineEdit.on(offlineEdit.events.EDITS_ENQUEUED, updateStatus);
offlineEdit.on(offlineEdit.events.EDITS_SENT, updateStatus);
offlineEdit.on(offlineEdit.events.ALL_EDITS_SENT, updateStatus);
offlineEdit.on(offlineEdit.events.EDITS_SENT_ERROR, editsError);
}
function extendFeatureLayer(online,callback){
var featureLayerJSON = null;
if(online) {
// This object contains everything we need to restore the map and feature layer after an offline restart
//
// There are two caveats:
// First, you cannot use the object key 'id'. That's a reserved key for internal offline library use.
// Second, complex objects need to be serialized or you'll get a database cloning error.
//
// We do not want to (re)set this if are offline. We can modify it but we don't want to overwrite it.
featureLayerJSON = getFeatureLayerJSON();
}
// NOTE: if app is offline then we want the dataStore object to be null
offlineEdit.extend(busStopFeatureLayer,function(result, error) {
if(result) {
console.log("OfflineEditAdvanced initialized.");
// This sets listeners to detect if the app goes online or offline.
Offline.on('up', goOnline);
Offline.on('down', goOffline);
// If the app is online then force OfflineEditAdvanced to its online state
// This will force the library to check for pending edits and attempt to
// resend them to the Feature Service.
if(_isOnline){
offlineEdit.goOnline(function(result){
if(!result.success){
alert("There was a problem when attempting to go back online.");
}
else {
updateStatus();
}
});
}
else {
offlineEdit.goOffline();
updateStatus();
}
callback(true);
}
else {
callback(false);
alert("Unable to initialize the database. " + error);
}
}.bind(this),/* This is the optional offline configuration property */featureLayerJSON);
}
/**
* Display modal popup when someone clicks on a feature
*/
function setFeatureLayerClickHandler() {
busStopFeatureLayer.on("click", function(evt) {
currentFeature = evt.graphic;
showModalPopup(currentFeature);
var atts = currentFeature.attributes;
stopID.value = atts.GlobalID;
stopMainID.value = atts.BSID;
stopNames.value = atts.STOPNAME;
stopRoutes.value = atts.ROUTES;
}.bind(this));
}
function setModalPopupClickListeners() {
closeBtn.onclick = function(evt) {
hideModalPopup();
}
saveBtn.onclick = function(evt) {
//You may need to uncomment this forced offline check for production use.
//forceInternalOfflineCheck();
popup.graphic.attributes.ROUTES = stopRoutes.value;
popup.graphic.attributes.STOPNAME = stopNames.value;
busStopFeatureLayer.applyEdits(null,[popup.graphic],null,function(result) {
updateFeatureLayerJSON();
console.log("Successfully saved changes to: " + popup.graphic.attributes.STOPNAME);
hideModalPopup();
},
function(err){
alert("There was a problem while trying to save: " + popup.graphic.attributes.STOPNAME);
})
}
deleteBtn.onclick = function(evt) {
// Best practice is to uncomment these for production use
//forceInternalOfflineCheck();
busStopFeatureLayer.applyEdits(null,null,[popup.graphic],function(result) {
updateFeatureLayerJSON();
console.log("Successfully deleted: " + popup.graphic.attributes.STOPNAME);
hideModalPopup();
},
function(err) {
alert("There was a problem while trying to delete: " + popup.graphic.attributes.STOPNAME);
})
}
}
function showModalPopup(graphic) {
popup.graphic = graphic; // assign graphic to popup as a property.
popup.show();
}
function hideModalPopup() {
popup.hide();
}
function getFeatureLayerJSON() {
return {
"featureLayerCollection": JSON.stringify(busStopFeatureLayer.toJson()),
"zoomLevel": map.getZoom(),
"centerPt" : (map.extent.getCenter()).toJson(),
"featureLayerUrl": busStopFeatureLayer.url
}
}
function updateFeatureLayerJSON() {
var fl = getFeatureLayerJSON();
busStopFeatureLayer.setFeatureLayerJSONDataStore(fl,function(result,error){
console.log("updateFeatureLayerJSON - Result: " + result + ", error: " + error);
})
}
/**
* ************************************
* TILE MANAGEMENT CODE
* ************************************
*/
/**
* Manually starts the process to download and store tiles
* in the local database
*/
function downloadTiles() {
tileLayer.deleteAllTiles(function(success,err) {
if(success == false) {
alert("There was a problem deleting the tile cache");
}
else {
console.log("success deleting tile cache");
if( globalState.downloadState == 'downloading')
{
console.log("cancel!");
_wantToCancel = true;
btnGetTiles.innerHTML = "cancelling..";
}
else
{
var zoom = tileLayer.getMinMaxLOD(minZoomAdjust,maxZoomAdjust);
var extent = tileLayer.getExtentBuffer(EXTENT_BUFFER,_currentExtent);
_wantToCancel = false;
tileLayer.prepareForOffline(zoom.min, zoom.max, extent, reportProgress.bind(this));
globalState.downloadState = 'downloading';
}
}
}.bind(this))
}
/**
* Reports the process while downloading tiles.
*/
function reportProgress(progress) {
console.log("downloading tiles...");
if(progress.hasOwnProperty("countNow")){
var percent = Math.floor(progress.countNow / progress.countMax * 100);
btnGetTiles.innerHTML = 'Saving to phone ' + percent + "% - Tap to Cancel";
}
if( progress.finishedDownloading ) {
btnGetTiles.innerHTML = "Saving to phone 100% - Tap to Cancel";
updateOfflineUsage();
updateFeatureLayerJSON();
if( progress.cancelRequested ) {
globalState.downloadState = 'cancelled';
alert("Tile download was cancelled");
}
else {
globalState.downloadState = 'downloaded';
alert("Tile download complete");
}
btnGetTiles.innerHTML = '1. Download Tiles';
}
return _wantToCancel; //determines if a cancel request has been issued
}
/**
* ************************************
* HANDLE GOING ONLINE/OFFLINE
* ************************************
*/
/**
* Forces OfflineEditAdvanced to go online.
* When invoking featureLayer.goOnline() we force library to sync any edits that were
* stored while offline.
*/
function goOnline() {
console.log("Going online...");
loading.style.visibility = "visible";
if(busStopFeatureLayer && busStopFeatureLayer.offlineExtended) {
}
offlineEdit.goOnline(function(success,error) {
if(error === undefined) {
setUIOnline();
console.log("OfflineEditAdvanced is online.");
}
else {
alert("There was a problem syncing offline edits: " + JSON.stringify(error));
}
loading.style.visibility = "hidden";
});
updateOfflineUsage();
if(typeof tileLayer != "undefined") tileLayer.goOnline();
}
/**
* Forces OfflineEditAdvanced offline
*/
function goOffline() {
console.log("Going offline...");
setUIOffline();
offlineEdit.goOffline();
if(typeof tileLayer != "undefined") tileLayer.goOffline();
}
/**
* Toggles offlineEdit online/offline
*/
function goOnlineOffline() {
if(offlineEdit.getOnlineStatus() == offlineEdit.ONLINE){
goOffline();
}
else{
goOnline();
}
}
function setUIOnline() {
btnOnlineOffline.innerHTML = "2. Go Offline";
imgOfflineIndicator.className = "glyphicon glyphicon-link";
imgOfflineIndicator.innerHTML = " Up";
btnState.className = "btn btn-success btn-large floatRight";
}
function setUIOffline() {
btnOnlineOffline.innerHTML = "2. Go Online";
imgOfflineIndicator.className = "glyphicon glyphicon-thumbs-down";
imgOfflineIndicator.innerHTML = " Down";
btnState.className = "btn btn-danger btn-large floatRight";
}
/**
* For internal use - detecting amount of storage used and number of tiles stored.
*/
function updateOfflineUsage() {
tileLayer.offline.store.usedSpace(function(result,err){
if(result != null) {
console.log( "DB Tile count: " + result.tileCount + ", DB Bytes: " + result.sizeBytes);
}
else {
console.log("DB Tile count: " + count + ", DB Bytes: Error");
}
})
}
/**
* Attempts a manual http request to verify if app is online or offline.
* Use this in conjunction with the offline checker library: offline.min.js
* @param callback
*/
function validateOnline(callback) {
var req = new XMLHttpRequest();
req.open("GET", "http://esri.github.io/offline-editor-js/samples/images/blue-pin.png?" + (Math.floor(Math.random() * 1000000000)), true);
req.onload = function() {
if( req.status === 200 && req.responseText !== "") {
req = null;
callback(true);
}
else {
console.log("verifyOffline failed");
req = null;
callback(false);
}
};
req.onerror = function(e) {
console.log("appcache-features.html verifyOnline failed: " + e);
callback(false);
};
req.send(null);
}
/**
* ***********************************************
* OFFLINE FEATURE MANAGER - EVENT MANAGEMENT CODE
* ***********************************************å
*/
function editsError(evt) {
alert("There was a problem. Not all edits were synced with the server. " + JSON.stringify(evt));
}
function updateStatus() {
// Depending on application life cycle busStopFeatureLayer may or may not be extended
// So we have to protect pendingEditsCount() from throwing an "is not a function" error.
if("pendingEditsCount" in busStopFeatureLayer) {
busStopFeatureLayer.pendingEditsCount(function(count) {
pendingEdits.innerHTML = count;
});
}
}
});
</script>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
</body>
</html>