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(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
示例#3
0
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)
示例#4
0
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)
示例#5
0
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
示例#6
0
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