def exportJSONLayer(i, eachPopup, precision, tmpFileName, exp_crs, layerFileName, safeLayerName, minify): cleanedLayer = writeTmpLayer(i, eachPopup) writer = QgsVectorFileWriter options = "COORDINATE_PRECISION=" + unicode(precision) writer.writeAsVectorFormat(cleanedLayer, tmpFileName, 'utf-8', exp_crs, 'GeoJson', 0, layerOptions=[options]) with open(layerFileName, "w") as f2: f2.write("var json_" + unicode(safeLayerName) + "=") with open(tmpFileName, "r") as tmpFile: for line in tmpFile: if minify: line = line.strip("\n\t ") line = removeSpaces(line) f2.write(line) os.remove(tmpFileName) f2.close
def exportJSONLayer(layer, eachPopup, precision, tmpFileName, exp_crs, layerFileName, safeLayerName, minify, canvas): cleanedLayer = writeTmpLayer(layer, eachPopup) if is25d(layer, canvas): provider = cleanedLayer.dataProvider() provider.addAttributes([QgsField("height", QVariant.Double), QgsField("wallColor", QVariant.String), QgsField("roofColor", QVariant.String)]) cleanedLayer.updateFields() fields = cleanedLayer.pendingFields() renderer = layer.rendererV2() renderContext = QgsRenderContext.fromMapSettings( canvas.mapSettings()) feats = layer.getFeatures() context = QgsExpressionContext() context.appendScope(QgsExpressionContextUtils.layerScope(layer)) expression = QgsExpression('eval(@qgis_25d_height)') heightField = fields.indexFromName("height") wallField = fields.indexFromName("wallColor") roofField = fields.indexFromName("roofColor") renderer.startRender(renderContext, fields) cleanedLayer.startEditing() for feat in feats: context.setFeature(feat) height = expression.evaluate(context) if isinstance(renderer, QgsCategorizedSymbolRendererV2): classAttribute = renderer.classAttribute() attrValue = feat.attribute(classAttribute) catIndex = renderer.categoryIndexForValue(attrValue) categories = renderer.categories() symbol = categories[catIndex].symbol() elif isinstance(renderer, QgsGraduatedSymbolRendererV2): classAttribute = renderer.classAttribute() attrValue = feat.attribute(classAttribute) ranges = renderer.ranges() for range in ranges: if (attrValue >= range.lowerValue() and attrValue <= range.upperValue()): symbol = range.symbol().clone() else: symbol = renderer.symbolForFeature2(feat, renderContext) wallColor = symbol.symbolLayer(1).subSymbol().color().name() roofColor = symbol.symbolLayer(2).subSymbol().color().name() cleanedLayer.changeAttributeValue(feat.id() + 1, heightField, height) cleanedLayer.changeAttributeValue(feat.id() + 1, wallField, wallColor) cleanedLayer.changeAttributeValue(feat.id() + 1, roofField, roofColor) cleanedLayer.commitChanges() renderer.stopRender(renderContext) writer = QgsVectorFileWriter if precision != "maintain": options = "COORDINATE_PRECISION=" + unicode(precision) else: options = "" writer.writeAsVectorFormat(cleanedLayer, tmpFileName, 'utf-8', exp_crs, 'GeoJson', 0, layerOptions=[options]) with open(layerFileName, "w") as f2: f2.write("var json_" + unicode(safeLayerName) + "=") with open(tmpFileName, "r") as tmpFile: for line in tmpFile: if minify: line = line.strip("\n\t ") line = removeSpaces(line) f2.write(line) os.remove(tmpFileName) fields = layer.pendingFields() for field in fields: exportImages(layer, field.name(), layerFileName)
def writeLeaflet(iface, outputProjectFileName, width, height, full, layer_list, visible, opacity_raster, cluster, webpage_name, webmap_head, webmap_subhead, labels, labelhover, selected, json, params, popup): legends = {} canvas = iface.mapCanvas() pluginDir = os.path.dirname(os.path.realpath(__file__)) outputProjectFileName = os.path.join(outputProjectFileName, 'qgis2web_' + unicode(time.time())) outputIndex = outputProjectFileName + os.sep + 'index.html' cluster_num = 1 cleanUnusedFields = params["Data export"]["Delete unused fields"] if not cleanUnusedFields: usedFields = [ALL_ATTRIBUTES] * len(popup) else: usedFields = popup QgsApplication.initQgis() mapLibLocation = params["Data export"]["Mapping library location"] minify = params["Data export"]["Minify GeoJSON files"] extent = params["Scale/Zoom"]["Extent"] minZoom = params["Scale/Zoom"]["Min zoom level"] maxZoom = params["Scale/Zoom"]["Max zoom level"] scaleDependent = params["Scale/Zoom"]["Use layer scale dependent visibility"] basemapName = params["Appearance"]["Base layer"] matchCRS = params["Appearance"]["Match project CRS"] addressSearch = params["Appearance"]["Add address search"] locate = params["Appearance"]["Geolocate user"] measure = params["Appearance"]["Add measure tool"] highlight = params["Appearance"]["Highlight features"] dataStore, cssStore = writeFoldersAndFiles(pluginDir, outputProjectFileName, cluster, labels, measure, matchCRS, canvas, mapLibLocation, locate) writeHTMLstart(outputIndex, webpage_name, cluster, labels, addressSearch, measure, matchCRS, canvas, full, mapLibLocation) writeCSS(cssStore, full, height, width) wfsLayers = "" scaleDependentLayers = "" exp_crs = QgsCoordinateReferenceSystem(4326, QgsCoordinateReferenceSystem.EpsgCrsId) for count, i in enumerate(layer_list): rawLayerName = i.name() safeLayerName = re.sub('[\W_]+', '', rawLayerName) layerFileName = dataStore + os.sep + 'json_' + safeLayerName + '.js' if i.providerType() != 'WFS' or json[count] == True and i: precision = params["Data export"]["Precision"] if i.type() == QgsMapLayer.VectorLayer: qgis.core.QgsVectorFileWriter.writeAsVectorFormat(i, layerFileName, 'utf-8', exp_crs, 'GeoJson', selected, layerOptions=["COORDINATE_PRECISION=" + unicode(precision)]) # now change the data structure to work with leaflet: with open(layerFileName) as f: lines = f.readlines() with open(layerFileName, "w") as f2: f2.write("var json_" + unicode(safeLayerName) + "=") for line in lines: if minify: line = line.strip("\n\t ") line = removeSpaces(line) f2.write(line) f2.close # now add the js files as data input for our map with open(outputIndex, 'a') as f3: new_src = jsonScript(safeLayerName) # 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() == QgsMapLayer.RasterLayer: if i.dataProvider().name() != "wms": in_raster = unicode(i.dataProvider().dataSourceUri()) prov_raster = tempfile.gettempdir() + os.sep + 'json_' + safeLayerName + '_prov.tif' out_raster = dataStore + os.sep + 'json_' + safeLayerName + '.png' crsSrc = i.crs() crsDest = QgsCoordinateReferenceSystem(4326) xform = QgsCoordinateTransform(crsSrc, crsDest) extentRep = xform.transform(i.extent()) extentRepNew = ','.join([unicode(extentRep.xMinimum()), unicode(extentRep.xMaximum()), unicode(extentRep.yMinimum()), unicode(extentRep.yMaximum())]) processing.runalg("gdalogr:warpreproject", in_raster, i.crs().authid(), "EPSG:4326", "", 0, 1, 0, -1, 75, 6, 1, False, 0, False, "", prov_raster) processing.runalg("gdalogr:translate", prov_raster, 100, True, "", 0, "", extentRepNew, False, 0, 0, 75, 6, 1, False, 0, False, "", out_raster) if scaleDependent and i.hasScaleBasedVisibility(): scaleDependentLayers += scaleDependentLayerScript(i, safeLayerName) if scaleDependentLayers != "": scaleDependentLayers = scaleDependentScript(scaleDependentLayers) # now determine the canvas bounding box # now with viewcontrol try: crsSrc = canvas.mapSettings().destinationCrs() except: crsSrc = canvas.mapRenderer().destinationCrs() crsAuthId = crsSrc.authid() crsProj4 = crsSrc.toProj4() middle = openScript() if highlight: middle += highlightScript() if extent == "Canvas extent": pt0 = canvas.extent() 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 = '[[' + unicode(pt1.yMinimum()) + ',' + unicode(pt1.xMinimum()) + '],[' + unicode(pt1.yMaximum()) + ',' + unicode(pt1.xMaximum()) + ']]' if matchCRS and crsAuthId != 'EPSG:4326': middle += crsScript(crsAuthId, crsProj4) middle += mapScript(extent, matchCRS, crsAuthId, measure, maxZoom, minZoom, bounds) else: if matchCRS and crsAuthId != 'EPSG:4326': middle += crsScript(crsAuthId, crsProj4) middle += mapScript(extent, matchCRS, crsAuthId, measure, maxZoom, minZoom, 0) middle += featureGroupsScript() if basemapName == 0 or basemapName == "" or basemapName == "None" or matchCRS: basemapText = "" else: basemapText = basemapsScript(basemapAddresses[basemapName], basemapAttributions[basemapName], maxZoom) layerOrder = layerOrderScript() with open(outputIndex, 'a') as f4: f4.write(middle) f4.write(basemapText) f4.write(layerOrder) f4.close() for count, i in enumerate(layer_list): new_field_names = [] rawLayerName = i.name() safeLayerName = re.sub('[\W_]+', '', rawLayerName) if i.type() == QgsMapLayer.VectorLayer: with open(outputIndex, 'a') as f5: fields = i.pendingFields() field_names = [field.name() for field in fields] if usedFields[count] != 0 and usedFields[count] != 1: for field in field_names: # for popup_field in usedFields: if field == usedFields[count]: new_field_names.append(field) field_names = new_field_names html_prov = False icon_prov = False label_exp = '' labeltext = "" f = '' if labels[count]: palyr = QgsPalLayerSettings() palyr.readFromLayer(i) f = palyr.fieldName label_exp = False if not labelhover: labeltext = """.bindLabel(feature.properties.""" + unicode(f) + """, {noHide: true, offset: [-0, -16]})""" else: labeltext = """.bindLabel(feature.properties.""" + unicode(f) + """)""" for field in field_names: if unicode(field) == 'html_exp': html_prov = True table = 'feature.properties.html_exp' if unicode(field) == 'label_exp' and not labelhover: label_exp = True labeltext = """.bindLabel(feature.properties.label_exp, {noHide: true, offset: [-0, -16]})""" if unicode(field) == 'label_exp' and labelhover: label_exp = True labeltext = """.bindLabel(feature.properties.label_exp)""" if unicode(f) != "" and unicode(f) == unicode(field) and f: label_exp = True if unicode(field) == 'icon_exp': icon_prov = True if not html_prov: tablestart = """'<table>""" row = "" for field in field_names: if unicode(field) == "icon_exp": row += "" else: if i.editorWidgetV2(fields.indexFromName(field)) != QgsVectorLayer.Hidden and i.editorWidgetV2(fields.indexFromName(field)) != 'Hidden': row += """<tr><th scope="row">""" + i.attributeDisplayName(fields.indexFromName(unicode(field))) + """</th><td>' + Autolinker.link(String(feature.properties['""" + unicode(field) + """'])) + '</td></tr>""" tableend = """</table>'""" table = tablestart + row + tableend if not label_exp: labeltext = "" popFuncs = popFuncsScript(table) new_pop = popupScript(safeLayerName, popFuncs, highlight) layerName = safeLayerName renderer = i.rendererV2() try: rendererDump = renderer.dump() except: rendererDump = "" layer_transp = 1 - (float(i.layerTransparency()) / 100) new_obj = "" # single marker points: if rendererDump[0:6] == 'SINGLE' or rendererDump[0:10] == 'Rule-based': print "SINGLE" if rendererDump[0:10] == 'Rule-based': symbol = renderer.rootRule().children()[0].symbol() else: symbol = renderer.symbol() legendIcon = QgsSymbolLayerV2Utils.symbolPreviewPixmap(symbol, QSize(16, 16)) legendIcon.save(outputProjectFileName + os.sep + "legend" + os.sep + layerName + ".png") legends[layerName] = """<img src="legend/""" + layerName + """.png" /> """ + i.name() colorName = symbol.color().name() symbol_transp = symbol.alpha() fill_transp = float(symbol.color().alpha()) / 255 fill_opacity = unicode(layer_transp * symbol_transp * fill_transp) if i.geometryType() == QGis.Point and not icon_prov: print "POINT" radius = unicode(symbol.size() * 2) try: borderStyle = symbol.symbolLayer(0).outlineStyle() borderColor = unicode(symbol.symbolLayer(0).borderColor().name()) border_transp = float(symbol.symbolLayer(0).borderColor().alpha()) / 255 borderWidth = symbol.symbolLayer(0).outlineWidth() except: borderStyle = "" borderColor = "" border_transp = 0 borderWidth = 1 borderOpacity = unicode(layer_transp * symbol_transp * border_transp) pointStyleLabel = pointStyleLabelScript(safeLayerName, radius, borderWidth, borderStyle, colorName, borderColor, borderOpacity, fill_opacity, labeltext) pointToLayer = pointToLayerScript(safeLayerName) if i.providerType() == 'WFS' and json[count] == False: stylestr = pointStyleScript(pointToLayer, popFuncs) new_obj, scriptTag, cluster_num = buildPointWFS(pointStyleLabel, layerName, i.source(), "", cluster[count], cluster_num, visible[count]) wfsLayers += wfsScript(scriptTag) else: new_obj = jsonPointScript(pointStyleLabel, safeLayerName, pointToLayer, usedFields[count]) if cluster[count]: new_obj += clusterScript(safeLayerName) cluster_num += 1 elif i.geometryType() == QGis.Line: print "LINE" radius = symbol.width() try: penStyle = getLineStyle(symbol.symbolLayer(0).penStyle(), radius) except: penStyle = "" lineStyle = simpleLineStyleScript(radius, colorName, penStyle, fill_opacity) if i.providerType() == 'WFS' and json[count] == False: stylestr = nonPointStylePopupsScript(safeLayerName) new_obj, scriptTag = buildNonPointWFS(layerName, i.source(), "", stylestr, popFuncs, visible[count]) new_obj += nonPointStyleFunctionScript(safeLayerName, lineStyle) wfsLayers += wfsScript(scriptTag) else: new_obj = nonPointStyleFunctionScript(safeLayerName, lineStyle) new_obj += buildNonPointJSON("", safeLayerName, usedFields[count]) new_obj += restackLayers(layerName, visible[count]) elif i.geometryType() == QGis.Polygon: print "POLYGON" borderStyle = "" if symbol.symbolLayer(0).layerType() == 'SimpleLine' or isinstance(symbol.symbolLayer(0), QgsSimpleLineSymbolLayerV2): radius = symbol.symbolLayer(0).width() colorName = 'none' borderColor = unicode(symbol.color().name()) border_transp = float(symbol.color().alpha()) / 255 else: try: radius = symbol.symbolLayer(0).borderWidth() borderColor = unicode(symbol.symbolLayer(0).borderColor().name()) borderStyle = getLineStyle(symbol.symbolLayer(0).borderStyle(), radius) border_transp = float(symbol.symbolLayer(0).borderColor().alpha()) / 255 if symbol.symbolLayer(0).borderStyle() == 0: radius = "0" if symbol.symbolLayer(0).brushStyle() == 0: colorName = "none" except: radius = 1 borderColor = "#000000" borderStyle = "" border_transp = 1 colorName = "#ffffff" borderOpacity = unicode(layer_transp * symbol_transp * border_transp) polyStyle = singlePolyStyleScript(radius * 4, borderColor, borderOpacity, colorName, borderStyle, fill_opacity) if i.providerType() == 'WFS' and json[count] == False: stylestr = nonPointStylePopupsScript(polyStyle, safeLayerName) new_obj, scriptTag = buildNonPointWFS(layerName, i.source(), "", stylestr, popFuncs, visible[count]) wfsLayers += wfsScript(scriptTag) else: new_obj = nonPointStyleFunctionScript(safeLayerName, polyStyle) new_obj += buildNonPointJSON("", safeLayerName, usedFields[count]) new_obj += restackLayers(layerName, visible[count]) elif rendererDump[0:11] == 'CATEGORIZED': print "CATEGORIZED" catLegend = i.name() + "<br />" if i.geometryType() == QGis.Point and not icon_prov: print "POINT" categories = renderer.categories() valueAttr = renderer.classAttribute() categoryStr = categoryScript(layerName, valueAttr) for cat in categories: if not cat.value(): categoryStr += defaultCategoryScript() else: categoryStr += eachCategoryScript(cat.value()) symbol = cat.symbol() legendIcon = QgsSymbolLayerV2Utils.symbolPreviewPixmap(symbol, QSize(16, 16)) safeLabel = re.sub('[\W_]+', '', cat.label()) legendIcon.save(outputProjectFileName + os.sep + "legend" + os.sep + layerName + "_" + safeLabel + ".png") catLegend += """ <img src="legend/""" + layerName + "_" + safeLabel + """.png" /> """ + cat.label() + "<br />" symbol_transp = symbol.alpha() fill_transp = float(symbol.color().alpha()) / 255 fill_opacity = unicode(layer_transp * symbol_transp * fill_transp) border_transp = float(symbol.symbolLayer(0).borderColor().alpha()) / 255 borderOpacity = unicode(layer_transp * symbol_transp * border_transp) categoryStr += categorizedPointStylesScript(symbol, fill_opacity, borderOpacity) categoryStr += endCategoryScript() if i.providerType() == 'WFS' and json[count] == False: stylestr = categorizedPointWFSscript(layerName, labeltext, popFuncs) new_obj, scriptTag, cluster_num = buildPointWFS(layerName, i.source(), categoryStr, cluster[count], cluster_num, visible[count]) wfsLayers += wfsScript(scriptTag) else: new_obj = categoryStr + categorizedPointJSONscript(safeLayerName, labeltext, usedFields[count]) if cluster[count] == True: new_obj += clusterScript(safeLayerName) cluster_num += 1 elif i.geometryType() == QGis.Line: print "LINE" categories = renderer.categories() valueAttr = renderer.classAttribute() categoryStr = categoryScript(layerName, valueAttr) for cat in categories: if not cat.value(): categoryStr += defaultCategoryScript() else: categoryStr += eachCategoryScript(cat.value()) # categoryStr += "radius: '" + unicode(cat.symbol().size() * 2) + "'," symbol = cat.symbol() legendIcon = QgsSymbolLayerV2Utils.symbolPreviewPixmap(symbol, QSize(16, 16)) safeLabel = re.sub('[\W_]+', '', cat.label()) legendIcon.save(outputProjectFileName + os.sep + "legend" + os.sep + layerName + "_" + safeLabel + ".png") catLegend += """ <img src="legend/""" + layerName + "_" + safeLabel + """.png" /> """ + cat.label() + "<br />" symbol_transp = symbol.alpha() fill_transp = float(symbol.color().alpha()) / 255 fill_opacity = unicode(layer_transp * symbol_transp * fill_transp) categoryStr += categorizedLineStylesScript(symbol, fill_opacity) categoryStr += endCategoryScript() stylestr = categorizedNonPointStyleFunctionScript(layerName, popFuncs) if i.providerType() == 'WFS' and json[count] == False: new_obj, scriptTag = buildNonPointWFS(layerName, i.source(), categoryStr, stylestr, popFuncs, visible[count]) wfsLayers += wfsScript(scriptTag) else: new_obj = buildNonPointJSON(categoryStr, safeLayerName, usedFields[count]) elif i.geometryType() == QGis.Polygon: print "POLYGON" categories = renderer.categories() valueAttr = renderer.classAttribute() categoryStr = categoryScript(layerName, valueAttr) for cat in categories: if not cat.value(): categoryStr += defaultCategoryScript() else: categoryStr += eachCategoryScript(cat.value()) symbol = cat.symbol() legendIcon = QgsSymbolLayerV2Utils.symbolPreviewPixmap(symbol, QSize(16, 16)) safeLabel = re.sub('[\W_]+', '', cat.label()) legendIcon.save(outputProjectFileName + os.sep + "legend" + os.sep + layerName + "_" + safeLabel + ".png") catLegend += """ <img src="legend/""" + layerName + "_" + safeLabel + """.png" /> """ + cat.label() + "<br />" symbol_transp = symbol.alpha() border_transp = float(symbol.symbolLayer(0).borderColor().alpha()) / 255 borderOpacity = unicode(layer_transp * symbol_transp * border_transp) fill_transp = float(symbol.color().alpha()) / 255 fill_opacity = unicode(layer_transp * symbol_transp * fill_transp) categoryStr += categorizedPolygonStylesScript(symbol, fill_opacity, borderOpacity) categoryStr += endCategoryScript() if i.providerType() == 'WFS' and json[count] == False: stylestr = categorizedNonPointStyleFunctionScript(layerName, popFuncs) new_obj, scriptTag = buildNonPointWFS(layerName, i.source(), categoryStr, stylestr, popFuncs, visible[count]) wfsLayers += wfsScript(scriptTag) else: new_obj = buildNonPointJSON(categoryStr, safeLayerName, usedFields[count]) legends[layerName] = catLegend elif rendererDump[0:9] == 'GRADUATED': print "GRADUATED" catLegend = i.name() + "<br />" categoryStr = graduatedStyleScript(layerName) if i.geometryType() == QGis.Point and not icon_prov: print "POINT" valueAttr = renderer.classAttribute() for r in renderer.ranges(): symbol = r.symbol() legendIcon = QgsSymbolLayerV2Utils.symbolPreviewPixmap(symbol, QSize(16, 16)) safeLabel = re.sub('[\W_]+', '', r.label()) legendIcon.save(outputProjectFileName + os.sep + "legend" + os.sep + layerName + "_" + safeLabel + ".png") catLegend += """ <img src="legend/""" + layerName + "_" + safeLabel + """.png" /> """ + r.label() + "<br />" symbol_transp = symbol.alpha() border_transp = float(symbol.symbolLayer(0).borderColor().alpha()) / 255 borderOpacity = unicode(layer_transp * symbol_transp * border_transp) fill_transp = float(symbol.color().alpha()) / 255 fill_opacity = unicode(layer_transp * symbol_transp * fill_transp) categoryStr += graduatedPointStylesScript(valueAttr, r, symbol, fill_opacity, borderOpacity) categoryStr += endGraduatedStyleScript() if i.providerType() == 'WFS' and json[count] == False: stylestr = categorizedPointWFSscript(layerName, labeltext, popFuncs) new_obj, scriptTag, cluster_num = buildPointWFS(layerName, i.source(), categoryStr, cluster[count], cluster_num, visible[count]) wfsLayers += wfsScript(scriptTag) else: new_obj = categoryStr + categorizedPointJSONscript(safeLayerName, labeltext, usedFields[count]) # add points to the cluster group if cluster[count] == True: new_obj += clusterScript(safeLayerName) cluster_num += 1 elif i.geometryType() == QGis.Line: print "LINE" valueAttr = renderer.classAttribute() for r in renderer.ranges(): symbol = r.symbol() legendIcon = QgsSymbolLayerV2Utils.symbolPreviewPixmap(symbol, QSize(16, 16)) safeLabel = re.sub('[\W_]+', '', r.label()) legendIcon.save(outputProjectFileName + os.sep + "legend" + os.sep + layerName + "_" + safeLabel + ".png") catLegend += """ <img src="legend/""" + layerName + "_" + safeLabel + """.png" /> """ + r.label() + "<br />" legendIcon = QgsSymbolLayerV2Utils.symbolPreviewPixmap(symbol, QSize(16, 16)) legendIcon.save(outputProjectFileName + os.sep + "legend" + os.sep + layerName + "_" + unicode(r.label()) + ".png") symbol_transp = symbol.alpha() fill_transp = float(symbol.color().alpha()) / 255 fill_opacity = unicode(layer_transp * symbol_transp * fill_transp) categoryStr += graduatedLineStylesScript(valueAttr, r, categoryStr, symbol, fill_opacity) categoryStr += endGraduatedStyleScript() if i.providerType() == 'WFS' and json[count] == False: stylestr = categorizedNonPointStyleFunctionScript(layerName, popFuncs) new_obj, scriptTag = buildNonPointWFS(layerName, i.source(), categoryStr, stylestr, popFuncs, visible[count]) wfsLayers += wfsScript(scriptTag) else: new_obj = buildNonPointJSON(categoryStr, safeLayerName, usedFields[count]) elif i.geometryType() == QGis.Polygon: print "POLYGON" valueAttr = renderer.classAttribute() for r in renderer.ranges(): symbol = r.symbol() legendIcon = QgsSymbolLayerV2Utils.symbolPreviewPixmap(symbol, QSize(16, 16)) safeLabel = re.sub('[\W_]+', '', r.label()) legendIcon.save(outputProjectFileName + os.sep + "legend" + os.sep + layerName + "_" + safeLabel + ".png") catLegend += """ <img src="legend/""" + layerName + "_" + safeLabel + """.png" /> """ + r.label() + "<br />" legendIcon = QgsSymbolLayerV2Utils.symbolPreviewPixmap(symbol, QSize(16, 16)) legendIcon.save(outputProjectFileName + os.sep + "legend" + os.sep + layerName + "_" + unicode(r.label()) + ".png") symbol_transp = symbol.alpha() border_transp = float(symbol.symbolLayer(0).borderColor().alpha()) / 255 borderOpacity = unicode(layer_transp * symbol_transp * border_transp) fill_transp = float(symbol.color().alpha()) / 255 fill_opacity = unicode(layer_transp * symbol_transp * fill_transp) categoryStr += graduatedPolygonStylesScript(valueAttr, r, symbol, fill_opacity, borderOpacity) categoryStr += endGraduatedStyleScript() if i.providerType() == 'WFS' and json[count] == False: stylestr = categorizedNonPointStyleFunctionScript(layerName, popFuncs) new_obj, scriptTag = buildNonPointWFS(layerName, i.source(), categoryStr, stylestr, popFuncs, visible[count]) wfsLayers += wfsScript(scriptTag) else: new_obj = buildNonPointJSON(categoryStr, safeLayerName, usedFields[count]) legends[layerName] = catLegend else: print "No renderer" # elif rendererDump[0:10] == 'Rule-based': # for rule in renderer.rootRule().children(): # try: # print rule.filterExpression() + ": " + rule.filter().functionCount() # except: # print 11111 # print renderer.rootRule().filterExpression() # categoryStr = """ # function doStyle""" + layerName + "(feature) {" # for r in renderer.rootRule().children(): # symbol = r.symbol() # filterExpression = r.filterExpression() # filterExpression = re.sub('=', '==', filterExpression) # categoryStr += """ # if (""" + filterExpression + """) { # return { # radius: '""" + unicode(symbol.size() * 2) + """', # fillColor: '""" + unicode(symbol.color().name()) + """', # color: '""" + unicode(symbol.symbolLayer(0).borderColor().name())+ """', # weight: 1, # fillOpacity: '""" + unicode(symbol.alpha()) + """', # } # }""" # categoryStr += """ # }""" # if i.providerType() == 'WFS' and json[count] == False: # stylestr=""" # pointToLayer: function (feature, latlng) { # return L.circleMarker(latlng, doStyle""" + layerName + """(feature))"""+labeltext+""" # }, # onEachFeature: function (feature, layer) {"""+popFuncs+""" # }""" # new_obj, scriptTag, cluster_num = buildPointWFS(layerName, i.source(), categoryStr, cluster[count], cluster_num, visible[count]) # wfsLayers += """ # <script src='""" + scriptTag + """'></script>""" # else: # new_obj = categoryStr + """ # var json_""" + safeLayerName + """JSON = new L.geoJson(json_""" + safeLayerName + """,{ # onEachFeature: pop_""" + safeLayerName + """, # pointToLayer: function (feature, latlng) { # return L.circleMarker(latlng, doStyle""" + safeLayerName + """(feature))"""+labeltext+""" # } # });""" # #add points to the cluster group # if cluster[count] == True: # new_obj += """ # var cluster_group"""+ safeLayerName + """JSON= new L.MarkerClusterGroup({showCoverageOnHover: false}); # cluster_group"""+ safeLayerName + """JSON.addLayer(json_""" + safeLayerName + """JSON);""" # cluster_num += 1 if icon_prov and i.geometryType() == QGis.Point: new_obj = customMarkerScript(safeLayerName, labeltext, usedFields[count]) if cluster[count] == True: new_obj += clusterScript(safeLayerName) cluster_num += 1 # else: # new_obj = """ # var json_""" + safeLayerName + """JSON = new L.geoJson(json_""" + safeLayerName + """,{ # onEachFeature: pop_""" + safeLayerName + """, # });""" if usedFields[count] != 0: f5.write(new_pop) f5.write(""" """ + new_obj) f5.write(""" bounds_group.addLayer(json_""" + safeLayerName + """JSON);""") if visible[count]: if cluster[count] == False: f5.write(""" //add comment sign to hide this layer on the map in the initial view. feature_group.addLayer(json_""" + safeLayerName + """JSON);""") else: f5.write(""" //add comment sign to hide this layer on the map in the initial view. cluster_group""" + safeLayerName + """JSON.addTo(map);""") else: if cluster[count] == False: if i.geometryType() == QGis.Point: f5.write(""" //delete comment sign to show this layer on the map in the initial view. //feature_group.addLayer(json_""" + safeLayerName + """JSON);""") if i.geometryType() != 0: f5.write(""" //delete comment sign to show this layer on the map in the initial view. //feature_group.addLayer(json_""" + safeLayerName + """JSON);""") else: f5.write(""" //delete comment sign to show this layer on the map in the initial view. //cluster_group""" + safeLayerName + """JSON.addTo(map);""") f5.close() elif i.type() == QgsMapLayer.RasterLayer: if i.dataProvider().name() == "wms": d = parse_qs(i.source()) wms_url = d['url'][0] wms_layer = d['layers'][0] wms_format = d['format'][0] wms_crs = d['crs'][0] new_obj = wmsScript(safeLayerName, wms_url, wms_layer, wms_format) else: out_raster_name = 'data/' + 'json_' + safeLayerName + '.png' 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 = '[[' + unicode(pt3.yMinimum()) + ',' + unicode(pt3.xMinimum()) + '],[' + unicode(pt3.yMaximum()) + ',' + unicode(pt3.xMaximum()) + ']]' new_obj = rasterScript(safeLayerName, out_raster_name, bounds2) if visible[count]: new_obj += """ raster_group.addLayer(overlay_""" + safeLayerName + """);""" with open(outputIndex, 'a') as f5_raster: f5_raster.write(new_obj) f5_raster.close() with open(outputIndex, 'a') as f5fgroup: f5fgroup.write(""" raster_group.addTo(map); feature_group.addTo(map);""") f5fgroup.close() with open(outputIndex, 'a') as f5scaleDependent: f5scaleDependent.write(scaleDependentLayers) f5scaleDependent.close() if webmap_head != "": titleStart = titleSubScript(webmap_head, webmap_subhead) with open(outputIndex, 'a') as f5contr: f5contr.write(titleStart) f5contr.close() if addressSearch: address_text = addressSearchScript() with open(outputIndex, 'a') as f5addr: f5addr.write(address_text) f5addr.close() # let's add layer control if params["Appearance"]["Add layers list"]: if len(basemapName) == 0 or basemapName == "None" or matchCRS: controlStart = """ var baseMaps = {};""" else: controlStart = """ var baseMaps = { '""" + unicode(basemapName) + """': basemap };""" # if len(basemapName) > 1: # controlStart = """ # var baseMaps = {""" # for l in range(0,len(basemapName)): # if l < len(basemapName)-1: # controlStart+= """ # '""" + unicode(basemapName[l]) + """': basemap_""" + unicode(l) + """,""" # if l == len(basemapName)-1: # controlStart+= """ # '""" + unicode(basemapName[l]) + """': basemap_""" + unicode(l) + """};""" # if len # control_basemap = """ # var baseMaps = {""" # for l in range(0,len(basemapName)): if len(basemapName) == 0 or basemapName == "None": controlStart += """ L.control.layers({},{""" else: controlStart += """ L.control.layers(baseMaps,{""" with open(outputIndex, 'a') as f6: f6.write(controlStart) f6.close() for count, i in enumerate(reversed(layer_list)): try: testDump = i.rendererV2().dump() rawLayerName = i.name() safeLayerName = re.sub('[\W_]+', '', rawLayerName) if i.type() == QgsMapLayer.VectorLayer: with open(outputIndex, 'a') as f7: if cluster[count] == True and i.geometryType() == QGis.Point: new_layer = "'" + legends[safeLayerName] + "'" + ": cluster_group""" + safeLayerName + """JSON,""" else: new_layer = "'" + legends[safeLayerName] + "'" + ": json_" + safeLayerName + """JSON,""" f7.write(new_layer) f7.close() elif i.type() == QgsMapLayer.RasterLayer: with open(outputIndex, 'a') as f7: new_layer = '"' + rawLayerName + '"' + ": overlay_" + safeLayerName + """,""" f7.write(new_layer) f7.close() except: pass controlEnd = "},{collapsed:false}).addTo(map);" with open(outputIndex, 'rb+') as f8: f8.seek(-1, os.SEEK_END) f8.truncate() f8.write(controlEnd) f8.close() if opacity_raster: opacityStart = """ function updateOpacity(value) { """ with open(outputIndex, 'a') as f9: f9.write(opacityStart) f9.close() for i in layer_list: rawLayerName = i.name() safeLayerName = re.sub('[\W_]+', '', rawLayerName) if i.type() == QgsMapLayer.RasterLayer: with open(outputIndex, 'a') as f10: new_opc = """ overlay_""" + safeLayerName + """.setOpacity(value);""" f10.write(new_opc) f10.close() opacityEnd = """}""" with open(outputIndex, 'rb+') as f11: f11.seek(-1, os.SEEK_END) f11.truncate() f11.write(opacityEnd) f11.close() if locate: end = locateScript() else: end = '' # let's close the file but ask for the extent of all layers if the user wants to show only this extent: if extent == 'Fit to layers extent': end += """ map.fitBounds(bounds_group.getBounds());""" if params["Appearance"]["Add scale bar"]: end += """ L.control.scale({options: {position: 'bottomleft',maxWidth: 100,metric: true,imperial: false,updateWhenIdle: false}}).addTo(map);""" end += endHTMLscript(wfsLayers) with open(outputIndex, 'a') as f12: f12.write(end) f12.close() return outputIndex
def exportJSONLayer(layer, eachPopup, precision, tmpFileName, exp_crs, layerFileName, safeLayerName, minify, canvas, restrictToExtent, iface, extent): cleanedLayer = writeTmpLayer(layer, eachPopup, restrictToExtent, iface, extent) if is25d(layer, canvas, restrictToExtent, extent): provider = cleanedLayer.dataProvider() provider.addAttributes([QgsField("height", QVariant.Double), QgsField("wallColor", QVariant.String), QgsField("roofColor", QVariant.String)]) cleanedLayer.updateFields() fields = cleanedLayer.pendingFields() renderer = layer.rendererV2() renderContext = QgsRenderContext.fromMapSettings( canvas.mapSettings()) feats = layer.getFeatures() context = QgsExpressionContext() context.appendScope(QgsExpressionContextUtils.layerScope(layer)) expression = QgsExpression('eval(@qgis_25d_height)') heightField = fields.indexFromName("height") wallField = fields.indexFromName("wallColor") roofField = fields.indexFromName("roofColor") renderer.startRender(renderContext, fields) cleanedLayer.startEditing() for feat in feats: context.setFeature(feat) height = expression.evaluate(context) if isinstance(renderer, QgsCategorizedSymbolRendererV2): classAttribute = renderer.classAttribute() attrValue = feat.attribute(classAttribute) catIndex = renderer.categoryIndexForValue(attrValue) categories = renderer.categories() symbol = categories[catIndex].symbol() elif isinstance(renderer, QgsGraduatedSymbolRendererV2): classAttribute = renderer.classAttribute() attrValue = feat.attribute(classAttribute) ranges = renderer.ranges() for range in ranges: if (attrValue >= range.lowerValue() and attrValue <= range.upperValue()): symbol = range.symbol().clone() else: symbol = renderer.symbolForFeature2(feat, renderContext) wallColor = symbol.symbolLayer(1).subSymbol().color().name() roofColor = symbol.symbolLayer(2).subSymbol().color().name() cleanedLayer.changeAttributeValue(feat.id() + 1, heightField, height) cleanedLayer.changeAttributeValue(feat.id() + 1, wallField, wallColor) cleanedLayer.changeAttributeValue(feat.id() + 1, roofField, roofColor) cleanedLayer.commitChanges() renderer.stopRender(renderContext) writer = QgsVectorFileWriter if precision != "maintain": options = "COORDINATE_PRECISION=" + unicode(precision) else: options = "" writer.writeAsVectorFormat(cleanedLayer, tmpFileName, 'utf-8', exp_crs, 'GeoJson', 0, layerOptions=[options]) with open(layerFileName, "w") as f2: f2.write("var json_" + unicode(safeLayerName) + "=") with open(tmpFileName, "r") as tmpFile: for line in tmpFile: if minify: line = line.strip("\n\t ") line = removeSpaces(line) f2.write(line) os.remove(tmpFileName) fields = layer.pendingFields() for field in fields: exportImages(layer, field.name(), layerFileName)
def writeLeaflet(iface, outputProjectFileName, width, height, full, layer_list, visible, opacity_raster, cluster, webpage_name, webmap_head, webmap_subhead, labels, labelhover, selected, json, params, popup): legends = {} canvas = iface.mapCanvas() pluginDir = os.path.dirname(os.path.realpath(__file__)) outputProjectFileName = os.path.join(outputProjectFileName, 'qgis2web_' + unicode(time.time())) outputIndex = outputProjectFileName + os.sep + 'index.html' cluster_num = 1 cleanUnusedFields = params["Data export"]["Delete unused fields"] if not cleanUnusedFields: usedFields = [ALL_ATTRIBUTES] * len(popup) else: usedFields = popup QgsApplication.initQgis() mapLibLocation = params["Data export"]["Mapping library location"] minify = params["Data export"]["Minify GeoJSON files"] extent = params["Scale/Zoom"]["Extent"] minZoom = params["Scale/Zoom"]["Min zoom level"] maxZoom = params["Scale/Zoom"]["Max zoom level"] scaleDependent = params["Scale/Zoom"]["Use layer scale dependent visibility"] basemapName = params["Appearance"]["Base layer"] matchCRS = params["Appearance"]["Match project CRS"] addressSearch = params["Appearance"]["Add address search"] locate = params["Appearance"]["Geolocate user"] measure = params["Appearance"]["Add measure tool"] highlight = params["Appearance"]["Highlight features"] popupsOnHover = params["Appearance"]["Show popups on hover"] dataStore, cssStore = writeFoldersAndFiles(pluginDir, outputProjectFileName, cluster, labels, measure, matchCRS, canvas, mapLibLocation, locate) writeHTMLstart(outputIndex, webpage_name, cluster, labels, addressSearch, measure, matchCRS, canvas, full, mapLibLocation) writeCSS(cssStore, full, height, width) wfsLayers = "" scaleDependentLayers = "" exp_crs = QgsCoordinateReferenceSystem(4326, QgsCoordinateReferenceSystem.EpsgCrsId) for count, i in enumerate(layer_list): rawLayerName = i.name() safeLayerName = re.sub('[\W_]+', '', rawLayerName) layerFileName = dataStore + os.sep + 'json_' + safeLayerName + '.js' if i.providerType() != 'WFS' or json[count] == True and i: precision = params["Data export"]["Precision"] if i.type() == QgsMapLayer.VectorLayer: qgis.core.QgsVectorFileWriter.writeAsVectorFormat(i, layerFileName, 'utf-8', exp_crs, 'GeoJson', selected, layerOptions=["COORDINATE_PRECISION=" + unicode(precision)]) # now change the data structure to work with leaflet: with open(layerFileName) as f: lines = f.readlines() with open(layerFileName, "w") as f2: f2.write("var json_" + unicode(safeLayerName) + "=") for line in lines: if minify: line = line.strip("\n\t ") line = removeSpaces(line) f2.write(line) f2.close # now add the js files as data input for our map with open(outputIndex, 'a') as f3: new_src = jsonScript(safeLayerName) # 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() == QgsMapLayer.RasterLayer: if i.dataProvider().name() != "wms": in_raster = unicode(i.dataProvider().dataSourceUri()) prov_raster = tempfile.gettempdir() + os.sep + 'json_' + safeLayerName + '_prov.tif' out_raster = dataStore + os.sep + 'json_' + safeLayerName + '.png' crsSrc = i.crs() crsDest = QgsCoordinateReferenceSystem(4326) xform = QgsCoordinateTransform(crsSrc, crsDest) extentRep = xform.transform(i.extent()) extentRepNew = ','.join([unicode(extentRep.xMinimum()), unicode(extentRep.xMaximum()), unicode(extentRep.yMinimum()), unicode(extentRep.yMaximum())]) processing.runalg("gdalogr:warpreproject", in_raster, i.crs().authid(), "EPSG:4326", "", 0, 1, 0, -1, 75, 6, 1, False, 0, False, "", prov_raster) processing.runalg("gdalogr:translate", prov_raster, 100, True, "", 0, "", extentRepNew, False, 0, 0, 75, 6, 1, False, 0, False, "", out_raster) if scaleDependent and i.hasScaleBasedVisibility(): scaleDependentLayers += scaleDependentLayerScript(i, safeLayerName) if scaleDependentLayers != "": scaleDependentLayers = scaleDependentScript(scaleDependentLayers) # now determine the canvas bounding box # now with viewcontrol try: crsSrc = canvas.mapSettings().destinationCrs() except: crsSrc = canvas.mapRenderer().destinationCrs() crsAuthId = crsSrc.authid() crsProj4 = crsSrc.toProj4() middle = openScript() if highlight or popupsOnHover: middle += highlightScript(highlight, popupsOnHover, canvas.mapSettings().selectionColor().name()) if extent == "Canvas extent": pt0 = canvas.extent() 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 = '[[' + unicode(pt1.yMinimum()) + ',' + unicode(pt1.xMinimum()) + '],[' + unicode(pt1.yMaximum()) + ',' + unicode(pt1.xMaximum()) + ']]' if matchCRS and crsAuthId != 'EPSG:4326': middle += crsScript(crsAuthId, crsProj4) middle += mapScript(extent, matchCRS, crsAuthId, measure, maxZoom, minZoom, bounds) else: if matchCRS and crsAuthId != 'EPSG:4326': middle += crsScript(crsAuthId, crsProj4) middle += mapScript(extent, matchCRS, crsAuthId, measure, maxZoom, minZoom, 0) middle += featureGroupsScript() if basemapName == 0 or basemapName == "" or basemapName == "None" or matchCRS: basemapText = "" else: basemapText = basemapsScript(basemapAddresses[basemapName], basemapAttributions[basemapName], maxZoom) layerOrder = layerOrderScript() with open(outputIndex, 'a') as f4: f4.write(middle) f4.write(basemapText) f4.write(layerOrder) f4.close() for count, i in enumerate(layer_list): new_field_names = [] rawLayerName = i.name() safeLayerName = re.sub('[\W_]+', '', rawLayerName) if i.type() == QgsMapLayer.VectorLayer: with open(outputIndex, 'a') as f5: fields = i.pendingFields() field_names = [field.name() for field in fields] if usedFields[count] != 0 and usedFields[count] != 1: for field in field_names: # for popup_field in usedFields: if field == usedFields[count]: new_field_names.append(field) field_names = new_field_names html_prov = False icon_prov = False label_exp = '' labeltext = "" f = '' if labels[count]: palyr = QgsPalLayerSettings() palyr.readFromLayer(i) f = palyr.fieldName label_exp = False if not labelhover: labeltext = """.bindLabel(feature.properties.""" + unicode(f) + """, {noHide: true, offset: [-0, -16]})""" else: labeltext = """.bindLabel(feature.properties.""" + unicode(f) + """)""" for field in field_names: if unicode(field) == 'html_exp': html_prov = True table = 'feature.properties.html_exp' if unicode(field) == 'label_exp' and not labelhover: label_exp = True labeltext = """.bindLabel(feature.properties.label_exp, {noHide: true, offset: [-0, -16]})""" if unicode(field) == 'label_exp' and labelhover: label_exp = True labeltext = """.bindLabel(feature.properties.label_exp)""" if unicode(f) != "" and unicode(f) == unicode(field) and f: label_exp = True if unicode(field) == 'icon_exp': icon_prov = True if not html_prov: tablestart = """'<table>""" row = "" for field in field_names: if unicode(field) == "icon_exp": row += "" else: if i.editorWidgetV2(fields.indexFromName(field)) != QgsVectorLayer.Hidden and i.editorWidgetV2(fields.indexFromName(field)) != 'Hidden': row += """<tr><th scope="row">""" + i.attributeDisplayName(fields.indexFromName(unicode(field))) + """</th><td>' + Autolinker.link(String(feature.properties['""" + unicode(field) + """'])) + '</td></tr>""" tableend = """</table>'""" table = tablestart + row + tableend if not label_exp: labeltext = "" popFuncs = popFuncsScript(table) new_pop = popupScript(safeLayerName, popFuncs, highlight, popupsOnHover) layerName = safeLayerName renderer = i.rendererV2() try: rendererDump = renderer.dump() except: rendererDump = "" layer_transp = 1 - (float(i.layerTransparency()) / 100) new_obj = "" # single marker points: if rendererDump[0:6] == 'SINGLE' or rendererDump[0:10] == 'Rule-based': print "SINGLE" if rendererDump[0:10] == 'Rule-based': symbol = renderer.rootRule().children()[0].symbol() else: symbol = renderer.symbol() legendIcon = QgsSymbolLayerV2Utils.symbolPreviewPixmap(symbol, QSize(16, 16)) legendIcon.save(outputProjectFileName + os.sep + "legend" + os.sep + layerName + ".png") legends[layerName] = """<img src="legend/""" + layerName + """.png" /> """ + i.name() colorName = symbol.color().name() symbol_transp = symbol.alpha() fill_transp = float(symbol.color().alpha()) / 255 fill_opacity = unicode(layer_transp * symbol_transp * fill_transp) if i.geometryType() == QGis.Point and not icon_prov: print "POINT" radius = unicode(symbol.size() * 2) try: borderStyle = symbol.symbolLayer(0).outlineStyle() borderColor = unicode(symbol.symbolLayer(0).borderColor().name()) border_transp = float(symbol.symbolLayer(0).borderColor().alpha()) / 255 borderWidth = symbol.symbolLayer(0).outlineWidth() except: borderStyle = "" borderColor = "" border_transp = 0 borderWidth = 1 borderOpacity = unicode(layer_transp * symbol_transp * border_transp) pointStyleLabel = pointStyleLabelScript(safeLayerName, radius, borderWidth, borderStyle, colorName, borderColor, borderOpacity, fill_opacity, labeltext) pointToLayer = pointToLayerScript(safeLayerName) if i.providerType() == 'WFS' and json[count] == False: stylestr = pointStyleScript(pointToLayer, popFuncs) new_obj, scriptTag, cluster_num = buildPointWFS(pointStyleLabel, layerName, i.source(), "", cluster[count], cluster_num, visible[count]) wfsLayers += wfsScript(scriptTag) else: new_obj = jsonPointScript(pointStyleLabel, safeLayerName, pointToLayer, usedFields[count]) if cluster[count]: new_obj += clusterScript(safeLayerName) cluster_num += 1 elif i.geometryType() == QGis.Line: print "LINE" radius = symbol.width() try: penStyle = getLineStyle(symbol.symbolLayer(0).penStyle(), radius) except: penStyle = "" lineStyle = simpleLineStyleScript(radius, colorName, penStyle, fill_opacity) if i.providerType() == 'WFS' and json[count] == False: stylestr = nonPointStylePopupsScript(safeLayerName) new_obj, scriptTag = buildNonPointWFS(layerName, i.source(), "", stylestr, popFuncs, visible[count]) new_obj += nonPointStyleFunctionScript(safeLayerName, lineStyle) wfsLayers += wfsScript(scriptTag) else: new_obj = nonPointStyleFunctionScript(safeLayerName, lineStyle) new_obj += buildNonPointJSON("", safeLayerName, usedFields[count]) new_obj += restackLayers(layerName, visible[count]) elif i.geometryType() == QGis.Polygon: print "POLYGON" borderStyle = "" if symbol.symbolLayer(0).layerType() == 'SimpleLine' or isinstance(symbol.symbolLayer(0), QgsSimpleLineSymbolLayerV2): radius = symbol.symbolLayer(0).width() colorName = 'none' borderColor = unicode(symbol.color().name()) border_transp = float(symbol.color().alpha()) / 255 else: try: radius = symbol.symbolLayer(0).borderWidth() borderColor = unicode(symbol.symbolLayer(0).borderColor().name()) borderStyle = getLineStyle(symbol.symbolLayer(0).borderStyle(), radius) border_transp = float(symbol.symbolLayer(0).borderColor().alpha()) / 255 if symbol.symbolLayer(0).borderStyle() == 0: radius = "0" if symbol.symbolLayer(0).brushStyle() == 0: colorName = "none" except: radius = 1 borderColor = "#000000" borderStyle = "" border_transp = 1 colorName = "#ffffff" borderOpacity = unicode(layer_transp * symbol_transp * border_transp) polyStyle = singlePolyStyleScript(radius * 4, borderColor, borderOpacity, colorName, borderStyle, fill_opacity) if i.providerType() == 'WFS' and json[count] == False: stylestr = nonPointStylePopupsScript(polyStyle, safeLayerName) new_obj, scriptTag = buildNonPointWFS(layerName, i.source(), "", stylestr, popFuncs, visible[count]) wfsLayers += wfsScript(scriptTag) else: new_obj = nonPointStyleFunctionScript(safeLayerName, polyStyle) new_obj += buildNonPointJSON("", safeLayerName, usedFields[count]) new_obj += restackLayers(layerName, visible[count]) elif rendererDump[0:11] == 'CATEGORIZED': print "CATEGORIZED" catLegend = i.name() + "<br />" if i.geometryType() == QGis.Point and not icon_prov: print "POINT" categories = renderer.categories() valueAttr = renderer.classAttribute() categoryStr = categoryScript(layerName, valueAttr) for cat in categories: if not cat.value(): categoryStr += defaultCategoryScript() else: categoryStr += eachCategoryScript(cat.value()) symbol = cat.symbol() legendIcon = QgsSymbolLayerV2Utils.symbolPreviewPixmap(symbol, QSize(16, 16)) safeLabel = re.sub('[\W_]+', '', cat.label()) legendIcon.save(outputProjectFileName + os.sep + "legend" + os.sep + layerName + "_" + safeLabel + ".png") catLegend += """ <img src="legend/""" + layerName + "_" + safeLabel + """.png" /> """ + cat.label() + "<br />" symbol_transp = symbol.alpha() fill_transp = float(symbol.color().alpha()) / 255 fill_opacity = unicode(layer_transp * symbol_transp * fill_transp) border_transp = float(symbol.symbolLayer(0).borderColor().alpha()) / 255 borderOpacity = unicode(layer_transp * symbol_transp * border_transp) categoryStr += categorizedPointStylesScript(symbol, fill_opacity, borderOpacity) categoryStr += endCategoryScript() if i.providerType() == 'WFS' and json[count] == False: stylestr = categorizedPointWFSscript(layerName, labeltext, popFuncs) new_obj, scriptTag, cluster_num = buildPointWFS(layerName, i.source(), categoryStr, cluster[count], cluster_num, visible[count]) wfsLayers += wfsScript(scriptTag) else: new_obj = categoryStr + categorizedPointJSONscript(safeLayerName, labeltext, usedFields[count]) if cluster[count] == True: new_obj += clusterScript(safeLayerName) cluster_num += 1 elif i.geometryType() == QGis.Line: print "LINE" categories = renderer.categories() valueAttr = renderer.classAttribute() categoryStr = categoryScript(layerName, valueAttr) for cat in categories: if not cat.value(): categoryStr += defaultCategoryScript() else: categoryStr += eachCategoryScript(cat.value()) # categoryStr += "radius: '" + unicode(cat.symbol().size() * 2) + "'," symbol = cat.symbol() legendIcon = QgsSymbolLayerV2Utils.symbolPreviewPixmap(symbol, QSize(16, 16)) safeLabel = re.sub('[\W_]+', '', cat.label()) legendIcon.save(outputProjectFileName + os.sep + "legend" + os.sep + layerName + "_" + safeLabel + ".png") catLegend += """ <img src="legend/""" + layerName + "_" + safeLabel + """.png" /> """ + cat.label() + "<br />" symbol_transp = symbol.alpha() fill_transp = float(symbol.color().alpha()) / 255 fill_opacity = unicode(layer_transp * symbol_transp * fill_transp) categoryStr += categorizedLineStylesScript(symbol, fill_opacity) categoryStr += endCategoryScript() stylestr = categorizedNonPointStyleFunctionScript(layerName, popFuncs) if i.providerType() == 'WFS' and json[count] == False: new_obj, scriptTag = buildNonPointWFS(layerName, i.source(), categoryStr, stylestr, popFuncs, visible[count]) wfsLayers += wfsScript(scriptTag) else: new_obj = buildNonPointJSON(categoryStr, safeLayerName, usedFields[count]) elif i.geometryType() == QGis.Polygon: print "POLYGON" categories = renderer.categories() valueAttr = renderer.classAttribute() categoryStr = categoryScript(layerName, valueAttr) for cat in categories: if not cat.value(): categoryStr += defaultCategoryScript() else: categoryStr += eachCategoryScript(cat.value()) symbol = cat.symbol() legendIcon = QgsSymbolLayerV2Utils.symbolPreviewPixmap(symbol, QSize(16, 16)) safeLabel = re.sub('[\W_]+', '', cat.label()) legendIcon.save(outputProjectFileName + os.sep + "legend" + os.sep + layerName + "_" + safeLabel + ".png") catLegend += """ <img src="legend/""" + layerName + "_" + safeLabel + """.png" /> """ + cat.label() + "<br />" symbol_transp = symbol.alpha() border_transp = float(symbol.symbolLayer(0).borderColor().alpha()) / 255 borderOpacity = unicode(layer_transp * symbol_transp * border_transp) fill_transp = float(symbol.color().alpha()) / 255 fill_opacity = unicode(layer_transp * symbol_transp * fill_transp) categoryStr += categorizedPolygonStylesScript(symbol, fill_opacity, borderOpacity) categoryStr += endCategoryScript() if i.providerType() == 'WFS' and json[count] == False: stylestr = categorizedNonPointStyleFunctionScript(layerName, popFuncs) new_obj, scriptTag = buildNonPointWFS(layerName, i.source(), categoryStr, stylestr, popFuncs, visible[count]) wfsLayers += wfsScript(scriptTag) else: new_obj = buildNonPointJSON(categoryStr, safeLayerName, usedFields[count]) legends[layerName] = catLegend elif rendererDump[0:9] == 'GRADUATED': print "GRADUATED" catLegend = i.name() + "<br />" categoryStr = graduatedStyleScript(layerName) if i.geometryType() == QGis.Point and not icon_prov: print "POINT" valueAttr = renderer.classAttribute() for r in renderer.ranges(): symbol = r.symbol() legendIcon = QgsSymbolLayerV2Utils.symbolPreviewPixmap(symbol, QSize(16, 16)) safeLabel = re.sub('[\W_]+', '', r.label()) legendIcon.save(outputProjectFileName + os.sep + "legend" + os.sep + layerName + "_" + safeLabel + ".png") catLegend += """ <img src="legend/""" + layerName + "_" + safeLabel + """.png" /> """ + r.label() + "<br />" symbol_transp = symbol.alpha() border_transp = float(symbol.symbolLayer(0).borderColor().alpha()) / 255 borderOpacity = unicode(layer_transp * symbol_transp * border_transp) fill_transp = float(symbol.color().alpha()) / 255 fill_opacity = unicode(layer_transp * symbol_transp * fill_transp) categoryStr += graduatedPointStylesScript(valueAttr, r, symbol, fill_opacity, borderOpacity) categoryStr += endGraduatedStyleScript() if i.providerType() == 'WFS' and json[count] == False: stylestr = categorizedPointWFSscript(layerName, labeltext, popFuncs) new_obj, scriptTag, cluster_num = buildPointWFS(layerName, i.source(), categoryStr, cluster[count], cluster_num, visible[count]) wfsLayers += wfsScript(scriptTag) else: new_obj = categoryStr + categorizedPointJSONscript(safeLayerName, labeltext, usedFields[count]) # add points to the cluster group if cluster[count] == True: new_obj += clusterScript(safeLayerName) cluster_num += 1 elif i.geometryType() == QGis.Line: print "LINE" valueAttr = renderer.classAttribute() for r in renderer.ranges(): symbol = r.symbol() legendIcon = QgsSymbolLayerV2Utils.symbolPreviewPixmap(symbol, QSize(16, 16)) safeLabel = re.sub('[\W_]+', '', r.label()) legendIcon.save(outputProjectFileName + os.sep + "legend" + os.sep + layerName + "_" + safeLabel + ".png") catLegend += """ <img src="legend/""" + layerName + "_" + safeLabel + """.png" /> """ + r.label() + "<br />" legendIcon = QgsSymbolLayerV2Utils.symbolPreviewPixmap(symbol, QSize(16, 16)) legendIcon.save(outputProjectFileName + os.sep + "legend" + os.sep + layerName + "_" + unicode(r.label()) + ".png") symbol_transp = symbol.alpha() fill_transp = float(symbol.color().alpha()) / 255 fill_opacity = unicode(layer_transp * symbol_transp * fill_transp) categoryStr += graduatedLineStylesScript(valueAttr, r, categoryStr, symbol, fill_opacity) categoryStr += endGraduatedStyleScript() if i.providerType() == 'WFS' and json[count] == False: stylestr = categorizedNonPointStyleFunctionScript(layerName, popFuncs) new_obj, scriptTag = buildNonPointWFS(layerName, i.source(), categoryStr, stylestr, popFuncs, visible[count]) wfsLayers += wfsScript(scriptTag) else: new_obj = buildNonPointJSON(categoryStr, safeLayerName, usedFields[count]) elif i.geometryType() == QGis.Polygon: print "POLYGON" valueAttr = renderer.classAttribute() for r in renderer.ranges(): symbol = r.symbol() legendIcon = QgsSymbolLayerV2Utils.symbolPreviewPixmap(symbol, QSize(16, 16)) safeLabel = re.sub('[\W_]+', '', r.label()) legendIcon.save(outputProjectFileName + os.sep + "legend" + os.sep + layerName + "_" + safeLabel + ".png") catLegend += """ <img src="legend/""" + layerName + "_" + safeLabel + """.png" /> """ + r.label() + "<br />" legendIcon = QgsSymbolLayerV2Utils.symbolPreviewPixmap(symbol, QSize(16, 16)) legendIcon.save(outputProjectFileName + os.sep + "legend" + os.sep + layerName + "_" + unicode(r.label()) + ".png") symbol_transp = symbol.alpha() border_transp = float(symbol.symbolLayer(0).borderColor().alpha()) / 255 borderOpacity = unicode(layer_transp * symbol_transp * border_transp) fill_transp = float(symbol.color().alpha()) / 255 fill_opacity = unicode(layer_transp * symbol_transp * fill_transp) categoryStr += graduatedPolygonStylesScript(valueAttr, r, symbol, fill_opacity, borderOpacity) categoryStr += endGraduatedStyleScript() if i.providerType() == 'WFS' and json[count] == False: stylestr = categorizedNonPointStyleFunctionScript(layerName, popFuncs) new_obj, scriptTag = buildNonPointWFS(layerName, i.source(), categoryStr, stylestr, popFuncs, visible[count]) wfsLayers += wfsScript(scriptTag) else: new_obj = buildNonPointJSON(categoryStr, safeLayerName, usedFields[count]) legends[layerName] = catLegend else: print "No renderer" # elif rendererDump[0:10] == 'Rule-based': # for rule in renderer.rootRule().children(): # try: # print rule.filterExpression() + ": " + rule.filter().functionCount() # except: # print 11111 # print renderer.rootRule().filterExpression() # categoryStr = """ # function doStyle""" + layerName + "(feature) {" # for r in renderer.rootRule().children(): # symbol = r.symbol() # filterExpression = r.filterExpression() # filterExpression = re.sub('=', '==', filterExpression) # categoryStr += """ # if (""" + filterExpression + """) { # return { # radius: '""" + unicode(symbol.size() * 2) + """', # fillColor: '""" + unicode(symbol.color().name()) + """', # color: '""" + unicode(symbol.symbolLayer(0).borderColor().name())+ """', # weight: 1, # fillOpacity: '""" + unicode(symbol.alpha()) + """', # } # }""" # categoryStr += """ # }""" # if i.providerType() == 'WFS' and json[count] == False: # stylestr=""" # pointToLayer: function (feature, latlng) { # return L.circleMarker(latlng, doStyle""" + layerName + """(feature))"""+labeltext+""" # }, # onEachFeature: function (feature, layer) {"""+popFuncs+""" # }""" # new_obj, scriptTag, cluster_num = buildPointWFS(layerName, i.source(), categoryStr, cluster[count], cluster_num, visible[count]) # wfsLayers += """ # <script src='""" + scriptTag + """'></script>""" # else: # new_obj = categoryStr + """ # var json_""" + safeLayerName + """JSON = new L.geoJson(json_""" + safeLayerName + """,{ # onEachFeature: pop_""" + safeLayerName + """, # pointToLayer: function (feature, latlng) { # return L.circleMarker(latlng, doStyle""" + safeLayerName + """(feature))"""+labeltext+""" # } # });""" # #add points to the cluster group # if cluster[count] == True: # new_obj += """ # var cluster_group"""+ safeLayerName + """JSON= new L.MarkerClusterGroup({showCoverageOnHover: false}); # cluster_group"""+ safeLayerName + """JSON.addLayer(json_""" + safeLayerName + """JSON);""" # cluster_num += 1 if icon_prov and i.geometryType() == QGis.Point: new_obj = customMarkerScript(safeLayerName, labeltext, usedFields[count]) if cluster[count] == True: new_obj += clusterScript(safeLayerName) cluster_num += 1 # else: # new_obj = """ # var json_""" + safeLayerName + """JSON = new L.geoJson(json_""" + safeLayerName + """,{ # onEachFeature: pop_""" + safeLayerName + """, # });""" if usedFields[count] != 0: f5.write(new_pop) f5.write(""" """ + new_obj) f5.write(""" bounds_group.addLayer(json_""" + safeLayerName + """JSON);""") if visible[count]: if cluster[count] == False: f5.write(""" feature_group.addLayer(json_""" + safeLayerName + """JSON);""") else: f5.write(""" cluster_group""" + safeLayerName + """JSON.addTo(map);""") f5.close() elif i.type() == QgsMapLayer.RasterLayer: if i.dataProvider().name() == "wms": d = parse_qs(i.source()) wms_url = d['url'][0] wms_layer = d['layers'][0] wms_format = d['format'][0] wms_crs = d['crs'][0] new_obj = wmsScript(safeLayerName, wms_url, wms_layer, wms_format) else: out_raster_name = 'data/' + 'json_' + safeLayerName + '.png' 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 = '[[' + unicode(pt3.yMinimum()) + ',' + unicode(pt3.xMinimum()) + '],[' + unicode(pt3.yMaximum()) + ',' + unicode(pt3.xMaximum()) + ']]' new_obj = rasterScript(safeLayerName, out_raster_name, bounds2) if visible[count]: new_obj += """ raster_group.addLayer(overlay_""" + safeLayerName + """);""" with open(outputIndex, 'a') as f5_raster: f5_raster.write(new_obj) f5_raster.close() with open(outputIndex, 'a') as f5fgroup: f5fgroup.write(""" raster_group.addTo(map); feature_group.addTo(map);""") f5fgroup.close() with open(outputIndex, 'a') as f5scaleDependent: f5scaleDependent.write(scaleDependentLayers) f5scaleDependent.close() if webmap_head != "": titleStart = titleSubScript(webmap_head, webmap_subhead) with open(outputIndex, 'a') as f5contr: f5contr.write(titleStart) f5contr.close() if addressSearch: address_text = addressSearchScript() with open(outputIndex, 'a') as f5addr: f5addr.write(address_text) f5addr.close() # let's add layer control if params["Appearance"]["Add layers list"]: if len(basemapName) == 0 or basemapName == "None" or matchCRS: controlStart = """ var baseMaps = {};""" else: controlStart = """ var baseMaps = { '""" + unicode(basemapName) + """': basemap };""" # if len(basemapName) > 1: # controlStart = """ # var baseMaps = {""" # for l in range(0,len(basemapName)): # if l < len(basemapName)-1: # controlStart+= """ # '""" + unicode(basemapName[l]) + """': basemap_""" + unicode(l) + """,""" # if l == len(basemapName)-1: # controlStart+= """ # '""" + unicode(basemapName[l]) + """': basemap_""" + unicode(l) + """};""" # if len # control_basemap = """ # var baseMaps = {""" # for l in range(0,len(basemapName)): if len(basemapName) == 0 or basemapName == "None": controlStart += """ L.control.layers({},{""" else: controlStart += """ L.control.layers(baseMaps,{""" with open(outputIndex, 'a') as f6: f6.write(controlStart) f6.close() for count, i in enumerate(reversed(layer_list)): try: testDump = i.rendererV2().dump() rawLayerName = i.name() safeLayerName = re.sub('[\W_]+', '', rawLayerName) if i.type() == QgsMapLayer.VectorLayer: with open(outputIndex, 'a') as f7: if cluster[count] == True and i.geometryType() == QGis.Point: new_layer = "'" + legends[safeLayerName] + "'" + ": cluster_group""" + safeLayerName + """JSON,""" else: new_layer = "'" + legends[safeLayerName] + "'" + ": json_" + safeLayerName + """JSON,""" f7.write(new_layer) f7.close() elif i.type() == QgsMapLayer.RasterLayer: with open(outputIndex, 'a') as f7: new_layer = '"' + rawLayerName + '"' + ": overlay_" + safeLayerName + """,""" f7.write(new_layer) f7.close() except: pass controlEnd = "},{collapsed:false}).addTo(map);" with open(outputIndex, 'rb+') as f8: f8.seek(-1, os.SEEK_END) f8.truncate() f8.write(controlEnd) f8.close() if opacity_raster: opacityStart = """ function updateOpacity(value) { """ with open(outputIndex, 'a') as f9: f9.write(opacityStart) f9.close() for i in layer_list: rawLayerName = i.name() safeLayerName = re.sub('[\W_]+', '', rawLayerName) if i.type() == QgsMapLayer.RasterLayer: with open(outputIndex, 'a') as f10: new_opc = """ overlay_""" + safeLayerName + """.setOpacity(value);""" f10.write(new_opc) f10.close() opacityEnd = """}""" with open(outputIndex, 'rb+') as f11: f11.seek(-1, os.SEEK_END) f11.truncate() f11.write(opacityEnd) f11.close() if locate: end = locateScript() else: end = '' # let's close the file but ask for the extent of all layers if the user wants to show only this extent: if extent == 'Fit to layers extent': end += """ map.fitBounds(bounds_group.getBounds());""" if params["Appearance"]["Add scale bar"]: end += """ L.control.scale({options: {position: 'bottomleft',maxWidth: 100,metric: true,imperial: false,updateWhenIdle: false}}).addTo(map);""" end += endHTMLscript(wfsLayers) with open(outputIndex, 'a') as f12: f12.write(end) f12.close() return outputIndex
def writeLeaflet(iface, outputProjectFileName, layer_list, visible, cluster, json, params, popup): legends = {} canvas = iface.mapCanvas() project = QgsProject.instance() mapSettings = canvas.mapSettings() title = project.title() pluginDir = os.path.dirname(os.path.realpath(__file__)) outputProjectFileName = os.path.join(outputProjectFileName, 'qgis2web_' + unicode(time.time())) outputIndex = os.path.join(outputProjectFileName, 'index.html') cluster_num = 1 cleanUnusedFields = params["Data export"]["Delete unused fields"] mapLibLocation = params["Data export"]["Mapping library location"] minify = params["Data export"]["Minify GeoJSON files"] extent = params["Scale/Zoom"]["Extent"] minZoom = params["Scale/Zoom"]["Min zoom level"] maxZoom = params["Scale/Zoom"]["Max zoom level"] scaleDependent = ( params["Scale/Zoom"]["Use layer scale dependent visibility"]) basemapList = params["Appearance"]["Base layer"] matchCRS = params["Appearance"]["Match project CRS"] addressSearch = params["Appearance"]["Add address search"] locate = params["Appearance"]["Geolocate user"] measure = params["Appearance"]["Add measure tool"] highlight = params["Appearance"]["Highlight features"] popupsOnHover = params["Appearance"]["Show popups on hover"] template = params["Appearance"]["Template"] if not cleanUnusedFields: usedFields = [ALL_ATTRIBUTES] * len(popup) else: usedFields = popup QgsApplication.initQgis() dataStore, cssStore = writeFoldersAndFiles(pluginDir, outputProjectFileName, cluster, measure, matchCRS, canvas, mapLibLocation, locate) writeCSS(cssStore, mapSettings.backgroundColor().name()) wfsLayers = "" scaleDependentLayers = "" new_src = "" crs = QgsCoordinateReferenceSystem.EpsgCrsId exp_crs = QgsCoordinateReferenceSystem(4326, crs) for i, jsonEncode, eachPopup in zip(layer_list, json, popup): rawLayerName = i.name() safeLayerName = re.sub('[\W_]+', '', rawLayerName) dataPath = os.path.join(dataStore, 'json_' + safeLayerName) tmpFileName = dataPath + '.json' layerFileName = dataPath + '.js' if i.providerType() != 'WFS' or jsonEncode is True and i: precision = params["Data export"]["Precision"] if i.type() == QgsMapLayer.VectorLayer: cleanedLayer = writeTmpLayer(i, eachPopup) writer = qgis.core.QgsVectorFileWriter options = "COORDINATE_PRECISION=" + unicode(precision) writer.writeAsVectorFormat(cleanedLayer, tmpFileName, 'utf-8', exp_crs, 'GeoJson', 0, layerOptions=[options]) with open(layerFileName, "w") as f2: f2.write("var json_" + unicode(safeLayerName) + "=") with open(tmpFileName, "r") as tmpFile: for line in tmpFile: if minify: line = line.strip("\n\t ") line = removeSpaces(line) f2.write(line) os.remove(tmpFileName) f2.close new_src += jsonScript(safeLayerName) elif i.type() == QgsMapLayer.RasterLayer: if i.dataProvider().name() != "wms": print "Raster type: " + unicode(i.rasterType()) name_ts = safeLayerName + unicode(time.time()) pipelayer = i pipeextent = pipelayer.extent() pipewidth, pipeheight = (pipelayer.width(), pipelayer.height()) piperenderer = pipelayer.renderer() pipeprovider = pipelayer.dataProvider() crs = pipelayer.crs().toWkt() pipe = QgsRasterPipe() pipe.set(pipeprovider.clone()) pipe.set(piperenderer.clone()) pipedFile = os.path.join(tempfile.gettempdir(), name_ts + '_pipe.tif') print "pipedFile: " + pipedFile file_writer = QgsRasterFileWriter(pipedFile) file_writer.writeRaster(pipe, pipewidth, pipeheight, pipeextent, pipelayer.crs()) in_raster = pipedFile print "in_raster: " + in_raster prov_raster = os.path.join(tempfile.gettempdir(), 'json_' + name_ts + '_prov.tif') print "prov_raster: " + prov_raster out_raster = dataPath + '.png' print "out_raster: " + out_raster crsSrc = i.crs() crsDest = QgsCoordinateReferenceSystem(4326) xform = QgsCoordinateTransform(crsSrc, crsDest) extentRep = xform.transform(i.extent()) extentRepNew = ','.join([ unicode(extentRep.xMinimum()), unicode(extentRep.xMaximum()), unicode(extentRep.yMinimum()), unicode(extentRep.yMaximum()) ]) processing.runalg("gdalogr:warpreproject", in_raster, i.crs().authid(), "EPSG:4326", "", 0, 1, 5, 2, 75, 6, 1, False, 0, False, "", prov_raster) del in_raster del pipedFile os.remove( os.path.join(tempfile.gettempdir(), name_ts + '_pipe.tif')) processing.runalg("gdalogr:translate", prov_raster, 100, True, "", 0, "", extentRepNew, False, 0, 0, 75, 6, 1, False, 0, False, "", out_raster) del prov_raster os.remove( os.path.join(tempfile.gettempdir(), 'json_' + name_ts + '_prov.tif')) if scaleDependent and i.hasScaleBasedVisibility(): scaleDependentLayers += scaleDependentLayerScript(i, safeLayerName) if scaleDependentLayers != "": scaleDependentLayers = scaleDependentScript(scaleDependentLayers) try: crsSrc = mapSettings.destinationCrs() except: crsSrc = canvas.mapRenderer().destinationCrs() crsAuthId = crsSrc.authid() crsProj4 = crsSrc.toProj4() middle = openScript() if highlight or popupsOnHover: middle += highlightScript(highlight, popupsOnHover, mapSettings.selectionColor().name()) if extent == "Canvas extent": pt0 = canvas.extent() crsDest = QgsCoordinateReferenceSystem(4326) xform = QgsCoordinateTransform(crsSrc, crsDest) pt1 = xform.transform(pt0) bbox_canvas = [ pt1.yMinimum(), pt1.yMaximum(), pt1.xMinimum(), pt1.xMaximum() ] bounds = '[[' + unicode(pt1.yMinimum()) + ',' bounds += unicode(pt1.xMinimum()) + '],[' bounds += unicode(pt1.yMaximum()) + ',' bounds += unicode(pt1.xMaximum()) + ']]' if matchCRS and crsAuthId != 'EPSG:4326': middle += crsScript(crsAuthId, crsProj4) middle += mapScript(extent, matchCRS, crsAuthId, measure, maxZoom, minZoom, bounds) else: if matchCRS and crsAuthId != 'EPSG:4326': middle += crsScript(crsAuthId, crsProj4) middle += mapScript(extent, matchCRS, crsAuthId, measure, maxZoom, minZoom, 0) middle += featureGroupsScript() if (len(basemapList) == 0 or matchCRS): basemapText = "" else: basemapText = basemapsScript(basemapList, maxZoom) layerOrder = layerOrderScript(extent) new_src += middle new_src += basemapText new_src += layerOrder for count, i in enumerate(layer_list): rawLayerName = i.name() safeLayerName = re.sub('[\W_]+', '', rawLayerName) if i.type() == QgsMapLayer.VectorLayer: (new_pop, labeltext, popFuncs) = labelsAndPopups(i, safeLayerName, usedFields, highlight, popupsOnHover, popup, count) layerName = safeLayerName renderer = i.rendererV2() layer_transp = 1 - (float(i.layerTransparency()) / 100) new_obj = "" if (isinstance(renderer, QgsSingleSymbolRendererV2) or isinstance(renderer, QgsRuleBasedRendererV2)): (new_obj, legends, wfsLayers) = singleLayer(renderer, outputProjectFileName, layerName, safeLayerName, wfsLayers, i, layer_transp, labeltext, cluster, cluster_num, visible, json, usedFields, legends, count, popFuncs) elif isinstance(renderer, QgsCategorizedSymbolRendererV2): (new_obj, legends, wfsLayers) = categorizedLayer( i, renderer, layerName, safeLayerName, outputProjectFileName, layer_transp, usedFields, count, legends, labeltext, cluster, cluster_num, popFuncs, visible, json, wfsLayers) elif isinstance(renderer, QgsGraduatedSymbolRendererV2): (new_obj, legends, wfsLayers) = graduatedLayer( i, layerName, safeLayerName, renderer, outputProjectFileName, layer_transp, labeltext, popFuncs, cluster, cluster_num, visible, json, usedFields, count, legends, wfsLayers) else: print "No renderer" if usedFields[count] != 0: new_src += new_pop new_src += """ """ + new_obj new_src += """ bounds_group.addLayer(json_""" + safeLayerName + """JSON);""" if visible[count]: if cluster[count] is False: new_src += """ feature_group.addLayer(json_""" + safeLayerName + """JSON);""" else: new_src += """ cluster_group""" + safeLayerName + """JSON.addTo(map);""" elif i.type() == QgsMapLayer.RasterLayer: if i.dataProvider().name() == "wms": d = parse_qs(i.source()) wms_url = d['url'][0] wms_layer = d['layers'][0] wms_format = d['format'][0] wms_crs = d['crs'][0] new_obj = wmsScript(safeLayerName, wms_url, wms_layer, wms_format) else: out_raster_name = 'data/' + 'json_' + safeLayerName + '.png' pt2 = i.extent() crsSrc = i.crs() crsDest = QgsCoordinateReferenceSystem(4326) xform = QgsCoordinateTransform(crsSrc, crsDest) pt3 = xform.transform(pt2) bbox_canvas2 = [ pt3.yMinimum(), pt3.yMaximum(), pt3.xMinimum(), pt3.xMaximum() ] bounds2 = '[[' + unicode(pt3.yMinimum()) + ',' bounds2 += unicode(pt3.xMinimum()) + '],[' bounds2 += unicode(pt3.yMaximum()) + ',' bounds2 += unicode(pt3.xMaximum()) + ']]' new_obj = rasterScript(safeLayerName, out_raster_name, bounds2) if visible[count]: new_obj += """ raster_group.addLayer(overlay_""" + safeLayerName + """);""" new_src += new_obj new_src += """ raster_group.addTo(map); feature_group.addTo(map);""" new_src += scaleDependentLayers if title != "": titleStart = titleSubScript(title) new_src += titleStart if addressSearch: address_text = addressSearchScript() new_src += address_text if params["Appearance"]["Add layers list"]: if len(basemapList) == 0 or matchCRS: controlStart = """ var baseMaps = {};""" else: comma = "" controlStart = """ var baseMaps = {""" for count, basemap in enumerate(basemapList): controlStart += comma + "'" + unicode(basemap.text()) controlStart += "': basemap" + unicode(count) comma = ", " controlStart += "};" if len(basemapList) == 0: controlStart += """ L.control.layers({},{""" else: controlStart += """ L.control.layers(baseMaps,{""" new_src += controlStart for i, clustered in zip(reversed(layer_list), reversed(cluster)): try: testDump = i.rendererV2().dump() rawLayerName = i.name() safeLayerName = re.sub('[\W_]+', '', rawLayerName) if i.type() == QgsMapLayer.VectorLayer: if (clustered and i.geometryType() == QGis.Point): new_layer = "'" + legends[safeLayerName] + "'" + ": cluster_group" "" + safeLayerName + "JSON," else: new_layer = "'" + legends[safeLayerName] + "':" new_layer += " json_" + safeLayerName + "JSON," new_src += new_layer elif i.type() == QgsMapLayer.RasterLayer: new_layer = '"' + rawLayerName + '"' + ": overlay_" new_layer += safeLayerName + """,""" new_src += new_layer except: pass controlEnd = "},{collapsed:false}).addTo(map);" new_src += controlEnd if locate: end = locateScript() else: end = '' if params["Appearance"]["Add scale bar"]: end += """ L.control.scale({options: {position: 'bottomleft', """ end += "maxWidth: 100, metric: true, imperial: false, " end += "updateWhenIdle: false}}).addTo(map);" end += endHTMLscript(wfsLayers) new_src += end writeHTMLstart(outputIndex, title, cluster, addressSearch, measure, matchCRS, canvas, mapLibLocation, new_src, template) return outputIndex
def writeLeaflet(iface, outputProjectFileName, layer_list, visible, cluster, json, params, popup): legends = {} canvas = iface.mapCanvas() project = QgsProject.instance() mapSettings = canvas.mapSettings() title = project.title() pluginDir = os.path.dirname(os.path.realpath(__file__)) outputProjectFileName = os.path.join(outputProjectFileName, 'qgis2web_' + unicode(time.time())) outputIndex = os.path.join(outputProjectFileName, 'index.html') cluster_num = 1 cleanUnusedFields = params["Data export"]["Delete unused fields"] mapLibLocation = params["Data export"]["Mapping library location"] minify = params["Data export"]["Minify GeoJSON files"] extent = params["Scale/Zoom"]["Extent"] minZoom = params["Scale/Zoom"]["Min zoom level"] maxZoom = params["Scale/Zoom"]["Max zoom level"] scaleDependent = (params["Scale/Zoom"] ["Use layer scale dependent visibility"]) basemapList = params["Appearance"]["Base layer"] matchCRS = params["Appearance"]["Match project CRS"] addressSearch = params["Appearance"]["Add address search"] locate = params["Appearance"]["Geolocate user"] measure = params["Appearance"]["Add measure tool"] highlight = params["Appearance"]["Highlight features"] popupsOnHover = params["Appearance"]["Show popups on hover"] template = params["Appearance"]["Template"] if not cleanUnusedFields: usedFields = [ALL_ATTRIBUTES] * len(popup) else: usedFields = popup QgsApplication.initQgis() dataStore, cssStore = writeFoldersAndFiles(pluginDir, outputProjectFileName, cluster, measure, matchCRS, canvas, mapLibLocation, locate) writeCSS(cssStore, mapSettings.backgroundColor().name()) wfsLayers = "" scaleDependentLayers = "" new_src = "" crs = QgsCoordinateReferenceSystem.EpsgCrsId exp_crs = QgsCoordinateReferenceSystem(4326, crs) for i, jsonEncode, eachPopup in zip(layer_list, json, popup): rawLayerName = i.name() safeLayerName = re.sub('[\W_]+', '', rawLayerName) dataPath = os.path.join(dataStore, 'json_' + safeLayerName) tmpFileName = dataPath + '.json' layerFileName = dataPath + '.js' if i.providerType() != 'WFS' or jsonEncode is True and i: precision = params["Data export"]["Precision"] if i.type() == QgsMapLayer.VectorLayer: cleanedLayer = writeTmpLayer(i, eachPopup) writer = qgis.core.QgsVectorFileWriter options = "COORDINATE_PRECISION=" + unicode(precision) writer.writeAsVectorFormat(cleanedLayer, tmpFileName, 'utf-8', exp_crs, 'GeoJson', 0, layerOptions=[options]) with open(layerFileName, "w") as f2: f2.write("var json_" + unicode(safeLayerName) + "=") with open(tmpFileName, "r") as tmpFile: for line in tmpFile: if minify: line = line.strip("\n\t ") line = removeSpaces(line) f2.write(line) os.remove(tmpFileName) f2.close new_src += jsonScript(safeLayerName) elif i.type() == QgsMapLayer.RasterLayer: if i.dataProvider().name() != "wms": print "Raster type: " + unicode(i.rasterType()) name_ts = safeLayerName + unicode(time.time()) pipelayer = i pipeextent = pipelayer.extent() pipewidth, pipeheight = (pipelayer.width(), pipelayer.height()) piperenderer = pipelayer.renderer() pipeprovider = pipelayer.dataProvider() crs = pipelayer.crs().toWkt() pipe = QgsRasterPipe() pipe.set(pipeprovider.clone()) pipe.set(piperenderer.clone()) pipedFile = os.path.join(tempfile.gettempdir(), name_ts + '_pipe.tif') print "pipedFile: " + pipedFile file_writer = QgsRasterFileWriter(pipedFile) file_writer.writeRaster(pipe, pipewidth, pipeheight, pipeextent, pipelayer.crs()) in_raster = pipedFile print "in_raster: " + in_raster prov_raster = os.path.join(tempfile.gettempdir(), 'json_' + name_ts + '_prov.tif') print "prov_raster: " + prov_raster out_raster = dataPath + '.png' print "out_raster: " + out_raster crsSrc = i.crs() crsDest = QgsCoordinateReferenceSystem(4326) xform = QgsCoordinateTransform(crsSrc, crsDest) extentRep = xform.transform(i.extent()) extentRepNew = ','.join([unicode(extentRep.xMinimum()), unicode(extentRep.xMaximum()), unicode(extentRep.yMinimum()), unicode(extentRep.yMaximum())]) processing.runalg("gdalogr:warpreproject", in_raster, i.crs().authid(), "EPSG:4326", "", 0, 1, 5, 2, 75, 6, 1, False, 0, False, "", prov_raster) del in_raster del pipedFile os.remove(os.path.join(tempfile.gettempdir(), name_ts + '_pipe.tif')) processing.runalg("gdalogr:translate", prov_raster, 100, True, "", 0, "", extentRepNew, False, 0, 0, 75, 6, 1, False, 0, False, "", out_raster) del prov_raster os.remove(os.path.join(tempfile.gettempdir(), 'json_' + name_ts + '_prov.tif')) if scaleDependent and i.hasScaleBasedVisibility(): scaleDependentLayers += scaleDependentLayerScript(i, safeLayerName) if scaleDependentLayers != "": scaleDependentLayers = scaleDependentScript(scaleDependentLayers) try: crsSrc = mapSettings.destinationCrs() except: crsSrc = canvas.mapRenderer().destinationCrs() crsAuthId = crsSrc.authid() crsProj4 = crsSrc.toProj4() middle = openScript() if highlight or popupsOnHover: middle += highlightScript(highlight, popupsOnHover, mapSettings.selectionColor().name()) if extent == "Canvas extent": pt0 = canvas.extent() crsDest = QgsCoordinateReferenceSystem(4326) xform = QgsCoordinateTransform(crsSrc, crsDest) pt1 = xform.transform(pt0) bbox_canvas = [pt1.yMinimum(), pt1.yMaximum(), pt1.xMinimum(), pt1.xMaximum()] bounds = '[[' + unicode(pt1.yMinimum()) + ',' bounds += unicode(pt1.xMinimum()) + '],[' bounds += unicode(pt1.yMaximum()) + ',' bounds += unicode(pt1.xMaximum()) + ']]' if matchCRS and crsAuthId != 'EPSG:4326': middle += crsScript(crsAuthId, crsProj4) middle += mapScript(extent, matchCRS, crsAuthId, measure, maxZoom, minZoom, bounds) else: if matchCRS and crsAuthId != 'EPSG:4326': middle += crsScript(crsAuthId, crsProj4) middle += mapScript(extent, matchCRS, crsAuthId, measure, maxZoom, minZoom, 0) middle += featureGroupsScript() if (len(basemapList) == 0 or matchCRS): basemapText = "" else: basemapText = basemapsScript(basemapList, maxZoom) layerOrder = layerOrderScript(extent) new_src += middle new_src += basemapText new_src += layerOrder for count, i in enumerate(layer_list): rawLayerName = i.name() safeLayerName = re.sub('[\W_]+', '', rawLayerName) if i.type() == QgsMapLayer.VectorLayer: (new_pop, labeltext, popFuncs) = labelsAndPopups(i, safeLayerName, usedFields, highlight, popupsOnHover, popup, count) layerName = safeLayerName renderer = i.rendererV2() layer_transp = 1 - (float(i.layerTransparency()) / 100) new_obj = "" if (isinstance(renderer, QgsSingleSymbolRendererV2) or isinstance(renderer, QgsRuleBasedRendererV2)): (new_obj, legends, wfsLayers) = singleLayer(renderer, outputProjectFileName, layerName, safeLayerName, wfsLayers, i, layer_transp, labeltext, cluster, cluster_num, visible, json, usedFields, legends, count, popFuncs) elif isinstance(renderer, QgsCategorizedSymbolRendererV2): (new_obj, legends, wfsLayers) = categorizedLayer(i, renderer, layerName, safeLayerName, outputProjectFileName, layer_transp, usedFields, count, legends, labeltext, cluster, cluster_num, popFuncs, visible, json, wfsLayers) elif isinstance(renderer, QgsGraduatedSymbolRendererV2): (new_obj, legends, wfsLayers) = graduatedLayer(i, layerName, safeLayerName, renderer, outputProjectFileName, layer_transp, labeltext, popFuncs, cluster, cluster_num, visible, json, usedFields, count, legends, wfsLayers) else: print "No renderer" if usedFields[count] != 0: new_src += new_pop new_src += """ """ + new_obj new_src += """ bounds_group.addLayer(json_""" + safeLayerName + """JSON);""" if visible[count]: if cluster[count] is False: new_src += """ feature_group.addLayer(json_""" + safeLayerName + """JSON);""" else: new_src += """ cluster_group""" + safeLayerName + """JSON.addTo(map);""" elif i.type() == QgsMapLayer.RasterLayer: if i.dataProvider().name() == "wms": d = parse_qs(i.source()) wms_url = d['url'][0] wms_layer = d['layers'][0] wms_format = d['format'][0] wms_crs = d['crs'][0] new_obj = wmsScript(safeLayerName, wms_url, wms_layer, wms_format) else: out_raster_name = 'data/' + 'json_' + safeLayerName + '.png' pt2 = i.extent() crsSrc = i.crs() crsDest = QgsCoordinateReferenceSystem(4326) xform = QgsCoordinateTransform(crsSrc, crsDest) pt3 = xform.transform(pt2) bbox_canvas2 = [pt3.yMinimum(), pt3.yMaximum(), pt3.xMinimum(), pt3.xMaximum()] bounds2 = '[[' + unicode(pt3.yMinimum()) + ',' bounds2 += unicode(pt3.xMinimum()) + '],[' bounds2 += unicode(pt3.yMaximum()) + ',' bounds2 += unicode(pt3.xMaximum()) + ']]' new_obj = rasterScript(safeLayerName, out_raster_name, bounds2) if visible[count]: new_obj += """ raster_group.addLayer(overlay_""" + safeLayerName + """);""" new_src += new_obj new_src += """ raster_group.addTo(map); feature_group.addTo(map);""" new_src += scaleDependentLayers if title != "": titleStart = titleSubScript(title) new_src += titleStart if addressSearch: address_text = addressSearchScript() new_src += address_text if params["Appearance"]["Add layers list"]: if len(basemapList) == 0 or matchCRS: controlStart = """ var baseMaps = {};""" else: comma = "" controlStart = """ var baseMaps = {""" for count, basemap in enumerate(basemapList): controlStart += comma + "'" + unicode(basemap.text()) controlStart += "': basemap" + unicode(count) comma = ", " controlStart += "};" if len(basemapList) == 0: controlStart += """ L.control.layers({},{""" else: controlStart += """ L.control.layers(baseMaps,{""" new_src += controlStart for i, clustered in zip(reversed(layer_list), reversed(cluster)): try: testDump = i.rendererV2().dump() rawLayerName = i.name() safeLayerName = re.sub('[\W_]+', '', rawLayerName) if i.type() == QgsMapLayer.VectorLayer: if (clustered and i.geometryType() == QGis.Point): new_layer = "'" + legends[safeLayerName] + "'" + ": cluster_group""" + safeLayerName + "JSON," else: new_layer = "'" + legends[safeLayerName] + "':" new_layer += " json_" + safeLayerName + "JSON," new_src += new_layer elif i.type() == QgsMapLayer.RasterLayer: new_layer = '"' + rawLayerName + '"' + ": overlay_" new_layer += safeLayerName + """,""" new_src += new_layer except: pass controlEnd = "},{collapsed:false}).addTo(map);" new_src += controlEnd if locate: end = locateScript() else: end = '' if params["Appearance"]["Add scale bar"]: end += """ L.control.scale({options: {position: 'bottomleft', """ end += "maxWidth: 100, metric: true, imperial: false, " end += "updateWhenIdle: false}}).addTo(map);" end += endHTMLscript(wfsLayers) new_src += end writeHTMLstart(outputIndex, title, cluster, addressSearch, measure, matchCRS, canvas, mapLibLocation, new_src, template) return outputIndex