This repository has been archived by the owner on Apr 5, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 75
/
UploadFeature.js
504 lines (431 loc) · 16.6 KB
/
UploadFeature.js
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
/**
* @copyright 2011 geOps
* @author Just van den Broecke
* @license https://github.com/geops/ole/blob/master/license.txt
* @link https://github.com/geops/ole
*/
/**
* Class: OpenLayers.Editor.Control.UploadFeature
*
* Provide uploading of Features from a local file and add these to the current drawing on the Map.
* No server-side storage is involved, though a small server-side script is required that will echo
* back an uploaded file. This response is captured into an hidden IFrame, a well-known technique.
* See also: http://viralpatel.net/blogs/2008/11/ajax-style-file-uploading-using-hidden-iframe.html.
*
* Inherits from:
* - <OpenLayers.Control.Button>
*/
OpenLayers.Editor.Control.UploadFeature = OpenLayers.Class(OpenLayers.Control, {
EVENT_TYPES: ["featureuploaded"],
layer: null,
title: OpenLayers.i18n('oleUploadFeature'),
/**
* APIProperty: url
* {String} URL of server script to upload to,
* see example: https://code.google.com/p/geoext-viewer/source/browse/trunk/heron/services/heron.cgi.
*/
url: '',
/**
* APIProperty: params
* {Object} parameters to be passed to server (see url) in POST body
*/
params: {
action: 'upload',
mime: 'text/html',
encoding: 'escape'
},
/**
* APIProperty: formats
* {Array} array of supported formats, each format is object with name, extension, mime and formatter classname.
*/
formats: [
{name: 'GeoJSON', fileExt: '.json', mimeType: 'text/plain', formatter: 'OpenLayers.Format.GeoJSON'}
],
/**
* APIProperty: fileProjection
* {<OpenLayers.Projection>} projection of features in file, for custom projections use Proj4.js.
*/
fileProjection: null,
/**
* APIProperty: visibleOnUpload
* Ensure that the Layer is visible when uploaded.
*/
visibleOnUpload: true,
/** OpenLayers.Format objects, to be populated from formats, non-API property. */
formatters: {},
/** Should all objects be replaced on upload ? */
replaceFeatures: false,
/**
* Constructor: OpenLayers.Editor.Control.MergeFeature
* Create a new control for merging features.
*
* Parameters:
* layer - {<OpenLayers.Layer.Vector>}
* options - {Object} An optional object whose properties will be used
* to extend the control.
*/
initialize: function (layer, options) {
// The editable layer
this.layer = layer;
this.title = OpenLayers.i18n('oleUploadFeature');
OpenLayers.Control.Button.prototype.initialize.apply(this, [options]);
},
activate: function () {
var activated = OpenLayers.Control.prototype.activate.call(this);
if (activated) {
this.openDialog();
}
return activated;
},
deactivate: function () {
var deactivated = OpenLayers.Control.prototype.deactivate.call(this);
if (deactivated) {
this.cleanUp(this);
}
return deactivated;
},
/**
* Clean up .
*/
cleanUp: function (self) {
this.getDialog().hide();
if (!self.iframe) {
return;
}
self.removeIFrame();
},
/**
* Creates and pops up file chooser Dialog.
*/
delayedOpenDialog: function () {
var self = this;
setTimeout(function () {
self.openDialog();
}, 200);
},
/**
* Get the dialog object.
* We may use the upload control outside the Editor.
*/
getDialog: function () {
if (this.map && this.map.editor && this.map.editor.dialog) {
return this.map.editor.dialog;
}
if (!this.dialog) {
this.dialog = new OpenLayers.Editor.Control.Dialog();
this.map.addControl(this.dialog);
}
return this.dialog;
},
/**
* Creates and pops up file chooser Dialog.
*/
openDialog: function () {
// this.cleanUp(this);
// Create content div for Dialog
var content = document.createElement("div");
content.appendChild(document.createElement("p"));
// Create upload Form
var formElm = document.createElement("form");
formElm.setAttribute('id', 'upload_form');
formElm.setAttribute('method', "POST");
formElm.setAttribute('action', this.url);
formElm.setAttribute("target", "upload_iframe");
formElm.setAttribute("enctype", "multipart/form-data");
formElm.setAttribute("encoding", "multipart/form-data");
// Input element for selecting local file
formElm = this.createInputElm('oleFile', 'file', 'file', null, formElm);
/* Create select element for file format options */
var select = document.createElement("select");
select.setAttribute("name", "format_select");
select.setAttribute("id", "format_select");
// Add file format options
var option;
for (var i = 0; i < this.formats.length; ++i) {
option = document.createElement("option");
// Some formatters are already objects
// we cannot store these in elements, so save in map.
// we use formatter's name in lookup in this.formatters map
var format = this.formats[i];
var formatter = format.formatter;
if (typeof formatter == 'string') {
formatter = eval('new ' + formatter + '()');
}
formatter.fileProjection = format.fileProjection;
this.formatters[format.name] = formatter;
// Set formatter's name as value
option.setAttribute("value", format.name);
option.innerHTML = format.name;
option.fileExt = format.fileExt;
option.mimeType = format.mimeType;
// Extra optional format-specific params to be submitted to server script
option.params = {};
if (format.targetSrs) {
// Have server reproject (i.s.o. OL)
option.params.target_srs = format.targetSrs;
}
if (format.sourceSrs) {
option.params.source_srs = format.sourceSrs;
}
select.appendChild(option);
}
// Add selector to Form
formElm.appendChild(select);
// Checkbox, if all features in Layer need to be replaced
var replaceFeatures = document.createElement('p');
var replaceFeaturesCB = document.createElement('input');
replaceFeaturesCB.type = 'checkbox';
replaceFeaturesCB.id = 'oleUploadFeatureReplace';
replaceFeaturesCB.name = 'uploadFeatureReplace';
replaceFeaturesCB.value = 'true';
replaceFeaturesCB.checked = true;
// The following IE is required due to a bug in IE (below version 8) to tick the checkbox prior inserting it into the DOM
replaceFeaturesCB.defaultChecked = true;
this.setReplaceFeatures(replaceFeaturesCB.checked);
replaceFeatures.appendChild(replaceFeaturesCB);
OpenLayers.Event.observe(replaceFeatures, 'click', OpenLayers.Function.bind(function (event) {
// Prevent propagation of event to drawing controls
OpenLayers.Event.stop(event, true);
this.setReplaceFeatures(replaceFeaturesCB.checked);
}, this));
var element = document.createElement('label');
element.htmlFor = 'oleUploadFeatureReplace';
element.appendChild(document.createTextNode(OpenLayers.i18n('oleUploadFeatureReplace')));
replaceFeatures.appendChild(element);
formElm.appendChild(replaceFeatures);
// Additional user-defined hidden elements
for (var param in this.params) {
formElm = this.createInputElm(null, param, 'hidden', this.params[param], formElm);
}
// Add Form to content
content.appendChild(formElm);
this.showUploadDialog(content);
// Set format selector on selected format if file chosen based on file extension
var self = this;
document.getElementById('oleFile').onchange = function (e) {
var fileName = self.fileInputValue(this);
if (fileName) {
var fnameArr = fileName.split('.');
if (fnameArr.length > 1) {
var ext = '.' + fnameArr[fnameArr.length - 1].toLowerCase();
// Find option with .ext file extension
var selectElm = document.getElementById('format_select');
var options = selectElm.options;
for (var i = 0; i < options.length; ++i) {
if (ext == options[i].fileExt) {
selectElm.selectedIndex = i;
break;
}
}
}
}
};
},
/**
* Show message via Dialog.
*/
showMessage: function (content, close) {
this.getDialog().show({
title: OpenLayers.i18n('oleUploadFeature'),
content: content,
close: close
});
},
/**
* Show file upload Dialog.
* @param {!HTMLElement} content - HTML (form) content for the Dialog
*/
showUploadDialog: function (content) {
// Show the upload Dialog. We do Form-submit ourselves.
this.getDialog().show({
title: OpenLayers.i18n('oleUploadFeature'),
content: content,
save: OpenLayers.Function.bind(this.uploadFeature, this),
cancel: OpenLayers.Function.bind(this.cancel, this),
saveButtonText: 'oleDialogOkButton',
noHideOnSave: true
});
},
/**
* Create empty hidden IFrame to receive uploaded features echoed from server.
* @param {string} name - Name of element
* @return {!Element}
*/
createIFrame: function (name) {
// Create the hidden empty iframe in which the response (file contents) will be received
var iframe = document.createElement("iframe");
iframe.setAttribute("id", name);
iframe.setAttribute("name", name);
iframe.setAttribute("width", "0");
iframe.setAttribute("height", "0");
iframe.setAttribute("border", "0");
iframe.setAttribute("style", "width: 0; height: 0; border: none;");
iframe.src = 'about:blank';
return iframe;
},
/**
* removes IFrame if existing.
*/
removeIFrame: function () {
var iframe = document.getElementById('upload_iframe');
if (iframe) {
iframe.parentNode.removeChild(iframe);
}
this.iframe = null;
},
/**
* Cancel callback from Dialog.
*/
cancel: function () {
this.deactivate();
},
/**
* Parse response (file contents) text into feature array.
*/
parseFeatures: function (featuresText) {
// Get selected format option
var selectElm = document.getElementById('format_select');
var option = selectElm.options[selectElm.selectedIndex];
// Create a formatter from selected option
// Either a string or an object
var formatter = this.formatters[option.value];
if (!formatter) {
return null;
}
/* Need to reproject if projection in file is different from Layer */
if (this.fileProjection) {
formatter.internalProjection = this.layer.map.baseLayer.projection;
formatter.externalProjection = formatter.fileProjection ? formatter.fileProjection : this.fileProjection;
}
var features = formatter.read(featuresText);
if (!features || features.length < 1) {
return null;
}
// We have features, determine extent of feature collection
var bounds;
if (features.constructor != Array) {
// May be single feature
features = [features];
}
for (var i = 0; i < features.length; ++i) {
if (!bounds) {
bounds = features[i].geometry.getBounds();
} else {
bounds.extend(features[i].geometry.getBounds());
}
}
this.bounds = bounds;
return features;
},
uploadFeature: function () {
// At least one file needs to be specified
var fileInputElm = document.getElementById('oleFile');
if (!this.fileInputValue(fileInputElm)) {
this.cleanUp(this);
this.showMessage(OpenLayers.i18n('oleUploadFeatureNoFile'), OpenLayers.Function.bind(this.delayedOpenDialog, this));
return;
}
// Create hidden IFrame to receive uploaded data and add to DOM.
this.iframe = this.createIFrame('upload_iframe');
document.body.appendChild(this.iframe);
// Add event handler to handle response in IFrame
var self = this;
var iframe = self.iframe;
var eventHandler = function () {
if (iframe.detachEvent) {
iframe.detachEvent("onload", eventHandler);
} else {
iframe.removeEventListener("load", eventHandler, false);
}
// Fetch response from server from iframe
var content;
if (iframe.contentDocument) {
content = iframe.contentDocument.body.innerHTML;
} else if (iframe.contentWindow) {
content = iframe.contentWindow.document.body.innerHTML;
} else if (iframe.document) {
content = iframe.document.body.innerHTML;
}
// We normally use HTML-escaping, needed otherwise the iframe will garble GML (converting tags to lowercase)
if (content && self.params.encoding == 'escape') {
content = content.replace(/"/g, '"')
.replace(/>/g, '>')
.replace(/</g, '<')
.replace(/&/g, '&')
}
var features = self.parseFeatures(content);
if (self.replaceFeatures) {
self.layer.destroyFeatures();
}
if (!features) {
self.deactivate();
self.showMessage(OpenLayers.i18n('oleUploadFeatureNone'));
return;
}
// At least one feature present: add to map and zoom to extent
self.layer.addFeatures(features);
self.layer.map.zoomToExtent(self.bounds);
if (self.visibleOnUpload) {
self.layer.setVisibility(true);
}
// Del the iframe...
setTimeout(function () {
self.deactivate();
}, 250);
};
if (iframe.addEventListener) {
iframe.addEventListener("load", eventHandler, true);
}
if (iframe.attachEvent) {
iframe.attachEvent("onload", eventHandler);
}
var form = document.getElementById('upload_form');
// Optional per-format parameters to be included in form
var selectElm = document.getElementById('format_select');
var option = selectElm.options[selectElm.selectedIndex];
for (var param in option.params) {
form = this.createInputElm(null, param, 'hidden', option.params[param], form);
}
form.submit();
},
/**
* Instantiates an Input Element for Form
* @param {string} id Name of element
* @param {string} name Name of element
* @param {string} type Type of element, e.g. text or hidden
* @param {string} value optional initial Value for element
* @param {!HTMLElement} parentElm optional parent Element
* @return {!HTMLElement}
*/
createInputElm: function (id, name, type, value, parentElm) {
var inputElm = document.createElement('input');
inputElm.setAttribute('type', type);
inputElm.id = id;
inputElm.name = name;
inputElm.value = value ? value : null;
if (parentElm) {
parentElm.appendChild(inputElm);
}
return parentElm;
},
/**
* Get the filename value from a File Input element
* @param {!HTMLElement} fileElm file input Element
* @return {string}
*/
fileInputValue: function (fileElm) {
if (fileElm.files) {
return fileElm.files.length == 1 ? fileElm.files[0].name : null;
} else {
return fileElm.value;
}
},
/**
* Shows or hides guides
* @param {Boolean} guidesVisible Set to TRUE to show guides
*/
setReplaceFeatures: function (replace) {
this.replaceFeatures = replace;
},
CLASS_NAME: "OpenLayers.Editor.Control.UploadFeature"
});