-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1354 lines (1122 loc) · 39.8 KB
/
index.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
$(window).load(onDeviceReady)
var debug = false
var url_base = 'https://grid.my-poppy.eu/' // trailing / is important so that some QR code readers are able to read the url
var url_stats = 'https://grid.my-poppy.eu/stats.php'
var url_nominatim = "https://nominatim.openstreetmap.org/reverse?format=json"
var delta = 100; // in meters
var bea = 0; // in degrees
var invxy = 0, // 1 if inverse x & y
revy = 0 // 1 if reverse y (bottom to top instead of top to bottom)
var xlabels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v','w', 'x', 'y', 'z'];
var ylabels = ['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'];
var Nx0 = xlabels.length,
Ny0 = ylabels.length
var mycrs = null
var mysec = 0;
var WP = null;
var LG = null
var LH = null
var CM = null
var mymap = null
var map_state = 0
var map_first_view = true
var current_url = 0
var myurl = ''
var qrcode = null
var the_line = null
var sep_url = '?'
var myPhotonMarker = null
var WIDTH_LIMIT = 1049
var address_coords = null
var current_coords = null
var address_set = false
var acquiring_timeout = null
var tms = [
{ url:'', attr: 'Skobbler', subd:['1', '2', '3'], maxZoom:24, maxNativeZoom:18 },
{ url:'', attr: 'Mapbox', subd:['a', 'b', 'c'], maxZoom:24, maxNativeZoom:24 },
{ url:'', attr: 'Mapbox', subd:['a', 'b', 'c'], maxZoom:24, maxNativeZoom:24 }
]
var TL = null
var epsg_31370_str = '+lat_0=90 +lat_1=51.16666723333333 +lat_2=49.8333339 '
+'+lon_0=4.367486666666666 '
+'+x_0=150000.013 +y_0=5400088.438 '
+'+ellps=intl '
+'+proj=lcc '
+'+towgs84=-106.869,52.2978,-103.724,0.3366,-0.457,1.8422,-1.2747 '
+'+units=m '
+'+no_defs'
var editableLayers = null
var lineLayers = null
var blink_watch = null
var TYPEREF = 'master'
function onDeviceReady()
{
if ( ($(window).width() < 321) & ($(window).height() < 321) ) // small screen probably watch
{
$('.hide_for_wear').hide()
$('#mylastupdate').css('position', 'inherit').css('text-align', 'center')
}
$('.togglemap').click(toggle_map)
if ( !init() ) return false
/*if(window.applicationCache)
{
window.applicationCache.onupdateready = function(e)
{
window.alert('Une mise à jour est prête, rechargez la page pour la télécharger')
}
}*/
// ********************************************
// INITIALIZE GESTURES FOR THE MAP (HAMMER.JS)
// ********************************************
var myElement = document.getElementById('map2');
// create a manager for that element
var manager = new Hammer.Manager(myElement);
// create recognizers
var Pan = new Hammer.Pan();
var Pinch = new Hammer.Pinch();
var Rotate = new Hammer.Rotate();
// use them together
Rotate.recognizeWith([Pan]);
Pinch.recognizeWith([Rotate, Pan]);
// add the recognizers
manager.add(Pan);
manager.add(Rotate);
// subscribe to events
var currentRotation = 0, lastRotation, startRotation;
manager.on('rotatemove', function(e)
{
var diff = startRotation - Math.round(e.rotation);
currentRotation = lastRotation - diff;
mymap.setBearing(currentRotation)
});
manager.on('rotatestart', function(e)
{
lastRotation = currentRotation;
startRotation = Math.round(e.rotation);
});
manager.on('rotateend', function(e)
{
// cache the rotation
lastRotation = currentRotation;
});
if ($(window).width() < WIDTH_LIMIT)
{
make_interface_small()
}
}
function make_interface_small()
{
// adapt the interface to small screens
$('#btn-grid').html('① <i class="fa fa-pencil"></i> ' + msg.grid_short)
$('#btn-link').html('② <i class="fa fa-share-alt"></i> '+ msg.generate_short)
$('#btn-line').hide()
$('.lbr').show()
$('#btn-upload').html('① <i class="fa fa-upload"></i> ' + msg.parcours_short)
$('#btn-kml').html('③ <i class="fa fa-download"></i> ' + msg.KML_short)
$('.mapicons').css('width', '30%')
$('.my_or').hide()
}
function make_interface_large()
{
// adapt the interface to large screens
}
function init()
{
// explanation of quickgrid, privacy, disclaimer
var ret = window.confirm(msg.quickgrid_explain)
// if the user does not accept -> disconnect ; nothing is transmitted to the server
if (!ret)
{
$('body').html('<div style="text-align:center; padding-top:3em;font-weight:bold">DISCONNECTED</div>')
return false
}
// if no debugging session -> send stats to server -> only the timestamp + country (w/o 3rd party) + hash of the ip (to evaluate the number of unique visitors) are recorded
if (!debug) if (window.location.href.indexOf('my-poppy') > -1) // condition to avoid sending stats for tests
{
$.get(url_stats)
}
if (window.location.href.indexOf(sep_url) > -1) // a grid or a line is stored -- https://www.grid.my-poppy.eu?0,0,...
{
// *******************
// setup the interface
// *******************
$('#app2').hide()
$('#app').show()
$('#maptools').hide()
// *******************
// setup the map
// *******************
init_map()
$('#map2').css('height', '100%').css('position', 'fixed').css('top', '0').css('left', '0').css('right', '0').css('bottom', '0')
// *******************
// setup the events
// *******************
$('#myaddress').click(function(){get_address(current_coords)})
var s = window.location.href.split(sep_url)
s = s[1]
if ( (s.indexOf(',') == -1) & (s.indexOf(',') == -1) )
{
s = decodeURIComponent(s)
}
if (s.indexOf('lineblob') > -1) // IT IS A LINE
{
TYPEREF = 'line'
function callback(d)
{
var mylayers = L.geoJSON(d, {style: {color: '#f357a1',weight: 5}})
lineLayers.addLayer(mylayers)
var LL = mylayers.getLayers()[0]._latlngs
mycrs = new L.Proj.CRS("EPSG:999999","+proj=tmerc +lat_0="+LL[0].lat+" +lon_0="+LL[0].lng+" +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs");
the_line = build_line(LL)
show_km(LL, the_line.XY, the_line.s_sum, the_line.my_s)
}
// ***************************************
// retrieve the JSON blob & show the line
// ***************************************
var id = s.split('lineblob=')[1]
get_line(id, callback)
}
else // IT IS A GRID
{
var go = false
if (s.length > 4)
{
var x0y0
go = true
TYPEREF = 'grid'
// *******************
// decode the url
// *******************
s = s.split(',')
delta = s[2] // with of a square
bea = s[3] // bearing of the whole grid
var LAT0 = s[4] // coordinates of the top left corner of the grid
var LNG0 = s[5]
Nx0 = xlabels.length
Ny0 = xlabels.length
if (s.length > 6)
{
Nx0 = s[6] // number of squares in x
Ny0 = s[7] // number of squares in y
if (s.length > 8)
{
invxy = s[8] // inverse xy ? (figures in x, letters in y) -- 0 = false, 1 = true
revy = s[9] // reverse in y ? (bottom to top instead of top to bottom) -- 0 = false, 1 = true
}
}
// **************************************
// setup the coordinates reference system
// **************************************
if (s[0] == 0) // metric CRS, square anywhere on the world, dimensions not accurate
{
mycrs = new L.Proj.CRS("EPSG:999999","+proj=tmerc +lat_0="+LAT0+" +lon_0="+LNG0+" +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs");
x0y0 = {x:0, y:0}
}
else if (s[0] == '31370') // epsg 31370 -> lambert 72 -> works in Belgium only, perfectly metric
{
mycrs = new L.Proj.CRS('EPSG:31370', epsg_31370_str, { resolutions: [8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1] })
x0y0 = mycrs.projection.project({lat:LAT0, lng:LNG0})
}
else
{
go = false
}
// *******************
// shows the grid
// *******************
if (go)
{
show_grid(x0y0, xlabels, ylabels, delta, Nx0, Ny0, bea, invxy, revy)
}
}
if (!go)
{
window.alert(msg.error_url)
return false
}
}
// *************************************************
// tells the user that busy to acquire the location
// *************************************************
$("#myupdateicon").html('<i class="fa fa-spinner fa-spin"></i>')
$("#myupdatetext").html(msg.acquiring)
$('.tofilter').addClass('filter')
// *************************************************
// after 90 seconds of the initial acquisition
// if still busy : display a message to the user : check GPS, CHECK PRIVACY, ADVISE TO USE CHROME OR SAFARI (NO MESSENGER NOR QR CODE BROWSER)
// *************************************************
if (acquiring_timeout != null)
{
clearTimeout(acquiring_timeout)
acquiring_timeout = null
}
acquiring_timeout = setTimeout(function()
{
$("#myupdatetext").html(msg.acquiring + msg.acquiring_hint)
}, 90000)
// *******************
// acquires the location
// *******************
if (WP == null) get_position()
setInterval(
function()
{
check_last_update()
if (WP == null) get_position()
},
5000)
}
else // blank map -- https://www.grid.my-poppy.eu
{
// *******************
// setup the interface
// *******************
$('#app').hide()
$('#app2').show()
$('.togglemap').hide()
// *******************
// setup the map
// *******************
init_map()
$('.fa-chevron-left').parent().parent().parent().hide()
$('.fa-qrcode').parent().parent().parent().hide()
// *******************
// setup the events
// *******************
$('#btn-line').on('click', create_line )
$('#btn-grid').on('click', create_grid )
$('#btn-link').on('click', function(){ myurl_show(myurl) } )
$('#btn-kml').on('click',
function()
{
var kml = tokml(LH.toGeoJSON());
download(kml, 'poppy_quickgrid_' + Date.now() + '.kml', "text/plain");
})
}
if ($(window).width() < WIDTH_LIMIT)
{
$('.leaflet-control-easyPrint').hide()
$('.eb_to_hide').parent().parent().parent().hide()
}
return true
}
function myurl_show(myurl)
{
if (myurl == "")
{
window.alert(msg.link_explain);
return
}
$('#qrcode-wrap').css('top', $(window).height()/2-325/2).css('left', $(window).width()/2-275/2)
$("#qrcode-wrap").fadeIn()
$('#qrcode-text').text(myurl)
// if current == polyline
// store_line(editableLayers[0])
// + callback to show in the QR code
if (qrcode != null)
{
qrcode.clear()
qrcode.makeCode(myurl)
}
else
{
qrcode = new QRCode("qrcode",
{
text: myurl,
width: 175,
height: 175,
colorDark : "#000000",
colorLight : "#ffffff",
correctLevel : QRCode.CorrectLevel.L
});
}
}
function mobileAndTabletcheck()
{
// returns true if browser is mobile
//from : https://stackoverflow.com/questions/11381673/detecting-a-mobile-browser
var check = false;
(function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) check = true;})(navigator.userAgent||navigator.vendor||window.opera);
return check;
};
var current_feature = null
function create_line(e)
{
current_feature = 'polyline'
if (mobileAndTabletcheck() )
{
window.alert(msg.computer_needed)
}
else
{
window.alert(msg.line_explain);
//mymap.editTools.startPolyline(); // Leaflet.Editable
new L.Draw.Polyline(mymap, {shapeOptions: {color: '#f357a1',weight: 5 }}).enable() // Leaflet.Draw
}
}
function create_grid(e)
{
current_feature = 'rectangle'
if (mobileAndTabletcheck())
{
window.alert(msg.grid_explain)
mymap.on('dblclick', function(e)
{
delta = window.prompt(msg.square_size)
mycrs = new L.Proj.CRS("EPSG:999999","+proj=tmerc +lat_0="+e.latlng.lat+" +lon_0="+e.latlng.lng+" +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs");
var X0Y0 = mycrs.projection.project(e.latlng)
bea = mymap.getBearing()
show_grid(X0Y0, xlabels, ylabels, delta, xlabels.length, ylabels.length, bea, invxy, revy)
myurl = url_base + sep_url + Math.round(X0Y0.x) + ',' + Math.round(X0Y0.y) + ',' + delta + ',' + bea + ',' + e.latlng.lat + ',' + e.latlng.lng +',' + xlabels.length +',' + ylabels.length
mymap.off('dblclick')
})
}
else
{
window.alert(msg.grid_explain_draw);
if (LG != null)
{
mymap.removeLayer(LG)
}
//mymap.editTools.startRectangle(); // Leaflet.Editable
new L.Draw.Rectangle(mymap, {shapeOptions: {color: '#FFF'}}).enable(); // Leaflet.Draw
}
}
function toggle_map()
{
$('.togglemap').toggle()
$('#app').toggle()
$('#app2').toggle()
if (map_state == 0)
{
setTimeout(function(){$('#map2').css('position', 'fixed').css('top', '0').css('left', '0').css('right', '0').css('bottom', '0').css('height', '100%')}, 500)
mymap.invalidateSize()
get_position()
if (LG != null) mymap.fitBounds(LG.getBounds())
else if (lineLayers != null) mymap.fitBounds(lineLayers.getBounds())
if (map_first_view)
{
currentRotation = lastRotation = bea
mymap.setBearing(currentRotation)
map_first_view = false
}
}
map_state = 1-map_state
}
function myPhotonHandler(e)
{
var LL = [e.geometry.coordinates[1], e.geometry.coordinates[0]]
if (myPhotonMarker != null) mymap.removeLayer(myPhotonMarker)
myPhotonMarker = new L.CircleMarker(LL, {color: 'red',fillOpacity:.75,weight: 1})
myPhotonMarker.addTo(mymap)
mymap.setView(LL, 13);
}
function init_map()
{
$('#map2').height($(window).height() - $("#app2").height())
var options =
{
zoomControl: false,
rotate: true,
editable: true
}
if (!mobileAndTabletcheck())
{
options.zoomDelta = .25;
options.zoomSnap = .25;
}
mymap = L.map('map2', options).setView([50, 4], 13);
mymap.locate({setView : true, maxZoom:17});
L.control.scale().addTo(mymap);
L.easyButton('fa-chevron-left', toggle_map, 'back', 'topleft').addTo( mymap );
L.control.photon(
{
placeholder: msg.adress,
position: 'topleft',
onSelected: myPhotonHandler,
}).addTo(mymap);
TLayer_set()
L.control.zoom({position:'bottomright'}).addTo(mymap);
L.easyButton('fa-rotate-left', function(btn, map){ mymap.setBearing(mymap.getBearing()-2) }, 'rotate map', 'topright').addTo( mymap );
L.easyButton('fa-rotate-right', function(btn, map){ mymap.setBearing(mymap.getBearing()+2) }, 'rotate map', 'topright').addTo( mymap );
var animatedToggle = L.easyButton(
{
states: [ {
stateName: 'to-terrain',
icon: '<img height="22" src="img/mountain.svg">',
title: 'change basemap to terrain',
onClick: function(btn, map)
{
++current_url
current_url = current_url%tms.length
mymap.removeLayer(TL)
TLayer_set()
btn.state('to-roads-1');
}
},
{
stateName: 'to-roads-1',
icon: 'fa-road',
title: 'change basemap to roads',
onClick: function(btn, map)
{
++current_url
current_url = current_url%tms.length
mymap.removeLayer(TL)
TLayer_set()
btn.state('to-roads-2');
}
},
{
stateName: 'to-roads-2',
icon: 'fa-road',
title: 'change basemap to roads',
onClick: function(btn, map)
{
++current_url
current_url = current_url%tms.length
mymap.removeLayer(TL)
TLayer_set()
btn.state('to-terrain');
}
},
]
}) // , 'topright'
animatedToggle.addTo( mymap );
L.easyButton('fa-info-circle', function(btn, map)
{
window.alert( "Developed by Poppy, 2018\n"
+"contact: christophe@my-poppy.eu\n"
+"web: www.my-poppy.eu & blog.my-poppy.eu\n"
+"github: github.com/ccloquet/quickgrid\n"
+"\nCrédits:\n"
+"font-awesome-4.7.0 [github.com/FortAwesome/Font-Awesome/blob/master/LICENSE.txt]\n"
+"leaflet-1.3.1 fork by va2ron1 [github.com/va2ron1/Leaflet/blob/master/LICENSE]\n"
+"Leaflet.EasyButton-1.1.1 [github.com/CliffCloud/Leaflet.EasyButton/blob/master/LICENSE]\n"
+"Leaflet.Omnivore-0.3.3 [https://github.com/mapbox/leaflet-omnivore/blob/master/LICENSE]\n"
+"hammer-2.0.8.js [github.com/hammerjs/hammer.js/blob/master/LICENSE.md]\n"
+"Proj4Leaflet [github.com/kartena/Proj4Leaflet/blob/master/LICENSE]\n"
+"jquery-2.1.1 [github.com/jquery/jquery/blob/master/LICENSE.txt]\n"
+"leaflet-easyPrint [github.com/rowanwins/leaflet-easyPrint/blob/gh-pages/LICENSE]\n"
+"tokml.js [github.com/mapbox/tokml]\n"
+"download2.js [danml.com/download.html]\n"
+'Mountain icon made by www.freepik.com from flaticon.com is licensed by CC 3.0 BY (creativecommons.org/licenses/by/3.0)'
)
}, 'credits', 'bottomleft').addTo( mymap );
L.easyButton('fa-qrcode', function()
{
myurl_show(window.location.href)
}, 'qr code', 'bottomleft').addTo( mymap );
L.easyButton('fa-download eb_to_hide', function()
{
var kml = tokml(LH.toGeoJSON());
download(kml, 'poppy_quickgrid_' + Date.now() + '.kml', "text/plain");
}, 'download KML', 'bottomleft').addTo( mymap );
L.easyPrint(
{
title: 'Print',
position: 'bottomleft',
sizeModes: ['Current'],
}).addTo(mymap);
// set up editable layers
editableLayers = L.featureGroup().addTo(mymap)
lineLayers = L.featureGroup().addTo(mymap)
LH = L.featureGroup()
// Leaflet.Editable <<<
// 1. polyline : should store only when finished
// 2. polyline : should clean the old decorations when editing
// 3. rectangle : on create, fires both events...
// 4. rectangle : should find a better way to ask the user for grid division
// mymap.on('editable:drawing:commit', function(e){ set_new_editable_layer(e.layer, current_feature) })
// mymap.on('editable:vertex:dragend', function(e){ set_new_editable_layer(e.layer, current_feature) })
// Leaflet.Draw
mymap.on(L.Draw.Event.DRAWSTART, clear_editable_layers)
mymap.on(L.Draw.Event.CREATED, function(e){ set_new_editable_layer(e.layer, current_feature) });
var popup = null
editableLayers.on('mouseover', function(e)
{
var my_coords = L.latLng(e.latlng), idx
switch(TYPEREF)
{
/*case 'grid': g = getSquarePoint(mycrs, my_coords, delta, bea, xlabels, ylabels)
idx = g.mysquare
break;*/
case 'line': if (the_line != null)
{
g = getKm(mycrs, my_coords, the_line.XY, the_line.my_s)
idx = g.km
}
popup = L.popup()
.setLatLng(e.latlng)
.setContent(idx)
.openOn(mymap);
break;
}
})
editableLayers.on('mouseout', function(e)
{
if (popup != null) popup.closePopup();
popup = null
})
}
function clear_editable_layers()
{
myurl = ''
for (var x in editableLayers._layers)
{
if (editableLayers._layers.hasOwnProperty(x))
{
mymap.removeLayer(editableLayers._layers[x])
}
}
// should add
// if relevant :
// mymap.removeLayer(LG)
// mymap.removeLayer(LH)
}
function set_new_editable_layer(layer, type)
{
var LL = layer._latlngs
switch(type)
{
case 'polyline':
// 1. build local CRS
mycrs = new L.Proj.CRS("EPSG:999999","+proj=tmerc +lat_0="+LL[0].lat+" +lon_0="+LL[0].lng+" +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs");
editableLayers.addLayer(layer)
LH = L.featureGroup()
LH.addLayer(layer)
// 2. build & draw the array of segments lengths
var my_line = build_line(LL)
show_km(LL, my_line.XY, my_line.s_sum, my_line.my_s)
// 3. convert to geoJSON and store
store_line(layer)
break;
case 'rectangle':
//LL = LL[0] // Leaflet.Editable
var delta_list = [1, 1.5, 2,2.5,3,5,7.5,10,15,20,25,30,50,75,100,150,200,250,300,500,750,1000, 1500, 2000, 2500, 3000, 5000, 7500, 10000]
var LL_P_1 = 0, LL_P_3 = 0, j = -1, k = 1
var b = mymap.getBearing()
var s = 1
if ( ((b > 90) & (b < 270)) | (b < -90) & (b > -270) ) s = -1
while ( ! ((s*LL_P_1.x > 0) & (s*LL_P_3.y < 0)) ) // find the right orientation (otherwise, if start drawing from lower right -> does not display the grid correctly)
{
// iterate clockwise & counter clockwise
if (j == 4) {j = 0; k = -1}
++j
// 1. build local CRS
mycrs = new L.Proj.CRS("EPSG:999999","+proj=tmerc +lat_0="+LL[mod(j,4)].lat+" +lon_0="+LL[mod(j,4)].lng+" +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs");
LL_P_1 = mycrs.projection.project(LL[mod(j+k*1,4)])
LL_P_3 = mycrs.projection.project(LL[mod(j+k*3,4)])
}
var dx = Math.ceil(Math.sqrt(LL_P_1.x*LL_P_1.x + LL_P_1.y*LL_P_1.y)) // size in x
var dy = Math.ceil(Math.sqrt(LL_P_3.x*LL_P_3.x + LL_P_3.y*LL_P_3.y)) // size in y
editableLayers.addLayer(layer)
var my_delta = [] // suggested grid sizes
for (var i=0; i<delta_list.length; ++i)
{
if ( (delta_list[i] >= dx/xlabels.length) & (delta_list[i] < dx/4)) my_delta.push({delta:delta_list[i], Nx:Math.ceil(dx/delta_list[i]), Ny:Math.ceil(dy/delta_list[i])})
}
var txt = msg.grid_choose+'\n\n'
for (var i=0; i<my_delta.length; ++i)
{
txt += '[' + String.fromCharCode(65+i) + '] ' + my_delta[i].Nx + ' x ' + my_delta[i].Ny + ' (' + my_delta[i].delta + ' m)\n'
}
txt += msg.perso_size_between+Math.ceil(dx/xlabels.length)+' '+msg.and+' '+Math.floor(dx/4)+' m) :'
var delta = null, Nx, Ny
var ret = window.prompt(txt)
if (ret == null) return false
ret = ret.toUpperCase()
var J = ret.charCodeAt()-65
if ($.isNumeric(ret))
{
delta = ret
Nx = Math.ceil(dx/ret)
Ny = Math.ceil(dy/ret)
}
else if ((J >= 0) & (J <my_delta.length))
{
delta = my_delta[J].delta
Nx = my_delta[J].Nx
Ny = my_delta[J].Ny
}
if (delta != null)
{
bea = mymap.getBearing()
show_grid({x:0, y:0}, xlabels, ylabels, delta, Nx, Ny, bea, invxy, revy)
myurl = url_base + sep_url + '0,0,' + delta + ',' + bea + ',' + LL[mod(j,4)].lat + ',' + LL[mod(j,4)].lng + ',' + Nx + ',' + Ny
}
break;
}
}
function mod(n, m) {
return ((n % m) + m) % m;
}
function TLayer_set()
{
TL = L.tileLayer(tms[current_url].url,
{
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors + '+tms[current_url].attr+', <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>',
subdomains: tms[current_url].subd,
maxZoom: tms[current_url].maxZoom,
maxNativeZoom: tms[current_url].maxNativeZoom,
opacity: 0.5,
}).addTo(mymap);
}
function show_grid(latlng_31370, xlabels, ylabels, delta, Nx, Ny, b, invxy, revy)
{
// lowlevel grid
var G = [], H = [],
cb = Math.cos(b*Math.PI/180),
sb = Math.sin(b*Math.PI/180),
x0 = parseFloat(latlng_31370.x), // ! parseFloat ! otherwise string concat !!
y0 = parseFloat(latlng_31370.y)
for(var i=0; i<Nx; ++i)
{
for(var j=0; j<Ny; ++j)
{
var xy_center = {x: x0 + cb * (i+.5) * delta + sb * (j+.5) * delta , y: y0 + sb * (i+.5) * delta - cb * (j+.5) * delta}
var LL = mycrs.projection.unproject(xy_center) // center of the square
var LL_TL = mycrs.projection.unproject({x: x0 + cb*(i+0)*delta + sb*(j+0) * delta, y: y0 + sb*(i+0)*delta - cb*(j+0) * delta}) // top left
var LL_TR = mycrs.projection.unproject({x: x0 + cb*(i+1)*delta + sb*(j+0) * delta, y: y0 + sb*(i+1)*delta - cb*(j+0) * delta}) // top right
var LL_BL = mycrs.projection.unproject({x: x0 + cb*(i+0)*delta + sb*(j+1) * delta, y: y0 + sb*(i+0)*delta - cb*(j+1) * delta}) // bottom left
var LL_BR = mycrs.projection.unproject({x: x0 + cb*(i+1)*delta + sb*(j+1) * delta, y: y0 + sb*(i+1)*delta - cb*(j+1) * delta}) // bottom right
var lat_lngs = [LL_TL, LL_TR, LL_BR, LL_BL, LL_TL]
var myname = ''
var newj = j
if (revy == 1) newj = Ny - 1 - j
if (invxy == 1)
{
myname = xlabels[newj].toUpperCase() + ylabels[i]
}
else
{
myname = xlabels[i].toUpperCase()+ylabels[newj];
}
if ( ( (i%2==0) & (j%2==0) ) )
{
var myIcon = L.divIcon({className:'emptyicon', html: myname});
var marker = L.marker(LL, {icon: myIcon})
marker.properties = {};
//marker.properties.Name = "Test"
G.push(marker)
H.push(L.marker(LL, {icon: myIcon, name: myname })); // to display the names
}
if ( (i == 0) | (j == 0 ) )
{
var myIcon = L.divIcon({className:'boldicon', html: myname});
G.push(L.marker(LL, {icon: myIcon}))
H.push(L.marker(LL, {icon: myIcon, name: myname })); // to display the names
}
// one idea to draw squares ... but they are not square given the coordinate transsformation
// var circle = new L.Circle(LL, delta/2);
// G.push(new L.Rectangle(circle.getBounds(), {color: 'white',fillOpacity:0,weight: 1}));
// center of the squares
//G.push(new L.CircleMarker(LL, {color: 'white',fillOpacity:.5,weight: 1}));
G.push(new L.Polyline(lat_lngs, {color: 'darkgray',fillOpacity:0,weight: 1}));
H.push(new L.Polyline(lat_lngs, {color: 'darkgray',fillOpacity:0,weight: 1})); // name might be here, but then misplaced in Google Maps for instance (QGIS would be OK)
}
}
// High level grid delienation
var LL_TL = mycrs.projection.unproject({x: x0, y: y0}) // top left
var LL_TR = mycrs.projection.unproject({x: x0 + cb * Nx * delta, y: y0 + sb * Nx * delta}) // top right
var LL_BL = mycrs.projection.unproject({x: x0 + sb * Ny * delta, y: y0 - cb * Ny * delta}) // bottom left
var LL_BR = mycrs.projection.unproject({x: x0 + cb * Nx * delta + sb * Ny * delta, y: y0 + sb * Nx * delta - cb * Ny * delta}) // bottom right
var lat_lngs = [LL_TL, LL_TR, LL_BR, LL_BL, LL_TL]
G.push(new L.Polyline(lat_lngs, {color: 'yellow', fillOpacity:0,weight: 3}));
LG = L.featureGroup(G).addTo(mymap) // to draw
LH = L.featureGroup(H) // to download
}
function check_last_update()
{
var e = new Date();
var mynewsec = e.getTime()/1000;
if ((mysec > 0) & ( (mynewsec - mysec) > 35 ))
{
// GPS ERROR CASE
$("#myupdateicon").html('<i style="color:yellow" class="blink fa fa-exclamation-triangle"></i>')
$("#myupdatetext").html('<span style="color:yellow" class="blink">'+msg.update_error+'</span>' )
start_blink()
navigator.geolocation.clearWatch(WP)
WP = null
$('.tofilter').addClass('filter')
}
}
function get_address(coords)
{
if (coords == null) return false;
$('#myaddress_0').hide()
$('#myaddress_2').show(); $('#myaddress_2').text(msg.waiting)
$('#myaddress_1').show(); $('#myaddress_1').text('⏳')
$.get(url_nominatim + '&lon=' + coords.lng + '&lat=' + coords.lat,
function(e)
{
var road = msg.unknown, city = ""
if (e != null) if (e.address != null)
{
var f = e.address
road = ""
if (f.road != null) road += f.road + " "
if (f.house_number != null) road += f.house_number
if (f.village != null) city = f.village
else if (f.town != null) city = f.town
else if (f.suburb != null) city = f.suburb
$('#myaddress_1').text( '🕓 ' + current_time_hh_mm(new Date()) + ' ▷ ' + msg.close_to)
$('#myaddress_2').text(road + ', ' + city )
address_set = true
address_coords = coords
console.log(road, city, e)
}
}, 'json')
}
function get_position()
{
var mytimeout = 60000, g
current_coords
WP = navigator.geolocation.watchPosition(
function(p)
{
var my_coords = {lng:p.coords.longitude ,lat: p.coords.latitude}
current_coords = my_coords
if (address_set)
{
if (mymap.distance(my_coords, address_coords) > 10)
{
$('#myaddress_0').show()
$('#myaddress_1').hide(); $('#myaddress_1').text('')
$('#myaddress_2').hide(); $('#myaddress_2').text('')
address_set = false
address_coords = null
}
}
if (map_state == 1)
{
if (CM != null) mymap.removeLayer(CM)
CM = L.circleMarker( my_coords )
CM.addTo(mymap)
}
switch(TYPEREF)
{
case 'grid': g = getSquarePoint(mycrs, my_coords, delta, bea, xlabels, ylabels)
$('#mysquare').html(g.mysquare)
break;
case 'line': if (the_line != null)
{
g = getKm(mycrs, my_coords, the_line.XY, the_line.my_s)
$('#mysquare').html(g.km)
}
break;
}
if (p.coords.accuracy > delta / 3)
{
// if the accuracy (radius of the 95%-confidence circle where the Lat/Lon lies) is larger than delta, then display the accuracy in bold yellow
$('#myaccuracy').addClass('inaccurate')
}
else
{
$('#myaccuracy').removeClass('inaccurate')
}
$('#myaccuracy').html('± ' + Math.round(p.coords.accuracy) + " m" )
var mylat = Math.round(p.coords.latitude*10000)/10000
var mylng = Math.round(p.coords.longitude*10000)/10000
if (mylat < 0) mylat = (-mylat) + '° S'
else mylat += '° N'
if (mylng < 0) mylng = (-mylng) + '° E'
else mylng += '° W'
$('#mywgs84').html(mylat + ', ' + mylng)
var d = new Date(p.timestamp);
$("#myupdateicon").html('<i class="fa fa-clock-o"></i>')
$("#myupdatetext").html(msg.update+' ' + d.getDate() + "/" + (d.getMonth() +1) + "/" + d.getFullYear() + " " + current_time_hh_mm(d) + ":" + (d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds()) )
// clear acquiring_timeout that was set up to warn the user in case of initial issues with GPS/PRIVACY/BROWSER
if (acquiring_timeout != null)
{