-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.js
1356 lines (1164 loc) · 45 KB
/
app.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
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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function() {
'use strict';
var globals = typeof window === 'undefined' ? global : window;
if (typeof globals.require === 'function') return;
var modules = {};
var cache = {};
var aliases = {};
var has = ({}).hasOwnProperty;
var expRe = /^\.\.?(\/|$)/;
var expand = function(root, name) {
var results = [], part;
var parts = (expRe.test(name) ? root + '/' + name : name).split('/');
for (var i = 0, length = parts.length; i < length; i++) {
part = parts[i];
if (part === '..') {
results.pop();
} else if (part !== '.' && part !== '') {
results.push(part);
}
}
return results.join('/');
};
var dirname = function(path) {
return path.split('/').slice(0, -1).join('/');
};
var localRequire = function(path) {
return function expanded(name) {
var absolute = expand(dirname(path), name);
return globals.require(absolute, path);
};
};
var initModule = function(name, definition) {
var hot = null;
hot = hmr && hmr.createHot(name);
var module = {id: name, exports: {}, hot: hot};
cache[name] = module;
definition(module.exports, localRequire(name), module);
return module.exports;
};
var expandAlias = function(name) {
return aliases[name] ? expandAlias(aliases[name]) : name;
};
var _resolve = function(name, dep) {
return expandAlias(expand(dirname(name), dep));
};
var require = function(name, loaderPath) {
if (loaderPath == null) loaderPath = '/';
var path = expandAlias(name);
if (has.call(cache, path)) return cache[path].exports;
if (has.call(modules, path)) return initModule(path, modules[path]);
throw new Error("Cannot find module '" + name + "' from '" + loaderPath + "'");
};
require.alias = function(from, to) {
aliases[to] = from;
};
var extRe = /\.[^.\/]+$/;
var indexRe = /\/index(\.[^\/]+)?$/;
var addExtensions = function(bundle) {
if (extRe.test(bundle)) {
var alias = bundle.replace(extRe, '');
if (!has.call(aliases, alias) || aliases[alias].replace(extRe, '') === alias + '/index') {
aliases[alias] = bundle;
}
}
if (indexRe.test(bundle)) {
var iAlias = bundle.replace(indexRe, '');
if (!has.call(aliases, iAlias)) {
aliases[iAlias] = bundle;
}
}
};
require.register = require.define = function(bundle, fn) {
if (typeof bundle === 'object') {
for (var key in bundle) {
if (has.call(bundle, key)) {
require.register(key, bundle[key]);
}
}
} else {
modules[bundle] = fn;
delete cache[bundle];
addExtensions(bundle);
}
};
require.list = function() {
var list = [];
for (var item in modules) {
if (has.call(modules, item)) {
list.push(item);
}
}
return list;
};
var hmr = globals._hmr && new globals._hmr(_resolve, require, modules, cache);
require._cache = cache;
require.hmr = hmr && hmr.wrap;
require.brunch = true;
globals.require = require;
})();
(function() {
var global = window;
var __makeRelativeRequire = function(require, mappings, pref) {
var none = {};
var tryReq = function(name, pref) {
var val;
try {
val = require(pref + '/node_modules/' + name);
return val;
} catch (e) {
if (e.toString().indexOf('Cannot find module') === -1) {
throw e;
}
if (pref.indexOf('node_modules') !== -1) {
var s = pref.split('/');
var i = s.lastIndexOf('node_modules');
var newPref = s.slice(0, i).join('/');
return tryReq(name, newPref);
}
}
return none;
};
return function(name) {
if (name in mappings) name = mappings[name];
if (!name) return;
if (name[0] !== '.' && pref) {
var val = tryReq(name, pref);
if (val !== none) return val;
}
return require(name);
}
};
require.register("initialize.js", function(exports, require, module) {
'use strict';
var editor = require('lib/editor');
document.addEventListener('DOMContentLoaded', function () {
// do your setup here
editor();
console.log('Initialized app');
});
});
;require.register("lib/editor.js", function(exports, require, module) {
'use strict';
/* global alert, L, XMLHttpRequest, XDomainRequest */ // used by standardjs (linter)
var initMap = require('./map.js');
var getUrlVars = require('./getUrlVars.js');
var redFetch = require('./red_fetch.js');
var taxonomy = require('./taxonomy.js');
var translations = require('./translations.js');
window.translations = translations;
var map;
var endpoint = 'https://data.transformap.co/place/';
module.exports = function () {
console.log('editor initialize start');
map = initMap();
var urlVars = getUrlVars();
var dataUrls;
var place = urlVars['place'];
if (place) {
if (/^[0-9a-f-]{32,36}$/i.test(place)) {
var normalizedPlace = place.replace(/-/, '');
if (normalizedPlace.length === 32) {
dataUrls = [endpoint + place, 'http://192.168.0.2:6000/place/' + place, place];
} else {
dataUrls = [place];
}
} else {
dataUrls = [place];
}
}
function createToiArray(toiString) {
if (typeof toiString !== 'string') {
return [];
}
var toiArray = toiString.split(';');
for (var i = 0; i < toiArray.length; i++) {
toiArray[i] = toiArray[i].trim();
}
return toiArray;
}
var startLang = translations.selectAllowedLang(translations.current_lang);
console.log("lang on start: " + startLang);
console.log(translations.supported_languages);
var typeOfInintiatives = [];
var toiHashtable = {};
function fillTransforMapTax(data) {
console.log('fillTransforMapTax called');
var dataArray = data.results.bindings;
var current_lang = dataArray[0].itemLabel['xml:lang'];
var needs = [];
var interactions = [];
var identities = [];
dataArray.forEach(function (entry) {
if (!entry.subclass_of) {
return;
}
var label = {};
label[current_lang] = entry.itemLabel.value;
var currentObject = {
item: entry.item.value,
label: label
};
if (entry.subclass_of.value == 'https://base.transformap.co/entity/Q146') {
currentObject['needs_tag'] = entry.needs_tag.value;
needs.push(currentObject);
} else if (entry.subclass_of.value == 'https://base.transformap.co/entity/Q150') {
currentObject['interaction_tag'] = entry.interaction_tag.value;
interactions.push(currentObject);
} else if (entry.subclass_of.value == 'https://base.transformap.co/entity/Q176') {
currentObject['identity_tag'] = entry.identity_tag.value;
identities.push(currentObject);
}
});
//needs
$('#_key_provides').empty();
needs.forEach(function (entry) {
var newOption = $('<option>');
newOption.attr('value', entry.needs_tag);
if (currentData.properties && currentData.properties.provides) {
var needs_array = createToiArray(currentData.properties.provides);
needs_array.forEach(function (need) {
if (need === entry.needs_tag) {
newOption.attr('selected', 'selected');
}
});
}
newOption.append(entry.label[current_lang]);
$('#_key_provides').append(newOption);
$('#_key_provides').selectpicker('refresh');
});
//interaction
$('#_key_interaction').empty();
interactions.forEach(function (entry) {
var newOption = $('<option>');
newOption.attr('value', entry.interaction_tag);
if (currentData.properties && currentData.properties.interaction) {
var interactions_array = createToiArray(currentData.properties.interaction);
interactions_array.forEach(function (interact) {
if (interact === entry.interaction_tag) {
newOption.attr('selected', 'selected');
}
});
}
newOption.append(entry.label[current_lang]);
$('#_key_interaction').append(newOption);
$('#_key_interaction').selectpicker('refresh');
});
//identity
$('#_key_identity').empty();
identities.forEach(function (entry) {
var newOption = $('<option>');
newOption.attr('value', entry.identity_tag);
if (currentData.properties && currentData.properties.identity) {
var identity_array = createToiArray(currentData.properties.identity);
identity_array.forEach(function (identity) {
if (identity === entry.identity_tag) {
newOption.attr('selected', 'selected');
}
});
}
newOption.append(entry.label[current_lang]);
$('#_key_identity').append(newOption);
$('#_key_identity').selectpicker('refresh');
});
}
function fillTOIs(data) {
$('#_key_type_of_initiative').empty();
typeOfInintiatives = [];
toiHashtable = {};
var toiSelect = document.getElementById('_key_type_of_initiative');
var dataArray = data.results.bindings;
var current_lang = dataArray[0].itemLabel['xml:lang'];
dataArray.forEach(function (entry) {
if (!entry.type_of_initiative_tag) {
return;
}
if (toiHashtable[entry.type_of_initiative_tag.value]) {
// filter out duplicates
return;
}
var label = {};
label[current_lang] = entry.itemLabel.value;
var currentObject = {
item: entry.item.value,
label: label,
type_of_initiative_tag: entry.type_of_initiative_tag.value
};
typeOfInintiatives.push(currentObject);
toiHashtable[entry.type_of_initiative_tag.value] = currentObject;
});
function labelCompare(a, b) {
// 'Others' cat should get sorted last
if (a.item === 'https://base.transformap.co/entity/Q20') return 1;
if (b.item === 'https://base.transformap.co/entity/Q20') return -1;
// in toi list, 'other*' should be last
if (a.type_of_initiative_tag && a.type_of_initiative_tag.match(/^other_/)) return 1;
if (b.type_of_initiative_tag && b.type_of_initiative_tag.match(/^other_/)) return -1;
if (a.label[current_lang] < b.label[current_lang]) {
return -1;
} else {
return 1;
}
}
typeOfInintiatives.sort(labelCompare);
typeOfInintiatives.forEach(function (entry) {
var newOption = document.createElement('option');
var optionValue = document.createAttribute('value');
optionValue.value = entry.type_of_initiative_tag;
newOption.setAttributeNode(optionValue);
if (currentData.properties && currentData.properties.type_of_initiative) {
var tois = createToiArray(currentData.properties.type_of_initiative);
tois.forEach(function (toi) {
if (toi === entry.type_of_initiative_tag) {
var newSelected = document.createAttribute('selected');
newOption.setAttributeNode(newSelected);
}
});
}
var label = document.createTextNode(entry.label[current_lang]); // FIXME fallback langs
newOption.appendChild(label);
toiSelect.appendChild(newOption);
$('#_key_type_of_initiative').selectpicker('refresh');
});
}
function addFreeTagsRow() {
var freetags = document.getElementById('freetags');
var lastRow = freetags.lastChild;
while (lastRow.nodeType === 3) {
// 3 = text-node
lastRow = lastRow.previousSibling;
}
var keyNode = lastRow.firstChild.nodeType === 1 ? lastRow.firstChild : lastRow.firstChild.nextSibling;
var newNr = parseInt(keyNode.id.slice(-1)) + 1;
var newRow = document.createElement('div');
var divClass = document.createAttribute('class');
divClass.value = 'row';
newRow.setAttributeNode(divClass);
var newKey = document.createElement('input');
var bootstrapClass = document.createAttribute('class');
bootstrapClass.value = 'form-control';
newKey.setAttributeNode(bootstrapClass);
var bootstrapClass = document.createAttribute('class');
bootstrapClass.value = 'form-control';
var newValue = document.createElement('input');
newValue.setAttributeNode(bootstrapClass);
var keyId = document.createAttribute('id');
keyId.value = 'key' + newNr;
var valueId = document.createAttribute('id');
valueId.value = 'value' + newNr;
newKey.setAttributeNode(keyId);
newValue.setAttributeNode(valueId);
var elementName = document.createAttribute('name');
elementName.value = 'freetags';
newKey.setAttributeNode(elementName);
newValue.setAttributeNode(elementName.cloneNode(true));
newRow.appendChild(newKey);
newRow.appendChild(newValue);
freetags.appendChild(newRow);
}
var currentData = {};
function fillForm(placeData) {
currentData = placeData;
if (currentData._deleted) {
document.getElementById('deleted').style.display = 'block';
}
if (currentData.properties) {
for (var key in currentData.properties) {
// ignore DB-generated fields
if (/^_/.test(key)) {
continue;
}
var field = document.getElementById('_key_' + key);
var value = currentData.properties[key];
if (field) {
// console.log(field)
// console.log(value)
field.value = value;
} else {
// put it into "free tags"
// get last child
var freetags = document.getElementById('freetags');
var lastRow = freetags.lastChild;
while (lastRow.nodeType === 3) {
// 3 = text-node
lastRow = lastRow.previousSibling;
}
// set data on last child
var keyNode = lastRow.firstChild.nodeType === 1 ? lastRow.firstChild : lastRow.firstChild.nextSibling;
keyNode.value = key;
var valueNode = lastRow.lastChild.nodeType === 1 ? lastRow.lastChild : lastRow.lastChild.previousSibling;
valueNode.value = value;
addFreeTagsRow();
}
}
}
if (currentData.geometry && currentData.geometry.coordinates) {
var lon = currentData.geometry.coordinates[0];
var lat = currentData.geometry.coordinates[1];
if (lat === undefined || lon === undefined) {
console.error('lat or lon empty');
return;
}
document.getElementById('_geometry_lon').value = lon;
document.getElementById('_geometry_lat').value = lat;
map.my_current_marker = new L.marker([lat, lon], { icon: new map.my_placeMarker() });
map.my_editableLayers.addLayer(map.my_current_marker);
map.my_drawControl = map.getDrawControl(false);
map.addControl(map.my_drawControl);
map.panTo(new L.LatLng(lat, lon));
} else {
// allow adding a marker
map.my_drawControl = map.getDrawControl(true);
map.addControl(map.my_drawControl);
}
if (currentData.properties && currentData.properties._id) {
document.getElementById('_id').value = currentData.properties._id;
$('#transformapapilink').attr('href', endpoint + currentData.properties._id);
} else if (currentData._id) {
document.getElementById('_id').value = currentData._id;
$('#transformapapilink').attr('href', endpoint + currentData._id);
}
if (currentData.properties.osm) {
$('#osmlink').attr('href', currentData.properties.osm);
}
}
if (place) {
redFetch(dataUrls, fillForm, function (e) {
console.error(e);
map.my_drawControl = map.getDrawControl(true);
map.addControl(map.my_drawControl);
});
} else {
map.my_drawControl = map.getDrawControl(true);
map.addControl(map.my_drawControl);
}
//add languageswitcher
var menu = document.getElementById('menu');
$('#menu').append('<div id=languageSelector onClick="$(\'#languageSelector ul\').toggleClass(\'open\');">' + '<span lang=en>Choose Language:</span>' + '<ul></ul>' + '</div>');
function initializeTranslatedTOIs(Q5data) {
translations.initializeLanguageSwitcher(Q5data);
var nowPossibleLang = translations.selectAllowedLang(translations.current_lang);
translations.current_lang = nowPossibleLang;
fetchAndSetNewTranslation(nowPossibleLang);
}
function fetchAndSetNewTranslation(lang) {
redFetch([taxonomy.getLangTaxURL(lang, 'Q8'), 'https://raw.githubusercontent.com/TransforMap/transformap-viewer-translations/master/taxonomy-backup/susy/taxonomy.' + lang + '.json'], fillTOIs, function (error) {
console.error('none of the taxonomy data urls available');
}, { cacheBusting: false });
redFetch([taxonomy.getLangTaxURL(lang, 'Q4'), 'https://raw.githubusercontent.com/TransforMap/transformap-viewer-translations/master/taxonomy-backup/susy/taxonomy.' + lang + '.json'], fillTransforMapTax, function (error) {
console.error('none of the taxonomy data urls available');
}, { cacheBusting: false });
}
translations.fetchAndSetNewTranslation = fetchAndSetNewTranslation;
redFetch(["https://base.transformap.co/wiki/Special:EntityData/Q5.json", "https://raw.githubusercontent.com/TransforMap/transformap-viewer/Q5-fallback.json"], initializeTranslatedTOIs, function (error) {
console.error("none of the lang init data urls available");
});
function createCORSRequest(method, url) {
// taken from https://www.html5rocks.com/en/tutorials/cors/
var xhr = new XMLHttpRequest();
if ('withCredentials' in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
} else if (typeof XDomainRequest !== 'undefined') {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
}
function clickSubmit() {
console.log('clickSubmit enter');
var requiredFields = ['_key_type_of_initiative', '_key_name', '_geometry_lat', '_geometry_lon'];
for (var i = 0; i < requiredFields.length; i++) {
var id = requiredFields[i];
var value = document.getElementById(id).value;
if (!value || !value.length) {
console.error('submit: field ' + id + ' empty');
alert('Error on submit: field ' + id.replace(/^_key_/, '') + ' is not allowed to be empty');
return false;
}
}
var data = {
'type': 'Feature',
'properties': {},
'geometry': {
'type': 'Point',
'coordinates': [parseFloat(document.getElementById('_geometry_lon').value), parseFloat(document.getElementById('_geometry_lat').value)]
}
};
// all 'input type=text'
var allInputs = document.getElementsByTagName('input');
var freeTags = { keys: {}, values: {} };
console.log(allInputs);
for (var i = 0; i < allInputs.length; i++) {
var element = allInputs[i];
if (!element.type === 'text') {
continue;
}
if (element.value && element.id) {
console.log(element.id + ': ' + element.value);
if (/^_key_/.test(element.id)) {
var key = element.id.replace(/^_key_/, '');
data.properties[key] = element.value.trim();
// element of 'free tags'
} else if (/^key[0-9]+$/.test(element.id) && element.name === 'freetags') {
var nr = element.id.replace(/^key/, '');
freeTags.keys[nr] = element.value;
} else if (/^value[0-9]+$/.test(element.id) && element.name === 'freetags') {
var nr = element.id.replace(/^value/, '');
freeTags.values[nr] = element.value;
}
}
}
console.log(freeTags);
for (var keynr in freeTags.keys) {
var key = freeTags.keys[keynr].trim();
if (key && freeTags.values[keynr]) {
// only take if key and value are not ""
data.properties[key] = freeTags.values[keynr].trim();
}
}
// drop-down
var allSelects = document.getElementsByTagName('select');
for (var i = 0; i < allSelects.length; i++) {
var element = allSelects[i];
if (/^_key_/.test(element.id) && element.value) {
var key = element.id.replace(/^_key_/, '');
for (var childCounter = 0; childCounter < element.children.length; childCounter++) {
var child = element.children[childCounter];
if (child.selected === true) {
data.properties[key] = (data.properties[key] ? data.properties[key] + ';' : '') + child.value;
}
}
}
}
// textarea
var allTextareas = document.getElementsByTagName('textarea');
for (var i = 0; i < allTextareas.length; i++) {
var element = allTextareas[i];
if (/^_key_/.test(element.id) && element.value) {
var key = element.id.replace(/^_key_/, '');
data.properties[key] = element.value.trim();
}
}
console.log(data);
var uuid = document.getElementById('_id').value;
var sendData = JSON.stringify(data);
console.log(sendData);
// PUT is for UPDATE, POST is for CREATE
var xhr = createCORSRequest(uuid ? 'PUT' : 'POST', endpoint + uuid);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(sendData);
console.log(xhr);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var retJson = JSON.parse(xhr.responseText);
console.log(retJson);
if (retJson.id) {
document.getElementById('_id').value = retJson.id;
$('#transformapapilink').attr('href', endpoint + retJson.id);
$('#osmlink').attr('href', $('#_key_osm').attr('value'));
alert('Save successful');
} else {
alert('Error: something wrent wrong on saving: ' + JSON.stringify(retJson));
}
} else {
console.error(xhr);
}
}
};
document.getElementById('deleted').style.display = 'none';
}
document.getElementById('save').onclick = clickSubmit;
function clickDelete() {
var uuid = document.getElementById('_id').value;
if (!uuid) {
alert('nothing to delete');
return;
}
if (!confirm('Do you really want to delete this POI? It will be only marked as deleted and can be restored later if you save the current Browser URL.')) {
console.log('user aborted delete');
return;
}
var xhr = createCORSRequest('DELETE', endpoint + uuid);
xhr.send();
console.log(xhr);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var retJson = JSON.parse(xhr.responseText);
console.log(retJson);
} else {
console.error(xhr);
}
}
};
document.getElementById('deleted').style.display = 'block';
}
document.getElementById('delete').onclick = clickDelete;
document.getElementById('plus').onclick = addFreeTagsRow;
function clickSearch() {
var country = document.getElementById('_key_addr:country').value;
var city = document.getElementById('_key_addr:city').value;
// const postcode = document.getElementById('_key_addr:postcode').value // postcode not used in nominatim, decreases result quality
var street = document.getElementById('_key_addr:street').value;
var housenumber = document.getElementById('_key_addr:housenumber').value;
var querystring = 'q=';
if (street) {
if (housenumber) {
querystring += housenumber + '+';
}
querystring += street + ',';
}
if (city) {
querystring += city + ',';
}
querystring += country;
var query = '//nominatim.openstreetmap.org/search?' + querystring + '&format=json&limit=1&[email protected]';
console.log(query);
redFetch([query], function (successData) {
console.log(successData);
if (successData.length !== 1) {
console.error('error in Nominatim return data: length != 1');
alert('Sorry, Nothing found');
return;
}
var result = successData[0];
if (result.class === 'building' || result.class === 'amenity' || result.class === 'shop' || result.class === 'place' && result.type === 'house') {
console.log('address found exactly');
document.getElementById('_geometry_lon').value = result.lon;
document.getElementById('_geometry_lat').value = result.lat;
// trigger update of place marker
document.getElementById('_geometry_lat').focus();
document.getElementById('_geometry_lon').focus();
map.setView(new L.LatLng(result.lat, result.lon), 18);
} else {
map.setView(new L.LatLng(result.lat, result.lon), 18);
console.log('address not found exactly');
setTimeout(function () {
// wait for map to pan to location
alert('Attention: The address was not found exactly, please place the marker manually!');
document.getElementById('_geometry_lon').value = '';
document.getElementById('_geometry_lat').value = '';
document.getElementById('_geometry_lon').focus();
document.getElementById('_geometry_lat').focus();
}, 400);
}
}, function (error) {
console.log(error);
alert('Sorry, Address search did not work');
});
}
document.getElementById('coordsearch').onclick = clickSearch;
function stopRKey(evt) {
var evt = evt ? evt : event ? event : null;
var node = evt.target ? evt.target : evt.srcElement ? evt.srcElement : null;
if (evt.keyCode == 13 && node.type == 'text') {
return false;
}
}
document.onkeypress = stopRKey;
function updateLinkPosition() {
var centre = map.getCenter();
var targetlocation = '#' + map.getZoom() + '/' + centre.lat + '/' + centre.lng;
var maplink = document.getElementById('gotomap');
var href = maplink.getAttribute('href');
var splitstr = href.split('#');
href = maplink.getAttribute('href').split('#')[0] + targetlocation;
maplink.setAttribute('href', href);
var newlink = document.getElementById('newbutton');
newlink.setAttribute('href', './' + targetlocation);
}
map.on('moveend', updateLinkPosition);
console.log('editor initialize end');
};
});
;require.register("lib/getUrlVars.js", function(exports, require, module) {
'use strict';
/*
* This library provides a simple function to parse URL parameters
*
* Mon 3 Oct 15:07:12 CEST 2016
* Michael Maier (species@github), WTFPL
*
* returns object with key:value pairs
This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://www.wtfpl.net/ for more details. */
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
vars[key] = value.replace(/#.*$/, '');
});
return vars;
}
module.exports = getUrlVars;
});
;require.register("lib/map.js", function(exports, require, module) {
'use strict';
var L = require('leaflet');
var L_Hash = require('leaflet-hash');
var L_Draw = require('leaflet-draw');
var editableLayers;
var drawControl;
var placeMarker;
var popupText = 'Press the edit button to move me. <img style="width:30px;height:30px;background-position:-150px -1px;background-image:url(\'images/spritesheet.svg\');background-size: 270px 30px;"> <br><br> Find it on the bottom left corner of the map.';
function getDrawControl(allowNewMarker) {
var markerValue = allowNewMarker ? { icon: new placeMarker() } : false;
var options = {
position: 'bottomleft',
draw: {
polyline: false,
polygon: false,
rectangle: false,
circle: false,
marker: markerValue
},
edit: {
featureGroup: editableLayers, // REQUIRED!!
remove: false
}
};
return new L.Control.Draw(options);
}
function initMap() {
console.log('initMap start');
var map;
var attrOsm = 'Map data by <a href="https://openstreetmap.org">OpenStreetMap</a> contributors, under <a href="https://www.openstreetmap.org/copyright">ODbL</a>. ';
var attrPois = 'POIs by <a href="http://solidariteconomy.eu">SUSY</a>, <a href="https://creativecommons.org/publicdomain/zero/1.0/">CC-0</a>. ';
var leafletBgMaps;
var zoom;
var defaultlayer;
var center;
var baseMaps = {};
baseMaps['mapnik'] = new L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: attrOsm + attrPois,
maxZoom: 19,
noWrap: true
});
baseMaps['stamen_terrain'] = new L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/terrain/{z}/{x}/{y}.png', {
attribution: 'Map tiles by <a href="http://stamen.com/">Stamen Design</a>, ' + 'under <a href="https://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. ' + attrOsm + attrPois,
maxZoom: 18,
noWrap: true
});
baseMaps['stamen_terrain_bg'] = new L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/terrain-background/{z}/{x}/{y}.png', {
attribution: 'Map tiles by <a href="http://stamen.com/">Stamen Design</a>, ' + 'under <a href="https://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. ' + attrOsm + attrPois,
maxZoom: 18,
noWrap: true
});
baseMaps['hot'] = new L.tileLayer('http://tile-{s}.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
attribution: 'Tiles courtesy of <a href="http://hot.openstreetmap.org/">Humanitarian OpenStreetMap Team</a>. ' + attrOsm + attrPois,
maxZoom: 20,
noWrap: true
});
if (!leafletBgMaps) {
leafletBgMaps = {
'Stamen - Terrain': baseMaps['stamen_terrain'],
'Stamen - Terrain Background': baseMaps['stamen_terrain_bg'],
'OpenStreetMap - Mapnik': baseMaps['mapnik'],
'Humanitarian OpenStreetMap ': baseMaps['hot']
};
}
if (!defaultlayer) {
defaultlayer = baseMaps['mapnik'];
}
map = L.map('map', {
zoomControl: true,
center: center ? center : new L.LatLng(28.6, 9),
zoom: zoom ? zoom : 2,
layers: defaultlayer
});
var ctrl = new L.Control.Layers(leafletBgMaps);
map.addControl(ctrl);
var hash = new L.Hash(map); // Leaflet persistent Url Hash function
// leaflet draw
editableLayers = new L.FeatureGroup();
map.addLayer(editableLayers);
placeMarker = L.Icon.extend({
options: {
shadowUrl: null,
iconAnchor: new L.Point(12, 40),
iconSize: new L.Point(25, 40),
iconUrl: 'marker-green.png'
}
});
map.on(L.Draw.Event.CREATED, function (e) {
var type = e.layerType;
var layer = e.layer;
if (type === 'marker') {
layer.bindPopup(popupText);
}
editableLayers.addLayer(layer);
map.my_current_marker = layer;
document.getElementById('_geometry_lon').value = layer._latlng.lng.toFixed(6);
document.getElementById('_geometry_lat').value = layer._latlng.lat.toFixed(6);
map.removeControl(map.my_drawControl);
map.my_drawControl = getDrawControl(false); // deactivate "add marker" after the 1st one
map.addControl(map.my_drawControl);
// fixme instantly enable 'edit' mode of layer
});
map.on('draw:editmove', function (e) {
console.log('editmove');
console.log(e);
document.getElementById('_geometry_lon').value = e.layer._latlng.lng.toFixed(6);
document.getElementById('_geometry_lat').value = e.layer._latlng.lat.toFixed(6);
});
map.my_editableLayers = editableLayers;
// map.my_drawControl = drawControl
map.my_placeMarker = placeMarker;
map.getDrawControl = getDrawControl;
map.updateMarkerFromForm = function () {
var lat = document.getElementById('_geometry_lat').value;
var lon = document.getElementById('_geometry_lon').value;
console.log('new lat: ' + lat + ' lon: ' + lon);
if (lat && lon) {
var coords = L.latLng(lat, lon);
if (map.my_current_marker) {
map.my_current_marker.setLatLng(coords);
} else {
map.my_current_marker = new L.marker([lat, lon], { icon: new map.my_placeMarker() });
map.my_current_marker.bindPopup(popupText);
map.my_editableLayers.addLayer(map.my_current_marker);
map.removeControl(map.my_drawControl);
map.my_drawControl = getDrawControl(false);
map.addControl(map.my_drawControl);
}
map.panTo(coords);
} else {
//delete marker
console.log('no coords, remove marker');
map.my_current_marker.remove();
delete map.my_current_marker;
map.removeControl(map.my_drawControl);
map.my_drawControl = getDrawControl(true); // allow "add marker" again
map.addControl(map.my_drawControl);
}
};
document.getElementById('_geometry_lat').onblur = map.updateMarkerFromForm;
document.getElementById('_geometry_lon').onblur = map.updateMarkerFromForm;
// console.log(map)
console.log('initMap end');
return map;
}
module.exports = initMap;
});
;require.register("lib/red_fetch.js", function(exports, require, module) {
'use strict';
/*
* This library provides a 'fetch', where you can use fallback URIs, to build on redundant servers.
*
* Mon 3 Oct 15:07:12 CEST 2016
* Michael Maier (species@github), WTFPL
*
* Give it an array of resources, that can be fetched from different urls.
* Will try to fetch them in the provided order.
* Execute successFunction on the first successful fetch, and errorFunction only if all resources fail to fetch.
*/
/* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://www.wtfpl.net/ for more details. */