forked from Geolicious/qgis2leaf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
qgis2leaf_exec.py
1117 lines (1078 loc) · 51.5 KB
/
qgis2leaf_exec.py
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
# -*- coding: utf-8 -*-
"""
/***************************************************************************
qgis2leaf
A QGIS plugin
QGIS to Leaflet creation programm
-------------------
begin : 2014-04-29
copyright : (C) 2013 by Riccardo Klinger
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 3 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
from PyQt4.QtCore import QFileInfo
import osgeo.ogr, osgeo.osr #we will need some packages
from osgeo import ogr
from osgeo import gdal
import processing
import shutil
from qgis.core import *
import qgis.utils
import os #for file writing/folder actions
import shutil #for reverse removing directories
import urllib # to get files from the web
import time
import tempfile
import re
import fileinput
import webbrowser #to open the made map directly in your browser
import sys #to use another print command without annoying newline characters
def layerstyle_single(layer):
return color_code
def qgis2leaf_exec(outputProjectFileName, basemapName, basemapMeta, basemapAddress, width, height, extent, full, layer_list, visible, opacity_raster, encode2JSON, cluster_set, webpage_name, webmap_head,webmap_subhead, legend, locate, address):
# supply path to where is your qgis installed
#QgsApplication.setPrefixPath("/path/to/qgis/installation", True)
pluginDir = os.path.dirname(os.path.realpath(__file__))
cluster_num = 1
# load providers
QgsApplication.initQgis()
# let's determine the current work folder of qgis:
print os.getcwd()
print layer_list
# let's create the overall folder structure:
outputProjectFileName = os.path.join(outputProjectFileName, 'export_' + str(time.strftime("%Y_%m_%d")) + '_' + str(time.strftime("%I_%M_%S")))
jsStore = os.path.join(os.getcwd(),outputProjectFileName, 'js')
os.makedirs(jsStore)
shutil.copyfile(pluginDir + os.sep + 'js' + os.sep + 'Autolinker.min.js', jsStore + os.sep + 'Autolinker.min.js')
shutil.copyfile(pluginDir + os.sep + 'js' + os.sep + 'leaflet.markercluster.js', jsStore + os.sep + 'leaflet.markercluster.js')
dataStore = os.path.join(os.getcwd(),outputProjectFileName, 'data')
os.makedirs(dataStore)
cssStore = os.path.join(os.getcwd(),outputProjectFileName, 'css')
os.makedirs(cssStore)
shutil.copyfile(pluginDir + os.sep + 'css' + os.sep + 'MarkerCluster.css', cssStore + os.sep + 'MarkerCluster.css')
shutil.copyfile(pluginDir + os.sep + 'css' + os.sep + 'MarkerCluster.Default.css', cssStore + os.sep + 'MarkerCluster.Default.css')
picturesStore = os.path.join(os.getcwd(),outputProjectFileName, 'pictures')
os.makedirs(picturesStore)
miscStore = os.path.join(os.getcwd(),outputProjectFileName, 'misc')
os.makedirs(miscStore)
#lets create a css file for own css:
with open(os.path.join(os.getcwd(),outputProjectFileName) + os.sep + 'css' + os.sep + 'own_style.css', 'w') as f_css:
if full == 1:
text = """
<style>
body {
padding: 0;
margin: 0;
}
html, body, #map {
height: 100%;
width: 100%;
padding: 0;
margin: 0;
}
th {
text-align: left;
vertical-align: top;
}
"""
elif full == 0:
text = """
<style>
body {
padding: 0;
margin: 0;
}
html, body, #map {
height: """+str(height)+"""px;
width: """+str(width)+"""px;
}
th {
text-align: left;
vertical-align: top;
}
"""
if opacity_raster == True and full == 1:
text += """
html, body, #slide {
width: 100%;
padding: 0;
margin: 0;
}
"""
elif opacity_raster == True and full== 0:
text += """
html, body, #slide {
width: """+str(width)+"""px;
padding: 0;
margin: 0;
}
"""
elif opacity_raster == False:
text += """
"""
text += """
.info {
padding: 6px 8px;
font: 14px/16px Arial, Helvetica, sans-serif;
background: white;
background: rgba(255,255,255,0.8);
box-shadow: 0 0 15px rgba(0,0,0,0.2);
border-radius: 5px;
}
.info h2 {
margin: 0 0 5px;
color: #777;
}
</style>"""
f_css.write(text)
f_css.close()
#the index file has an easy beginning. we will store it right away:
with open(os.path.join(os.getcwd(),outputProjectFileName) + os.sep + 'index.html', 'w') as f_html:
base = """
<!DOCTYPE html>
<html>
<head> """
if webpage_name == "":
base +="""
<title>QGIS2leaf webmap</title>
"""
else:
base +="""
<title>""" + (webpage_name).encode('utf-8') + """</title>
"""
base += """
<meta charset="utf-8" />
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.2/leaflet.css" /> <!-- we will us e this as the styling script for our webmap-->
<link rel="stylesheet" href="css/MarkerCluster.css" />
<link rel="stylesheet" href="css/MarkerCluster.Default.css" />
<link rel="stylesheet" type="text/css" href="css/own_style.css">"""
if address == True:
base += """
<link rel="stylesheet" href="http://k4r573n.github.io/leaflet-control-osm-geocoder/Control.OSMGeocoder.css" /> """
base +="""
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <!-- this is the javascript file that does the magic-->
<script src="js/Autolinker.min.js"></script>"""
if full == 1:
base +="""
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />"""
base += """
</head>
<body>
<div id="map"></div> <!-- this is the initial look of the map. in most cases it is done externally using something like a map.css stylesheet were you can specify the look of map elements, like background color tables and so on.-->
<script src="http://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.2/leaflet.js"></script> <!-- this is the javascript file that does the magic-->"""
if address == True:
base +="""
<script src="http://k4r573n.github.io/leaflet-control-osm-geocoder/Control.OSMGeocoder.js"></script>"""
base +="""
<script src="js/leaflet.markercluster.js"></script>
"""
if opacity_raster == True:
base += """<input id="slide" type="range" min="0" max="1" step="0.1" value="1" onchange="updateOpacity(this.value)">"""
f_html.write(base)
f_html.close()
# let's create the js files in the data folder of input vector files:
canvas = qgis.utils.iface.mapCanvas()
allLayers = canvas.layers()
exp_crs = QgsCoordinateReferenceSystem(4326, QgsCoordinateReferenceSystem.EpsgCrsId)
for i in allLayers:
for j in layer_list:
if re.sub('[\W_]+', '', i.name()) == re.sub('[\W_]+', '', j):
if i.providerType() != 'WFS' or encode2JSON == True and i:
if i.type() ==0:
qgis.core.QgsVectorFileWriter.writeAsVectorFormat(i,dataStore + os.sep + 'exp_' + re.sub('[\W_]+', '', i.name()) + '.js', 'utf-8', exp_crs, 'GeoJson')
#now change the data structure to work with leaflet:
with open(dataStore + os.sep + 'exp_' + re.sub('[\W_]+', '', i.name()) + '.js', "r+") as f2:
old = f2.read() # read everything in the file
f2.seek(0) # rewind
f2.write("var exp_" + str(re.sub('[\W_]+', '', i.name())) + " = " + old) # write the new line before
f2.close
#let's define style for the single marker points
if i.rendererV2().dump()[0:6] == 'SINGLE' and i.geometryType() == 0:
color_str = str(i.rendererV2().symbol().color().name())
radius_str = str(i.rendererV2().symbol().size() * 2)
transp_str = str(1 - ( float(i.layerTransparency()) / 100 ) )
transp_str2 = str(i.rendererV2().symbol().alpha())
for line in fileinput.FileInput(dataStore + os.sep + 'exp_' + re.sub('[\W_]+', '', i.name()) + '.js',inplace=1):
line = line.replace(""""type": "Feature", "properties": { """,""""type": "Feature", "properties": { "color_qgis2leaf": '""" + color_str + """', "radius_qgis2leaf": """ + radius_str + """, "transp_qgis2leaf": """ + transp_str + """, "transp_fill_qgis2leaf": """ + transp_str2 + """, """ )
sys.stdout.write(line)
#let's define style for the single marker lines
if i.rendererV2().dump()[0:6] == 'SINGLE' and i.geometryType() == 1:
color_str = str(i.rendererV2().symbol().color().name())
radius_str = str(i.rendererV2().symbol().width() * 5)
transp_str = str(1 - ( float(i.layerTransparency()) / 100 ) )
transp_str2 = str(i.rendererV2().symbol().alpha())
for line in fileinput.FileInput(dataStore + os.sep + 'exp_' + re.sub('[\W_]+', '', i.name()) + '.js',inplace=1):
line = line.replace(""""type": "Feature", "properties": { """,""""type": "Feature", "properties": { "color_qgis2leaf": '""" + color_str + """', "radius_qgis2leaf": """ + radius_str + """, "transp_qgis2leaf": """ + transp_str + """, "transp_fill_qgis2leaf": """ + transp_str2 + """, """ )
sys.stdout.write(line)
#let's define style for the single marker polygons
if i.rendererV2().dump()[0:6] == 'SINGLE' and i.geometryType() == 2:
if i.rendererV2().symbol().symbolLayer(0).layerType() == 'SimpleLine':
color_str = 'none'
borderColor_str = str(i.rendererV2().symbol().color().name())
radius_str = str(i.rendererV2().symbol().symbolLayer(0).width() * 5)
else:
color_str = str(i.rendererV2().symbol().color().name())
borderColor_str = str(i.rendererV2().symbol().symbolLayer(0).borderColor().name())
radius_str = str(i.rendererV2().symbol().symbolLayer(0).borderWidth() * 5)
transp_str = str(1 - ( float(i.layerTransparency()) / 100 ) )
transp_str2 = str(i.rendererV2().symbol().alpha())
for line in fileinput.FileInput(dataStore + os.sep + 'exp_' + re.sub('[\W_]+', '', i.name()) + '.js',inplace=1):
line = line.replace(""""type": "Feature", "properties": { """,""""type": "Feature", "properties": { "color_qgis2leaf": '""" + color_str + """', "border_color_qgis2leaf": '""" + borderColor_str + """', "radius_qgis2leaf": """ + radius_str + """, "transp_qgis2leaf": """ + transp_str + """, "transp_fill_qgis2leaf": """ + transp_str2 + """, """ )
sys.stdout.write(line)
#let's define style for categorized points
if i.rendererV2().dump()[0:11] == 'CATEGORIZED' and i.geometryType() == 0:
iter = i.getFeatures()
provider = i.dataProvider()
attrvalindex = provider.fieldNameIndex(i.rendererV2().classAttribute())
categories = i.rendererV2().categories()
color_str = []
radius_str = []
transp_str2 = []
transp_str = str(1 - ( float(i.layerTransparency()) / 100 ) )
for feat in iter:
fid = feat.id()
attribute_map = feat.attributes()
catindex = i.rendererV2().categoryIndexForValue(unicode(attribute_map[attrvalindex]))
if catindex != -1:
color_str.append(str(categories[catindex].symbol().color().name()))
radius_str.append(str(categories[catindex].symbol().size() * 2))
transp_str2.append(str(categories[catindex].symbol().alpha()))
else:
color_str.append('#FF00FF')
radius_str.append('4')
transp_str2.append('1')
qgisLeafId = 0
for line in fileinput.FileInput(dataStore + os.sep + 'exp_' + re.sub('[\W_]+', '', i.name()) + '.js',inplace=1):
addOne = str(line).count(""""type": "Feature", "properties": { """)
if qgisLeafId < len(color_str):
line = line.replace(""""type": "Feature", "properties": { """,""""type": "Feature", "properties": { "id_qgis2leaf": """ + str(qgisLeafId) + """, "color_qgis2leaf": '""" + str(color_str[qgisLeafId]) + """', "radius_qgis2leaf": """ + str(radius_str[qgisLeafId]) + """, "transp_qgis2leaf": """ + str(transp_str) + """, "transp_fill_qgis2leaf": """ + str(transp_str2[qgisLeafId]) + """, """ )
else:
line = line.replace(" "," ")
sys.stdout.write(line)
qgisLeafId = qgisLeafId+addOne
#let's define style for categorized lines
if i.rendererV2().dump()[0:11] == 'CATEGORIZED' and i.geometryType() == 1:
iter = i.getFeatures()
provider = i.dataProvider()
attrvalindex = provider.fieldNameIndex(i.rendererV2().classAttribute())
categories = i.rendererV2().categories()
color_str = []
radius_str = []
transp_str2 = []
transp_str = str(1 - ( float(i.layerTransparency()) / 100 ) )
for feat in iter:
fid = feat.id()
attribute_map = feat.attributes()
catindex = i.rendererV2().categoryIndexForValue(unicode(attribute_map[attrvalindex]))
if catindex != -1:
color_str.append(str(categories[catindex].symbol().color().name()))
radius_str.append(str(categories[catindex].symbol().width() * 5))
transp_str2.append(str(categories[catindex].symbol().alpha()))
else:
color_str.append('#FF00FF')
radius_str.append('4')
transp_str2.append('1')
qgisLeafId = 0
for line in fileinput.FileInput(dataStore + os.sep + 'exp_' + re.sub('[\W_]+', '', i.name()) + '.js',inplace=1):
addOne = str(line).count(""""type": "Feature", "properties": { """)
if qgisLeafId < len(color_str):
line = line.replace(""""type": "Feature", "properties": { """,""""type": "Feature", "properties": { "id_qgis2leaf": """ + str(qgisLeafId) + """, "color_qgis2leaf": '""" + str(color_str[qgisLeafId]) + """', "radius_qgis2leaf": """ + str(radius_str[qgisLeafId]) + """, "transp_qgis2leaf": """ + str(transp_str) + """, "transp_fill_qgis2leaf": """ + str(transp_str2[qgisLeafId]) + """, """ )
else:
line = line.replace(" "," ")
sys.stdout.write(line)
qgisLeafId = qgisLeafId+addOne
#let's define style for categorized polygons
if i.rendererV2().dump()[0:11] == 'CATEGORIZED' and i.geometryType() == 2:
iter = i.getFeatures()
provider = i.dataProvider()
attrvalindex = provider.fieldNameIndex(i.rendererV2().classAttribute())
categories = i.rendererV2().categories()
color_str = []
radius_str = []
transp_str2 = []
transp_str = str(1 - ( float(i.layerTransparency()) / 100 ) )
for feat in iter:
fid = feat.id()
attribute_map = feat.attributes()
catindex = i.rendererV2().categoryIndexForValue(unicode(attribute_map[attrvalindex]))
if catindex != -1:
color_str.append(str(categories[catindex].symbol().color().name()))
transp_str2.append(str(categories[catindex].symbol().alpha()))
else:
color_str.append('#FF00FF')
transp_str2.append('1')
qgisLeafId = 0
for line in fileinput.FileInput(dataStore + os.sep + 'exp_' + re.sub('[\W_]+', '', i.name()) + '.js',inplace=1):
addOne = str(line).count(""""type": "Feature", "properties": { """)
if qgisLeafId < len(color_str):
line = line.replace(""""type": "Feature", "properties": { """,""""type": "Feature", "properties": { "id_qgis2leaf": """ + str(qgisLeafId) + """, "color_qgis2leaf": '""" + str(color_str[qgisLeafId]) + """', "transp_qgis2leaf": """ + str(transp_str) + """, "transp_fill_qgis2leaf": """ + str(transp_str2[qgisLeafId]) + """, """ )
else:
line = line.replace(" "," ")
sys.stdout.write(line)
qgisLeafId = qgisLeafId+addOne
#let's define style for the graduaded marker points
if i.rendererV2().dump()[0:9] == 'GRADUATED' and i.geometryType() == 0:
# every json entry needs a unique id:
iter = i.getFeatures()
#what is the value based on:
provider = i.dataProvider()
attrvalindex = provider.fieldNameIndex(i.rendererV2().classAttribute())
transp_str = str(1 - ( float(i.layerTransparency()) / 100 ) )
color_str = []
radius_str = []
transp_str2 = []
for feat in iter:
if str(feat.attributes()[attrvalindex]) != 'NULL':
value = feat.attributes()[attrvalindex]
elif str(feat.attributes()[attrvalindex]) == 'NULL':
value = None
for r in i.rendererV2().ranges():
if value >= r.lowerValue() and value <= r.upperValue() and value != None:
color_str.append(str(r.symbol().color().name()))
radius_str.append(str(r.symbol().size() * 2))
transp_str2.append(str(r.symbol().alpha()))
break
elif value == None:
color_str.append('#FF00FF')
radius_str.append('4')
transp_str2.append('1')
break
qgisLeafId = 0
for line in fileinput.FileInput(dataStore + os.sep + 'exp_' + re.sub('[\W_]+', '', i.name()) + '.js',inplace=1):
addOne = str(line).count(""""type": "Feature", "properties": { """)
if qgisLeafId < len(color_str):
line = line.replace(""""type": "Feature", "properties": { """,""""type": "Feature", "properties": { "id_qgis2leaf": """ + str(qgisLeafId) + """, "color_qgis2leaf": '""" + str(color_str[qgisLeafId]) + """', "radius_qgis2leaf": """ + str(radius_str[qgisLeafId]) + """, "transp_qgis2leaf": """ + str(transp_str) + """, "transp_fill_qgis2leaf": """ + str(transp_str2[qgisLeafId]) + """, """ )
else:
line = line.replace(" "," ")
sys.stdout.write(line)
qgisLeafId = qgisLeafId+addOne
#let's define style for the graduaded marker line
if i.rendererV2().dump()[0:9] == 'GRADUATED' and i.geometryType() == 1:
# every json entry needs a unique id:
iter = i.getFeatures()
#what is the value based on:
provider = i.dataProvider()
attrvalindex = provider.fieldNameIndex(i.rendererV2().classAttribute())
transp_str = str(1 - ( float(i.layerTransparency()) / 100 ) )
color_str = []
radius_str = []
transp_str2 = []
for feat in iter:
if str(feat.attributes()[attrvalindex]) != 'NULL':
value = feat.attributes()[attrvalindex]
elif str(feat.attributes()[attrvalindex]) == 'NULL':
value = None
for r in i.rendererV2().ranges():
if value >= r.lowerValue() and value <= r.upperValue() and value != None:
color_str.append(str(r.symbol().color().name()))
radius_str.append(str(r.symbol().width() * 5))
transp_str2.append(str(r.symbol().alpha()))
break
elif value == None:
color_str.append('#FF00FF')
radius_str.append('4')
transp_str2.append('1')
break
qgisLeafId = 0
for line in fileinput.FileInput(dataStore + os.sep + 'exp_' + re.sub('[\W_]+', '', i.name()) + '.js',inplace=1):
addOne = str(line).count(""""type": "Feature", "properties": { """)
if qgisLeafId < len(color_str):
line = line.replace(""""type": "Feature", "properties": { """,""""type": "Feature", "properties": { "id_qgis2leaf": """ + str(qgisLeafId) + """, "color_qgis2leaf": '""" + str(color_str[qgisLeafId]) + """', "radius_qgis2leaf": """ + str(radius_str[qgisLeafId]) + """, "transp_qgis2leaf": """ + str(transp_str) + """, "transp_fill_qgis2leaf": """ + str(transp_str2[qgisLeafId]) + """, """ )
else:
line = line.replace(" "," ")
sys.stdout.write(line)
qgisLeafId = qgisLeafId+addOne
#let's define style for the graduaded marker polygon
if i.rendererV2().dump()[0:9] == 'GRADUATED' and i.geometryType() == 2:
# every json entry needs a unique id:
iter = i.getFeatures()
#what is the value based on:
provider = i.dataProvider()
attrvalindex = provider.fieldNameIndex(i.rendererV2().classAttribute())
transp_str = str(1 - ( float(i.layerTransparency()) / 100 ) )
color_str = []
radius_str = []
transp_str2 = []
for feat in iter:
if str(feat.attributes()[attrvalindex]) != 'NULL':
value = feat.attributes()[attrvalindex]
elif str(feat.attributes()[attrvalindex]) == 'NULL':
value = None
for r in i.rendererV2().ranges():
if value >= r.lowerValue() and value <= r.upperValue() and value != None:
color_str.append(str(r.symbol().color().name()))
transp_str2.append(str(r.symbol().alpha()))
break
elif value == None:
color_str.append('#FF00FF')
transp_str2.append('1')
break
qgisLeafId = 0
for line in fileinput.FileInput(dataStore + os.sep + 'exp_' + re.sub('[\W_]+', '', i.name()) + '.js',inplace=1):
addOne = str(line).count(""""type": "Feature", "properties": { """)
if qgisLeafId < len(color_str):
line = line.replace(""""type": "Feature", "properties": { """,""""type": "Feature", "properties": { "id_qgis2leaf": """ + str(qgisLeafId) + """, "color_qgis2leaf": '""" + str(color_str[qgisLeafId]) + """', "transp_qgis2leaf": """ + str(transp_str) + """, "transp_fill_qgis2leaf": """ + str(transp_str2[qgisLeafId]) + """, """ )
else:
line = line.replace(" "," ")
sys.stdout.write(line)
qgisLeafId = qgisLeafId+addOne
#now add the js files as data input for our map
with open(os.path.join(os.getcwd(),outputProjectFileName) + os.sep + 'index.html', 'a') as f3:
new_src = """
<script src='""" + 'data' + """/exp_""" + re.sub('[\W_]+', '', i.name()) + """.js' ></script>
"""
# store everything in the file
f3.write(new_src)
f3.close()
#here comes the raster layers. you need an installed version of gdal
elif i.type() == 1:
in_raster = str(i.dataProvider().dataSourceUri())
prov_raster = tempfile.gettempdir() + os.sep + 'exp_' + re.sub('[\W_]+', '', i.name()) + 'prov.tif'
out_raster = dataStore + os.sep + 'exp_' + re.sub('[\W_]+', '', i.name()) + '.jpg'
if str(i.dataProvider().metadata()[0:4]) == 'JPEG' and str(i.crs().authid()) == 'EPSG:4326':
shutil.copyfile(in_raster+".aux.xml", out_raster + ".aux.xml")
shutil.copyfile(in_raster, out_raster)
else:
processing.runalg("gdalogr:warpreproject",str(in_raster),str(i.crs().authid()),"EPSG:4326",0,1,"",prov_raster)
format = "jpeg"
driver = gdal.GetDriverByName( format )
src_ds = gdal.Open(prov_raster)
dst_ds = driver.CreateCopy( out_raster, src_ds, 0 )
dst_ds = None #free the dataset
src_ds = None #free the dataset
#ret = subprocess.check_call(['gdal_translate -of jpeg -outsize 100% 100% -a_srs EPSG:4326 ' + filename_raster + " " + out_raster_name], shell=True)
#ret2 = subprocess.check_call(['cp ' + filename_raster + ".aux.xml " + out_raster_name + ".aux.xml"], shell=True)
#now determine the canvas bounding box
#####now with viewcontrol
if extent == 'canvas extent':
pt0 = canvas.extent()
crsSrc = qgis.utils.iface.mapCanvas().mapRenderer().destinationCrs() # WGS 84
crsDest = QgsCoordinateReferenceSystem(4326) # WGS 84 / UTM zone 33N
xform = QgsCoordinateTransform(crsSrc, crsDest)
pt1 = xform.transform(pt0)
bbox_canvas = [pt1.yMinimum(), pt1.yMaximum(),pt1.xMinimum(), pt1.xMaximum()]
bounds = '[[' + str(pt1.yMinimum()) + ',' + str(pt1.xMinimum()) + '],[' + str(pt1.yMaximum()) + ',' + str(pt1.xMaximum()) +']]'
middle = """
<script>
var map = L.map('map', { zoomControl:true }).fitBounds(""" + bounds + """);
var additional_attrib = 'created w. <a href="https://github.com/geolicious/qgis2leaf" target ="_blank">qgis2leaf</a> by <a href="http://www.geolicious.de" target ="_blank">Geolicious</a> & contributors<br>';"""
if extent == 'layer extent':
middle = """
<script>
var map = L.map('map', { zoomControl:true });
var additional_attrib = 'created with <a href="https://github.com/geolicious/qgis2leaf" target ="_blank">qgis2leaf</a> by <a href="http://www.geolicious.de" target ="_blank">Geolicious</a> & contributors<br>';"""
# we will start with the clustergroup
middle += """
var feature_group = new L.featureGroup([]);
var raster_group = new L.LayerGroup([]);
"""
#here come the basemap (variants list thankfully provided by: "https://github.com/leaflet-extras/leaflet-providers") our geojsons will looped after that
#basemap name
basemapText = """
var basemap= L.tileLayer('""" + basemapAddress + """');"""
#attribution
basemapText += """
map.attributionControl.addAttribution(additional_attrib + '""" + basemapMeta + """');"""
basemapText += """
basemap.addTo(map);"""
layerOrder = """
var layerOrder=new Array();"""
with open(os.path.join(os.getcwd(),outputProjectFileName) + os.sep + 'index.html', 'a') as f4:
f4.write(middle)
f4.write(basemapText)
f4.write(layerOrder)
f4.close()
for i in reversed(allLayers):
for j in layer_list:
if re.sub('[\W_]+', '', i.name()) == j:
if i.type()==0:
with open(os.path.join(os.getcwd(),outputProjectFileName) + os.sep + 'index.html', 'a') as f5:
#here comes the layer style
#here comes the html popup content
fields = i.pendingFields()
field_names = [field.name() for field in fields]
html_prov = False
icon_prov = False
for field in field_names:
if str(field) == 'html_exp':
html_prov = True
table = 'feature.properties.html_exp'
if str(field) == 'icon_exp':
icon_prov = True #we need this later on for icon creation
if html_prov != True:
tablestart = """'<table>"""
row = ""
for field in field_names:
if str(field) == "icon_exp":
row += ""
else:
if i.editType(fields.indexFromName(field)) != QgsVectorLayer.Hidden:
row += """<tr><th scope="row">""" + i.attributeDisplayName(fields.indexFromName(str(field))) + """</th><td>' + Autolinker.link(String(feature.properties.""" + str(field) + """)) + '</td></tr>"""
tableend = """</table>'"""
table = tablestart + row +tableend
popFuncs = """ var popupContent = """ + table + """;
layer.bindPopup(popupContent);
"""
new_pop = """
function pop_""" + re.sub('[\W_]+', '', i.name()) + """(feature, layer) {
"""+popFuncs+"""
}
"""
#single marker points:
if i.rendererV2().dump()[0:6] == 'SINGLE' and i.geometryType() == 0 and icon_prov != True:
layerName=re.sub('[\W_]+', '', i.name())
if i.providerType() == 'WFS' and encode2JSON == False:
color_str = str(i.rendererV2().symbol().color().name())
radius_str = str(i.rendererV2().symbol().size() * 2)
transp_str = str(1 - ( float(i.layerTransparency()) / 100 ) )
transp_str2 = str(i.rendererV2().symbol().alpha())
stylestr="""
pointToLayer: function (feature, latlng) {
return L.circleMarker(latlng, {
radius: """+radius_str+""",
fillColor: '"""+color_str+"""',
color: '#000',
weight: 1,
opacity: """+transp_str+""",
fillOpacity: """+transp_str2+"""
})
},
onEachFeature : function (feature, layer) {
"""+popFuncs+"""
}
"""
new_obj="""
var """+layerName+"""URL='"""+i.source()+"""&outputFormat=text%2Fjavascript&format_options=callback%3Aget"""+layerName+"""Json';
"""+layerName+"""URL="""+layerName+"""URL.replace(/SRSNAME\=EPSG\:\d+/, 'SRSNAME=EPSG:4326');
var exp_"""+layerName+"""JSON = L.geoJson(null, {"""+stylestr+"""});
layerOrder[layerOrder.length] = exp_"""+layerName+"""JSON;
var """+layerName+"""ajax = $.ajax({
url : """+layerName+"""URL,
dataType : 'jsonp',
jsonpCallback : 'get"""+layerName+"""Json',
contentType : 'application/json',
success : function (response) {
L.geoJson(response, {
onEachFeature : function (feature, layer) {
"""+popFuncs+"""
exp_"""+layerName+"""JSON.addData(feature)
}
});
for (index = 0; index < layerOrder.length; index++) {
feature_group.removeLayer(layerOrder[index]);feature_group.addLayer(layerOrder[index]);
}
}
});
"""
else:
new_obj = """
var exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON = new L.geoJson(exp_""" + re.sub('[\W_]+', '', i.name()) + """,{
onEachFeature: pop_""" + re.sub('[\W_]+', '', i.name()) + """,
pointToLayer: function (feature, latlng) {
return L.circleMarker(latlng, {
radius: feature.properties.radius_qgis2leaf,
fillColor: feature.properties.color_qgis2leaf,
color: '#000',
weight: 1,
opacity: feature.properties.transp_qgis2leaf,
fillOpacity: feature.properties.transp_qgis2leaf
})
}
});
"""
#add points to the cluster group
if cluster_set == True:
new_obj += """
var cluster_group"""+ re.sub('[\W_]+', '', i.name()) + """JSON= new L.MarkerClusterGroup({showCoverageOnHover: false});
cluster_group"""+ re.sub('[\W_]+', '', i.name()) + """JSON.addLayer(exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON);
"""
cluster_num += 1
elif cluster_set == False:
new_obj += """
feature_group.addLayer(exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON);
layerOrder[layerOrder.length] = exp_"""+layerName+"""JSON;
for (index = 0; index < layerOrder.length; index++) {
feature_group.removeLayer(layerOrder[index]);feature_group.addLayer(layerOrder[index]);
}
"""
elif i.rendererV2().dump()[0:6] == 'SINGLE' and i.geometryType() == 1:
layerName=re.sub('[\W_]+', '', i.name())
if i.providerType() == 'WFS' and encode2JSON == False:
color_str = str(i.rendererV2().symbol().color().name())
radius_str = str(i.rendererV2().symbol().width() * 5)
transp_str = str(1 - ( float(i.layerTransparency()) / 100 ) )
transp_str2 = str(i.rendererV2().symbol().alpha())
stylestr="""
style: function (feature) {
return {weight: """+radius_str+""",
color: '"""+color_str+"""',
opacity: """+transp_str+""",
fillOpacity: """+transp_str2+"""};
},
onEachFeature : function (feature, layer) {
"""+popFuncs+"""
}
"""
new_obj="""
var """+layerName+"""URL='"""+i.source()+"""&outputFormat=text%2Fjavascript&format_options=callback%3Aget"""+layerName+"""Json';
"""+layerName+"""URL="""+layerName+"""URL.replace(/SRSNAME\=EPSG\:\d+/, 'SRSNAME=EPSG:4326');
var exp_"""+layerName+"""JSON = L.geoJson(null, {"""+stylestr+"""}).addTo(map);
layerOrder[layerOrder.length] = exp_"""+layerName+"""JSON;
var """+layerName+"""ajax = $.ajax({
url : """+layerName+"""URL,
dataType : 'jsonp',
jsonpCallback : 'get"""+layerName+"""Json',
contentType : 'application/json',
success : function (response) {
L.geoJson(response, {
onEachFeature : function (feature, layer) {
"""+popFuncs+"""
exp_"""+layerName+"""JSON.addData(feature)
}
});
for (index = 0; index < layerOrder.length; index++) {
map.removeLayer(layerOrder[index]);map.addLayer(layerOrder[index]);
}
}
});
"""
else:
new_obj = """
var exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON = new L.geoJson(exp_""" + re.sub('[\W_]+', '', i.name()) + """,{
onEachFeature: pop_""" + re.sub('[\W_]+', '', i.name()) + """,
style: function (feature) {
return {weight: feature.properties.radius_qgis2leaf,
color: feature.properties.color_qgis2leaf,
opacity: feature.properties.transp_qgis2leaf,
fillOpacity: feature.properties.transp_qgis2leaf};
}
});
feature_group.addLayer(exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON);
layerOrder[layerOrder.length] = exp_"""+layerName+"""JSON;
for (index = 0; index < layerOrder.length; index++) {
feature_group.removeLayer(layerOrder[index]);feature_group.addLayer(layerOrder[index]);
}
"""
elif i.rendererV2().dump()[0:6] == 'SINGLE' and i.geometryType() == 2:
layerName=re.sub('[\W_]+', '', i.name())
if i.providerType() == 'WFS' and encode2JSON == False:
if i.rendererV2().symbol().symbolLayer(0).layerType() == 'SimpleLine':
color_str = 'none'
borderColor_str = str(i.rendererV2().symbol().color().name())
radius_str = str(i.rendererV2().symbol().symbolLayer(0).width() * 5)
else:
color_str = str(i.rendererV2().symbol().color().name())
borderColor_str = str(i.rendererV2().symbol().symbolLayer(0).borderColor().name())
radius_str = str(i.rendererV2().symbol().symbolLayer(0).borderWidth() * 5)
transp_str = str(1 - ( float(i.layerTransparency()) / 100 ) )
transp_str2 = str(i.rendererV2().symbol().alpha())
stylestr="""
style: function (feature) {
return {color: '"""+borderColor_str+"""',
fillColor: '"""+color_str+"""',
weight: """+radius_str+""",
opacity: """+transp_str+""",
fillOpacity: """+transp_str+"""};
},
onEachFeature : function (feature, layer){
"""+popFuncs+"""
}
"""
new_obj="""
var """+layerName+"""URL='"""+i.source()+"""&outputFormat=text%2Fjavascript&format_options=callback%3Aget"""+layerName+"""Json';
"""+layerName+"""URL="""+layerName+"""URL.replace(/SRSNAME\=EPSG\:\d+/, 'SRSNAME=EPSG:4326');
var exp_"""+layerName+"""JSON = L.geoJson(null, {"""+stylestr+"""}).addTo(map);
layerOrder[layerOrder.length] = exp_"""+layerName+"""JSON;
var """+layerName+"""ajax = $.ajax({
url : """+layerName+"""URL,
dataType : 'jsonp',
jsonpCallback : 'get"""+layerName+"""Json',
contentType : 'application/json',
success : function (response) {
L.geoJson(response, {
onEachFeature : function (feature, layer) {
"""+popFuncs+"""
exp_"""+layerName+"""JSON.addData(feature)
}
});
for (index = 0; index < layerOrder.length; index++) {
map.removeLayer(layerOrder[index]);map.addLayer(layerOrder[index]);
}
}
});
"""
else:
new_obj = """
var exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON = new L.geoJson(exp_""" + re.sub('[\W_]+', '', i.name()) + """,{
onEachFeature: pop_""" + re.sub('[\W_]+', '', i.name()) + """,
style: function (feature) {
return {color: feature.properties.border_color_qgis2leaf,
fillColor: feature.properties.color_qgis2leaf,
weight: feature.properties.radius_qgis2leaf,
opacity: feature.properties.transp_qgis2leaf,
fillOpacity: feature.properties.transp_qgis2leaf};
}
});
feature_group.addLayer(exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON);
layerOrder[layerOrder.length] = exp_"""+layerName+"""JSON;
for (index = 0; index < layerOrder.length; index++) {
map.removeLayer(layerOrder[index]);map.addLayer(layerOrder[index]);
}
"""
elif i.rendererV2().dump()[0:11] == 'CATEGORIZED' and i.geometryType() == 0 and icon_prov != True:
new_obj = """
var exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON = new L.geoJson(exp_""" + re.sub('[\W_]+', '', i.name()) + """,{
onEachFeature: pop_""" + re.sub('[\W_]+', '', i.name()) + """,
pointToLayer: function (feature, latlng) {
return L.circleMarker(latlng, {
radius: feature.properties.radius_qgis2leaf,
fillColor: feature.properties.color_qgis2leaf,
color: '#000',
weight: 0.2,
opacity: feature.properties.transp_qgis2leaf,
fillOpacity: feature.properties.transp_qgis2leaf
})
}
});
"""
#add points to the cluster group
if cluster_set == True:
new_obj += """
var cluster_group"""+ re.sub('[\W_]+', '', i.name()) + """JSON= new L.MarkerClusterGroup({showCoverageOnHover: false});
cluster_group"""+ re.sub('[\W_]+', '', i.name()) + """JSON.addLayer(exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON);
"""
cluster_num += 1
elif cluster_set == False:
new_obj += """
feature_group.addLayer(exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON);
"""
elif i.rendererV2().dump()[0:11] == 'CATEGORIZED' and i.geometryType() == 1:
new_obj = """
var exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON = new L.geoJson(exp_""" + re.sub('[\W_]+', '', i.name()) + """,{
onEachFeature: pop_""" + re.sub('[\W_]+', '', i.name()) + """,
style: function (feature) {
return {weight: feature.properties.radius_qgis2leaf,
color: feature.properties.color_qgis2leaf,
opacity: feature.properties.transp_qgis2leaf,
fillOpacity: feature.properties.transp_qgis2leaf};
}
});
feature_group.addLayer(exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON);
"""
elif i.rendererV2().dump()[0:11] == 'CATEGORIZED' and i.geometryType() == 2:
new_obj = """
var exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON = new L.geoJson(exp_""" + re.sub('[\W_]+', '', i.name()) + """,{
onEachFeature: pop_""" + re.sub('[\W_]+', '', i.name()) + """,
style: function (feature) {
return {fillColor: feature.properties.color_qgis2leaf,
color: '#000',
weight: 1,
opacity: feature.properties.transp_qgis2leaf,
fillOpacity: feature.properties.transp_qgis2leaf};
}
});
feature_group.addLayer(exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON);
"""
elif i.rendererV2().dump()[0:9] == 'GRADUATED' and i.geometryType() == 0 and icon_prov != True:
new_obj = """
var exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON = new L.geoJson(exp_""" + re.sub('[\W_]+', '', i.name()) + """,{
onEachFeature: pop_""" + re.sub('[\W_]+', '', i.name()) + """,
pointToLayer: function (feature, latlng) {
return L.circleMarker(latlng, {
radius: feature.properties.radius_qgis2leaf,
fillColor: feature.properties.color_qgis2leaf,
color: '#000',
weight: 1,
opacity: feature.properties.transp_qgis2leaf,
fillOpacity: feature.properties.transp_qgis2leaf
})
}
});
"""
#add points to the cluster group
if cluster_set == True:
new_obj += """
var cluster_group"""+ re.sub('[\W_]+', '', i.name()) + """JSON= new L.MarkerClusterGroup({showCoverageOnHover: false});
cluster_group"""+ re.sub('[\W_]+', '', i.name()) + """JSON.addLayer(exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON);
"""
cluster_num += 1
elif cluster_set == False:
new_obj += """
feature_group.addLayer(exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON);
"""
elif i.rendererV2().dump()[0:9] == 'GRADUATED' and i.geometryType() == 1:
new_obj = """
var exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON = new L.geoJson(exp_""" + re.sub('[\W_]+', '', i.name()) + """,{
onEachFeature: pop_""" + re.sub('[\W_]+', '', i.name()) + """,
style: function (feature) {
return {weight: feature.properties.radius_qgis2leaf,
fillColor: feature.properties.color_qgis2leaf,
color: '#000',
opacity: feature.properties.transp_qgis2leaf,
fillOpacity: feature.properties.transp_qgis2leaf};
}
});
feature_group.addLayer(exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON);
"""
elif i.rendererV2().dump()[0:9] == 'GRADUATED' and i.geometryType() == 2:
new_obj = """
var exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON = new L.geoJson(exp_""" + re.sub('[\W_]+', '', i.name()) + """,{
onEachFeature: pop_""" + re.sub('[\W_]+', '', i.name()) + """,
style: function (feature) {
return {fillColor: feature.properties.color_qgis2leaf,
color: '#000',
weight: 1,
opacity: feature.properties.transp_qgis2leaf,
fillOpacity: feature.properties.transp_qgis2leaf};
}
});
feature_group.addLayer(exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON);
"""
elif icon_prov == True and i.geometryType() == 0:
new_obj = """
var exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON = new L.geoJson(exp_""" + re.sub('[\W_]+', '', i.name()) + """,{
onEachFeature: pop_""" + re.sub('[\W_]+', '', i.name()) + """,
pointToLayer: function (feature, latlng) {
return L.marker(latlng, {icon: L.icon({
iconUrl: feature.properties.icon_exp,
iconSize: [24, 24], // size of the icon change this to scale your icon (first coordinate is x, second y from the upper left corner of the icon)
iconAnchor: [12, 12], // point of the icon which will correspond to marker's location (first coordinate is x, second y from the upper left corner of the icon)
popupAnchor: [0, -14] // point from which the popup should open relative to the iconAnchor (first coordinate is x, second y from the upper left corner of the icon)
})
})
}}
);
"""
#add points to the cluster group
if cluster_set == True:
new_obj += """
var cluster_group"""+ re.sub('[\W_]+', '', i.name()) + """JSON= new L.MarkerClusterGroup({showCoverageOnHover: false});
cluster_group"""+ re.sub('[\W_]+', '', i.name()) + """JSON.addLayer(exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON);
"""
cluster_num += 1
elif cluster_set == False:
new_obj += """
feature_group.addLayer(exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON);
"""
else:
new_obj = """
var exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON = new L.geoJson(exp_""" + re.sub('[\W_]+', '', i.name()) + """,{
onEachFeature: pop_""" + re.sub('[\W_]+', '', i.name()) + """,
});
feature_group.addLayer(exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON);
"""
# store everything in the file
f5.write(new_pop)
f5.write(new_obj)
if visible == 'show all' and cluster_set == False:
f5.write("""
//add comment sign to hide this layer on the map in the initial view.
exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON.addTo(map);""")
if visible == 'show all' and cluster_set == True:
if i.geometryType() == 0:
f5.write("""
//add comment sign to hide this layer on the map in the initial view.
cluster_group"""+ re.sub('[\W_]+', '', i.name()) + """JSON.addTo(map);""")
if i.geometryType() != 0:
f5.write("""
//add comment sign to hide this layer on the map in the initial view.
exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON.addTo(map);""")
if visible == 'show none' and cluster_set == False:
f5.write("""
//delete comment sign to show this layer on the map in the initial view.
//exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON.addTo(map);""")
if visible == 'show none' and cluster_set == True:
if i.geometryType() == 0:
f5.write("""
//delete comment sign to show this layer on the map in the initial view.
//cluster_group"""+ re.sub('[\W_]+', '', i.name()) + """JSON.addTo(map);""")
if i.geometryType() != 0:
f5.write("""
//delete comment sign to show this layer on the map in the initial view.
//exp_""" + re.sub('[\W_]+', '', i.name()) + """JSON.addTo(map);""")
f5.close()
elif i.type() == 1:
out_raster_name = 'data/' + 'exp_' + re.sub('[\W_]+', '', i.name()) + '.jpg'
pt2 = i.extent()
crsSrc = i.crs() # WGS 84
crsDest = QgsCoordinateReferenceSystem(4326) # WGS 84 / UTM zone 33N
xform = QgsCoordinateTransform(crsSrc, crsDest)
pt3 = xform.transform(pt2)
bbox_canvas2 = [pt3.yMinimum(), pt3.yMaximum(),pt3.xMinimum(), pt3.xMaximum()]
bounds2 = '[[' + str(pt3.yMinimum()) + ',' + str(pt3.xMinimum()) + '],[' + str(pt3.yMaximum()) + ',' + str(pt3.xMaximum()) +']]'
with open(os.path.join(os.getcwd(),outputProjectFileName) + os.sep + 'index.html', 'a') as f5_raster:
new_obj = """
var img_""" + re.sub('[\W_]+', '', i.name()) + """= '""" + out_raster_name + """';
var img_bounds_""" + re.sub('[\W_]+', '', i.name()) + """ = """+ bounds2 + """;
var overlay_""" + re.sub('[\W_]+', '', i.name()) + """ = new L.imageOverlay(img_""" + re.sub('[\W_]+', '', i.name()) + """, img_bounds_""" + re.sub('[\W_]+', '', i.name()) + """).addTo(map);
raster_group.addLayer(overlay_""" + re.sub('[\W_]+', '', i.name()) + """);"""
f5_raster.write(new_obj)
f5_raster.close()
#let's add a Title and a subtitle
if webmap_head != "":
titleStart ="""
var title = new L.Control();
title.onAdd = function (map) {
this._div = L.DomUtil.create('div', 'info'); // create a div with a class "info"
this.update();
return this._div;
};
title.update = function () {
this._div.innerHTML = '<h2>""" + webmap_head.encode('utf-8') + """</h2>""" + webmap_subhead.encode('utf-8') + """'
};
title.addTo(map);"""
with open(os.path.join(os.getcwd(),outputProjectFileName) + os.sep + 'index.html', 'a') as f5contr:
f5contr.write(titleStart)
f5contr.close()
#here comes the address search:
if address == True:
address_text = """
var osmGeocoder = new L.Control.OSMGeocoder({
collapsed: false,
position: 'topright',
text: 'Find!',
});
osmGeocoder.addTo(map);
"""
with open(os.path.join(os.getcwd(),outputProjectFileName) + os.sep + 'index.html', 'a') as f5addr:
f5addr.write(address_text)
f5addr.close()
#let's add a legend
if legend == True:
legendStart = """
var legend = L.control({position: 'bottomright'});
legend.onAdd = function (map) {
var div = L.DomUtil.create('div', 'info legend');
div.innerHTML = "<h3>Legend</h3><table>"""
for i in reversed(allLayers):
for j in layer_list:
if re.sub('[\W_]+', '', i.name()) == j:
if i.type() == 0:
fields = i.pendingFields()
field_names = [field.name() for field in fields]
legend_ico_prov = False
legend_exp_prov = False
for field in field_names:
if str(field) == 'legend_ico':
legend_ico_prov = True
if str(field) == 'legend_exp':
legend_exp_prov = True
if legend_ico_prov == True and legend_exp_prov == True:
iter = i.getFeatures()
for feat in iter: