def writeOL(iface, layers, groups, popup, visible, json, cluster, labels, settings, folder): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) folder = os.path.join(folder, 'qgis2web_' + unicode(time.strftime("%Y_%m_%d-%H_%M_%S"))) # folder = os.path.join(os.getcwd(),folder) try: dst = os.path.join(folder, "resources") if not os.path.exists(dst): shutil.copytree(os.path.join(os.path.dirname(__file__), "resources"), dst) precision = settings["Data export"]["Precision"] optimize = settings["Data export"]["Minify GeoJSON files"] cleanUnusedFields = settings["Data export"]["Delete unused fields"] if not cleanUnusedFields: usedFields = [ALL_ATTRIBUTES] * len(popup) else: usedFields = popup exportLayers(layers, folder, precision, optimize, usedFields) exportStyles(layers, folder) writeLayersAndGroups(layers, groups, visible, folder, settings) if settings["Data export"]["Mapping library location"] == "Local": cssAddress = "./resources/ol.css" jsAddress = "./resources/ol.js" else: cssAddress = "http://openlayers.org/en/v3.8.2/css/ol.css" jsAddress = "http://openlayers.org/en/v3.8.2/build/ol.js" geojsonVars = "\n".join(['<script src="layers/%s"></script>' % (safeName(layer.name()) + ".js") for layer in layers if layer.type() == layer.VectorLayer]) styleVars = "\n".join(['<script src="styles/%s_style.js"></script>' % (safeName(layer.name())) for layer in layers if layer.type() == layer.VectorLayer]) popupLayers = "popupLayers = [%s];" % ",".join(['"%s"' % field if isinstance(field, basestring) else unicode(field) for field in popup]) controls = [] if settings["Appearance"]["Add scale bar"]: controls.append("new ol.control.ScaleLine({})") if settings["Appearance"]["Add layers list"]: controls.append('new ol.control.LayerSwitcher({tipLabel: "Layers"})') mapbounds = bounds(iface, settings["Scale/Zoom"]["Extent"] == "Canvas extent", layers) mapextent = "extent: %s," % mapbounds if settings["Scale/Zoom"]["Restrict to extent"] else "" maxZoom = int(settings["Scale/Zoom"]["Max zoom level"]) minZoom = int(settings["Scale/Zoom"]["Min zoom level"]) onHover = unicode(settings["Appearance"]["Show popups on hover"]).lower() highlight = unicode(settings["Appearance"]["Highlight features"]).lower() highlightFill = iface.mapCanvas().mapSettings().selectionColor().name() view = "%s maxZoom: %d, minZoom: %d" % (mapextent, maxZoom, minZoom) values = {"@CSSADDRESS@": cssAddress, "@JSADDRESS@": jsAddress, "@STYLEVARS@": styleVars, "@GEOJSONVARS@": geojsonVars, "@BOUNDS@": mapbounds, "@CONTROLS@": ",".join(controls), "@POPUPLAYERS@": popupLayers, "@VIEW@": view, "@ONHOVER@": onHover, "@DOHIGHLIGHT@": highlight, "@HIGHLIGHTFILL@": highlightFill} with open(os.path.join(folder, "index.html"), "w") as f: f.write(replaceInTemplate(settings["Appearance"]["Template"] + ".html", values)) finally: QApplication.restoreOverrideCursor() return os.path.join(folder, "index.html")
def writeOL(layers, groups, popup, visible, settings, folder): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) try: dst = os.path.join(folder, "resources") if not os.path.exists(dst): shutil.copytree(os.path.join(os.path.dirname(__file__), "resources"), dst) precision = settings["Data export"]["Precision"] optimize = settings["Data export"]["Minify GeoJSON files"] cleanUnusedFields = settings["Data export"]["Delete unused fields"] if not cleanUnusedFields: usedFields = [ALL_ATTRIBUTES] * len(popup) else: usedFields = popup exportLayers(layers, folder, precision, optimize, usedFields) exportStyles(layers, folder) writeLayersAndGroups(layers, groups, visible, folder, settings) geojsonVars ="\n".join(['<script src="layers/%s"></script>' % (safeName(layer.name()) + ".js") for layer in layers if layer.type() == layer.VectorLayer]) styleVars = "\n".join(['<script src="styles/%s_style.js"></script>' % (safeName(layer.name())) for layer in layers if layer.type() == layer.VectorLayer]) popupLayers = "popupLayers = [%s];" % ",".join(['"%s"' % field if isinstance(field, basestring) else str(field) for field in popup]) controls = [] if settings["Appearance"]["Add scale bar"]: controls.append("new ol.control.ScaleLine({})") if settings["Appearance"]["Add layers list"]: controls.append('new Boundless.LayersControl({groups: {default: {title: "Layers"}}})') mapbounds = bounds(settings["Scale/Zoom"]["Extent"] == "Canvas extent", layers) mapextent = "extent: %s," % mapbounds if settings["Scale/Zoom"]["Restrict to extent"] else "" maxZoom = int(settings["Scale/Zoom"]["Max zoom level"]) minZoom = int(settings["Scale/Zoom"]["Min zoom level"]) onHover = str(settings["Appearance"]["Show popups on hover"]).lower() highlight = str(settings["Appearance"]["Highlight features"]).lower() view = "%s maxZoom: %d, minZoom: %d" % (mapextent, maxZoom, minZoom) values = {"@STYLEVARS@": styleVars, "@GEOJSONVARS@": geojsonVars, "@BOUNDS@": mapbounds, "@CONTROLS@": ",".join(controls), "@POPUPLAYERS@": popupLayers, "@VIEW@": view, "@ONHOVER@": onHover, "@DOHIGHLIGHT@": highlight} with open(os.path.join(folder, "index.html"), "w") as f: f.write(replaceInTemplate(settings["Appearance"]["Template"] + ".html", values)) finally: QApplication.restoreOverrideCursor()
def writeOL(layers, groups, popup, visible, settings, folder): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) try: dst = os.path.join(folder, "resources") if not os.path.exists(dst): shutil.copytree(os.path.join(os.path.dirname(__file__), "resources"), dst) precision = settings["Data export"]["Precision"] optimize = settings["Data export"]["Minify GeoJSON files"] cleanUnusedFields = settings["Data export"]["Delete unused fields"] if not cleanUnusedFields: usedFields = [ALL_ATTRIBUTES] * len(popup) else: usedFields = popup exportLayers(layers, folder, precision, optimize, usedFields) exportStyles(layers, folder) writeLayersAndGroups(layers, groups, visible, folder, settings) geojsonVars ="\n".join(['<script src="layers/%s"></script>' % (safeName(layer.name()) + ".js") for layer in layers if layer.type() == layer.VectorLayer]) styleVars = "\n".join(['<script src="styles/%s_style.js"></script>' % (safeName(layer.name())) for layer in layers if layer.type() == layer.VectorLayer]) popupLayers = "popupLayers = [%s];" % ",".join(['"%s"' % field if isinstance(field, basestring) else str(field) for field in popup]) controls = [] if settings["Appearance"]["Add scale bar"]: controls.append("new ol.control.ScaleLine({})") if settings["Appearance"]["Add layers list"]: controls.append('new ol.control.LayerSwitcher({tipLabel: "Layers"})') mapbounds = bounds(settings["Scale/Zoom"]["Extent"] == "Canvas extent", layers) mapextent = "extent: %s," % mapbounds if settings["Scale/Zoom"]["Restrict to extent"] else "" maxZoom = int(settings["Scale/Zoom"]["Max zoom level"]) minZoom = int(settings["Scale/Zoom"]["Min zoom level"]) onHover = str(settings["Appearance"]["Show popups on hover"]).lower() highlight = str(settings["Appearance"]["Highlight features"]).lower() view = "%s maxZoom: %d, minZoom: %d" % (mapextent, maxZoom, minZoom) values = {"@STYLEVARS@": styleVars, "@GEOJSONVARS@": geojsonVars, "@BOUNDS@": mapbounds, "@CONTROLS@": ",".join(controls), "@POPUPLAYERS@": popupLayers, "@VIEW@": view, "@ONHOVER@": onHover, "@DOHIGHLIGHT@": highlight} with open(os.path.join(folder, "index.html"), "w") as f: f.write(replaceInTemplate(settings["Appearance"]["Template"] + ".html", values)) finally: QApplication.restoreOverrideCursor()
def writeOL(iface, layers, groups, popup, visible, json, clustered, settings, folder): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) stamp = time.strftime("%Y_%m_%d-%H_%M_%S") folder = os.path.join(folder, 'qgis2web_' + unicode(stamp)) imagesFolder = os.path.join(folder, "images") QDir().mkpath(imagesFolder) try: dst = os.path.join(folder, "resources") if not os.path.exists(dst): shutil.copytree(os.path.join(os.path.dirname(__file__), "resources"), dst) matchCRS = settings["Appearance"]["Match project CRS"] precision = settings["Data export"]["Precision"] optimize = settings["Data export"]["Minify GeoJSON files"] cleanUnusedFields = settings["Data export"]["Delete unused fields"] if not cleanUnusedFields: usedFields = [ALL_ATTRIBUTES] * len(popup) else: usedFields = popup exportLayers(iface, layers, folder, precision, optimize, popup, json) exportStyles(layers, folder, clustered) osmb = writeLayersAndGroups(layers, groups, visible, folder, popup, settings, json, matchCRS, clustered, iface) jsAddress = '<script src="resources/polyfills.js"></script>' if settings["Data export"]["Mapping library location"] == "Local": cssAddress = """<link rel="stylesheet" """ cssAddress += """href="./resources/ol.css" />""" jsAddress += """ <script src="./resources/ol.js"></script>""" else: cssAddress = """<link rel="stylesheet" href="http://""" cssAddress += """openlayers.org/en/v3.12.1/css/ol.css" />""" jsAddress += """ <script src="http://openlayers.org/en/v3.12.1/""" jsAddress += """build/ol.js"></script>""" jsAddress += """ <script src="resources/OSMBuildings-OL3.js"></script>""" geojsonVars = "" wfsVars = "" styleVars = "" for layer, encode2json in zip(layers, json): if layer.type() == layer.VectorLayer: if layer.providerType() != "WFS" or encode2json: geojsonVars += ('<script src="layers/%s"></script>' % (safeName(layer.name()) + ".js")) else: layerSource = layer.source() if not matchCRS: layerSource = re.sub('SRSNAME\=EPSG\:\d+', 'SRSNAME=EPSG:3857', layerSource) layerSource += "&outputFormat=text%2Fjavascript&" layerSource += "format_options=callback%3A" layerSource += "get" + safeName(layer.name()) + "Json" wfsVars += ('<script src="%s"></script>' % layerSource) styleVars += ('<script src="styles/%s_style.js"></script>' % (safeName(layer.name()))) popupLayers = "popupLayers = [%s];" % ",".join( ['1' for field in popup]) controls = ['expandedAttribution'] # Check qgis2web.js 14:7 if settings["Appearance"]["Add scale bar"]: controls.append("new ol.control.ScaleLine({})") if settings["Appearance"]["Add layers list"]: controls.append( 'new ol.control.LayerSwitcher({tipLabel: "Layers"})') if settings["Appearance"]["Measure tool"] != "None": controls.append( 'new measureControl()') pageTitle = QgsProject.instance().title() mapSettings = iface.mapCanvas().mapSettings() backgroundColor = """ <style> html, body {{ background-color: {bgcol}; }} </style> """.format(bgcol=mapSettings.backgroundColor().name()) mapbounds = bounds(iface, settings["Scale/Zoom"]["Extent"] == "Canvas extent", layers, settings["Appearance"]["Match project CRS"]) mapextent = "extent: %s," % mapbounds if ( settings["Scale/Zoom"]["Restrict to extent"]) else "" maxZoom = int(settings["Scale/Zoom"]["Max zoom level"]) minZoom = int(settings["Scale/Zoom"]["Min zoom level"]) popupsOnHover = settings["Appearance"]["Show popups on hover"] highlightFeatures = settings["Appearance"]["Highlight on hover"] onHover = unicode(popupsOnHover).lower() highlight = unicode(highlightFeatures).lower() highlightFill = mapSettings.selectionColor().name() proj4 = "" projdef = "" view = "%s maxZoom: %d, minZoom: %d" % (mapextent, maxZoom, minZoom) if settings["Appearance"]["Match project CRS"]: proj4 = """ <script src="http://cdnjs.cloudflare.com/ajax/libs/proj4js/2.3.6/proj4.js">""" proj4 += "</script>" projdef = "<script>proj4.defs('{epsg}','{defn}');</script>".format( epsg=mapSettings.destinationCrs().authid(), defn=mapSettings.destinationCrs().toProj4()) view += ", projection: '%s'" % ( mapSettings.destinationCrs().authid()) if settings["Appearance"]["Measure tool"] != "None": measureControl = measureControlScript() measuring = measuringScript() measure = measureScript() if settings["Appearance"]["Measure tool"] == "Imperial": measureUnit = measureUnitFeetScript() else: measureUnit = measureUnitMetricScript() measureStyle = measureStyleScript() else: measureControl = "" measuring = "" measure = "" measureUnit = "" measureStyle = "" geolocate = geolocation(settings["Appearance"]["Geolocate user"]) geocode = settings["Appearance"]["Add address search"] geocodingLinks = geocodeLinks(geocode) geocodingScript = geocodeScript(geocode) extracss = """ <link rel="stylesheet" href="./resources/ol3-layerswitcher.css"> <link rel="stylesheet" href="./resources/qgis2web.css">""" ol3layerswitcher = """ <script src="./resources/ol3-layerswitcher.js"></script>""" ol3popup = """<div id="popup" class="ol-popup"> <a href="#" id="popup-closer" class="ol-popup-closer"></a> <div id="popup-content"></div> </div>""" ol3qgis2webjs = """<script src="./resources/qgis2web.js"></script> <script src="./resources/Autolinker.min.js"></script>""" if osmb != "": ol3qgis2webjs += """ <script>{osmb}</script>""".format(osmb=osmb) ol3layers = """ <script src="./layers/layers.js" type="text/javascript"></script>""" mapSize = iface.mapCanvas().size() values = {"@PAGETITLE@": pageTitle, "@CSSADDRESS@": cssAddress, "@EXTRACSS@": extracss, "@JSADDRESS@": jsAddress, "@MAP_WIDTH@": unicode(mapSize.width()) + "px", "@MAP_HEIGHT@": unicode(mapSize.height()) + "px", "@OL3_STYLEVARS@": styleVars, "@OL3_BACKGROUNDCOLOR@": backgroundColor, "@OL3_POPUP@": ol3popup, "@OL3_GEOJSONVARS@": geojsonVars, "@OL3_WFSVARS@": wfsVars, "@OL3_PROJ4@": proj4, "@OL3_PROJDEF@": projdef, "@OL3_GEOCODINGLINKS@": geocodingLinks, "@QGIS2WEBJS@": ol3qgis2webjs, "@OL3_LAYERSWITCHER@": ol3layerswitcher, "@OL3_LAYERS@": ol3layers, "@OL3_MEASURESTYLE@": measureStyle, "@LEAFLET_ADDRESSCSS@": "", "@LEAFLET_MEASURECSS@": "", "@LEAFLET_EXTRAJS@": "", "@LEAFLET_ADDRESSJS@": "", "@LEAFLET_MEASUREJS@": "", "@LEAFLET_CRSJS@": "", "@LEAFLET_CLUSTERCSS@": "", "@LEAFLET_CLUSTERJS@": ""} with open(os.path.join(folder, "index.html"), "w") as f: htmlTemplate = settings["Appearance"]["Template"] if htmlTemplate == "": htmlTemplate = "basic" templateOutput = replaceInTemplate(htmlTemplate + ".html", values) templateOutput = re.sub('\n[\s_]+\n', '\n', templateOutput) f.write(templateOutput) values = {"@BOUNDS@": mapbounds, "@CONTROLS@": ",".join(controls), "@POPUPLAYERS@": popupLayers, "@VIEW@": view, "@ONHOVER@": onHover, "@DOHIGHLIGHT@": highlight, "@HIGHLIGHTFILL@": highlightFill, "@GEOLOCATE@": geolocate, "@GEOCODINGSCRIPT@": geocodingScript, "@MEASURECONTROL@": measureControl, "@MEASURING@": measuring, "@MEASURE@": measure, "@MEASUREUNIT@": measureUnit} with open(os.path.join(folder, "resources", "qgis2web.js"), "w") as f: f.write(replaceInScript("qgis2web.js", values)) except Exception as e: print "FAIL" print traceback.format_exc() finally: QApplication.restoreOverrideCursor() return os.path.join(folder, "index.html")
def writeOL(iface, layers, groups, popup, visible, json, clustered, settings, folder): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) stamp = time.strftime("%Y_%m_%d-%H_%M_%S") folder = os.path.join(folder, 'qgis2web_' + unicode(stamp)) imagesFolder = os.path.join(folder, "images") QDir().mkpath(imagesFolder) try: dst = os.path.join(folder, "resources") if not os.path.exists(dst): shutil.copytree( os.path.join(os.path.dirname(__file__), "resources"), dst) matchCRS = settings["Appearance"]["Match project CRS"] precision = settings["Data export"]["Precision"] optimize = settings["Data export"]["Minify GeoJSON files"] exportLayers(iface, layers, folder, precision, optimize, popup, json) exportStyles(layers, folder, clustered) osmb = writeLayersAndGroups(layers, groups, visible, folder, popup, settings, json, matchCRS, clustered, iface) jsAddress = '<script src="resources/polyfills.js"></script>' if settings["Data export"]["Mapping library location"] == "Local": cssAddress = """<link rel="stylesheet" """ cssAddress += """href="./resources/ol.css" />""" jsAddress += """ <script src="./resources/ol.js"></script>""" else: cssAddress = """<link rel="stylesheet" href="http://""" cssAddress += """openlayers.org/en/v3.18.2/css/ol.css" />""" jsAddress += """ <script src="http://openlayers.org/en/v3.18.2/""" jsAddress += """build/ol.js"></script>""" layerSearch = settings["Appearance"]["Layer search"] if layerSearch != "None" and layerSearch != "": cssAddress += """ <link rel="stylesheet" href="resources/horsey.min.css"> <link rel="stylesheet" href="resources/ol3-search-layer.min.css">""" jsAddress += """ <script src="http://cdn.polyfill.io/v2/polyfill.min.js?features=""" jsAddress += """Element.prototype.classList,URL"></script> <script src="resources/horsey.min.js"></script> <script src="resources/ol3-search-layer.min.js"></script>""" searchVals = layerSearch.split(": ") layerSearch = """ var searchLayer = new ol.SearchLayer({{ layer: lyr_{layer}, colName: '{field}', zoom: 10, collapsed: true, map: map }}); map.addControl(searchLayer);""".format(layer=searchVals[0], field=searchVals[1]) else: layerSearch = "" if osmb != "": jsAddress += """ <script src="resources/OSMBuildings-OL3.js"></script>""" geojsonVars = "" wfsVars = "" styleVars = "" for layer, encode2json in zip(layers, json): if layer.type() == layer.VectorLayer: if layer.providerType() != "WFS" or encode2json: geojsonVars += ('<script src="layers/%s"></script>' % (safeName(layer.name()) + ".js")) else: layerSource = layer.source() if "retrictToRequestBBOX" in layerSource: provider = layer.dataProvider() uri = QgsDataSourceURI(provider.dataSourceUri()) wfsURL = uri.param("url") wfsTypename = uri.param("typename") wfsSRS = uri.param("srsname") layerSource = wfsURL layerSource += "?SERVICE=WFS&VERSION=1.0.0&" layerSource += "REQUEST=GetFeature&TYPENAME=" layerSource += wfsTypename layerSource += "&SRSNAME=" layerSource += wfsSRS if not matchCRS: layerSource = re.sub('SRSNAME\=EPSG\:\d+', 'SRSNAME=EPSG:3857', layerSource) layerSource += "&outputFormat=text%2Fjavascript&" layerSource += "format_options=callback%3A" layerSource += "get" + safeName(layer.name()) + "Json" wfsVars += ('<script src="%s"></script>' % layerSource) styleVars += ('<script src="styles/%s_style.js"></script>' % (safeName(layer.name()))) popupLayers = "popupLayers = [%s];" % ",".join( ['1' for field in popup]) controls = ['expandedAttribution'] project = QgsProject.instance() if project.readBoolEntry("ScaleBar", "/Enabled", False)[0]: controls.append("new ol.control.ScaleLine({})") if settings["Appearance"]["Add layers list"]: controls.append( 'new ol.control.LayerSwitcher({tipLabel: "Layers"})') if settings["Appearance"]["Measure tool"] != "None": controls.append('new measureControl()') if settings["Appearance"]["Geolocate user"]: controls.append('new geolocateControl()') pageTitle = project.title() mapSettings = iface.mapCanvas().mapSettings() backgroundColor = """ <style> html, body {{ background-color: {bgcol}; }} </style> """.format(bgcol=mapSettings.backgroundColor().name()) geolocateUser = settings["Appearance"]["Geolocate user"] backgroundColor += geolocateStyle(geolocateUser) mapbounds = bounds(iface, settings["Scale/Zoom"]["Extent"] == "Canvas extent", layers, settings["Appearance"]["Match project CRS"]) mapextent = "extent: %s," % mapbounds if ( settings["Scale/Zoom"]["Restrict to extent"]) else "" maxZoom = int(settings["Scale/Zoom"]["Max zoom level"]) minZoom = int(settings["Scale/Zoom"]["Min zoom level"]) popupsOnHover = settings["Appearance"]["Show popups on hover"] highlightFeatures = settings["Appearance"]["Highlight on hover"] onHover = unicode(popupsOnHover).lower() highlight = unicode(highlightFeatures).lower() highlightFill = mapSettings.selectionColor().name() proj4 = "" proj = "" view = "%s maxZoom: %d, minZoom: %d" % (mapextent, maxZoom, minZoom) if settings["Appearance"]["Match project CRS"]: proj4 = """ <script src="http://cdnjs.cloudflare.com/ajax/libs/proj4js/2.3.6/proj4.js">""" proj4 += "</script>" proj = "<script>proj4.defs('{epsg}','{defn}');</script>".format( epsg=mapSettings.destinationCrs().authid(), defn=mapSettings.destinationCrs().toProj4()) view += ", projection: '%s'" % ( mapSettings.destinationCrs().authid()) if settings["Appearance"]["Measure tool"] != "None": measureControl = measureControlScript() measuring = measuringScript() measure = measureScript() if settings["Appearance"]["Measure tool"] == "Imperial": measureUnit = measureUnitFeetScript() else: measureUnit = measureUnitMetricScript() measureStyle = measureStyleScript() else: measureControl = "" measuring = "" measure = "" measureUnit = "" measureStyle = "" geolocateHead = geolocationHead(geolocateUser) geolocate = geolocation(geolocateUser) geocode = settings["Appearance"]["Add address search"] geocodingLinks = geocodeLinks(geocode) geocodingScript = geocodeScript(geocode) extracss = """ <link rel="stylesheet" href="./resources/ol3-layerswitcher.css"> <link rel="stylesheet" href="./resources/qgis2web.css">""" if settings["Appearance"]["Geolocate user"]: extracss += """ <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/""" extracss += """font-awesome/4.6.3/css/font-awesome.min.css">""" ol3layerswitcher = """ <script src="./resources/ol3-layerswitcher.js"></script>""" ol3popup = """<div id="popup" class="ol-popup"> <a href="#" id="popup-closer" class="ol-popup-closer"></a> <div id="popup-content"></div> </div>""" ol3qgis2webjs = """<script src="./resources/qgis2web.js"></script> <script src="./resources/Autolinker.min.js"></script>""" if osmb != "": ol3qgis2webjs += """ <script>{osmb}</script>""".format(osmb=osmb) ol3layers = """ <script src="./layers/layers.js" type="text/javascript"></script>""" mapSize = iface.mapCanvas().size() values = { "@PAGETITLE@": pageTitle, "@CSSADDRESS@": cssAddress, "@EXTRACSS@": extracss, "@JSADDRESS@": jsAddress, "@MAP_WIDTH@": unicode(mapSize.width()) + "px", "@MAP_HEIGHT@": unicode(mapSize.height()) + "px", "@OL3_STYLEVARS@": styleVars, "@OL3_BACKGROUNDCOLOR@": backgroundColor, "@OL3_POPUP@": ol3popup, "@OL3_GEOJSONVARS@": geojsonVars, "@OL3_WFSVARS@": wfsVars, "@OL3_PROJ4@": proj4, "@OL3_PROJDEF@": proj, "@OL3_GEOCODINGLINKS@": geocodingLinks, "@QGIS2WEBJS@": ol3qgis2webjs, "@OL3_LAYERSWITCHER@": ol3layerswitcher, "@OL3_LAYERS@": ol3layers, "@OL3_MEASURESTYLE@": measureStyle, "@LEAFLET_ADDRESSCSS@": "", "@LEAFLET_MEASURECSS@": "", "@LEAFLET_EXTRAJS@": "", "@LEAFLET_ADDRESSJS@": "", "@LEAFLET_MEASUREJS@": "", "@LEAFLET_CRSJS@": "", "@LEAFLET_LAYERSEARCHCSS@": "", "@LEAFLET_LAYERSEARCHJS@": "", "@LEAFLET_CLUSTERCSS@": "", "@LEAFLET_CLUSTERJS@": "" } with open(os.path.join(folder, "index.html"), "w") as f: htmlTemplate = settings["Appearance"]["Template"] if htmlTemplate == "": htmlTemplate = "basic" templateOutput = replaceInTemplate(htmlTemplate + ".html", values) templateOutput = re.sub('\n[\s_]+\n', '\n', templateOutput) f.write(templateOutput) values = { "@GEOLOCATEHEAD@": geolocateHead, "@BOUNDS@": mapbounds, "@CONTROLS@": ",".join(controls), "@POPUPLAYERS@": popupLayers, "@VIEW@": view, "@LAYERSEARCH@": layerSearch, "@ONHOVER@": onHover, "@DOHIGHLIGHT@": highlight, "@HIGHLIGHTFILL@": highlightFill, "@GEOLOCATE@": geolocate, "@GEOCODINGSCRIPT@": geocodingScript, "@MEASURECONTROL@": measureControl, "@MEASURING@": measuring, "@MEASURE@": measure, "@MEASUREUNIT@": measureUnit } with open(os.path.join(folder, "resources", "qgis2web.js"), "w") as f: f.write(replaceInScript("qgis2web.js", values)) except Exception as e: print "FAIL" print traceback.format_exc() finally: QApplication.restoreOverrideCursor() return os.path.join(folder, "index.html")
def writeOL(iface, layers, groups, popup, visible, json, clustered, settings, folder): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) stamp = time.strftime("%Y_%m_%d-%H_%M_%S") folder = os.path.join(folder, 'qgis2web_' + unicode(stamp)) try: dst = os.path.join(folder, "resources") if not os.path.exists(dst): shutil.copytree( os.path.join(os.path.dirname(__file__), "resources"), dst) matchCRS = settings["Appearance"]["Match project CRS"] precision = settings["Data export"]["Precision"] optimize = settings["Data export"]["Minify GeoJSON files"] cleanUnusedFields = settings["Data export"]["Delete unused fields"] if not cleanUnusedFields: usedFields = [ALL_ATTRIBUTES] * len(popup) else: usedFields = popup exportLayers(iface, layers, folder, precision, optimize, usedFields, json) exportStyles(layers, folder, clustered) writeLayersAndGroups(layers, groups, visible, folder, settings, json, matchCRS, clustered) jsAddress = '<script src="resources/bind_polyfill.js"></script>' if settings["Data export"]["Mapping library location"] == "Local": cssAddress = """<link rel="stylesheet" """ cssAddress += """href="./resources/ol.css" />""" jsAddress += """<script src="./resources/ol.js"></script>""" else: cssAddress = """<link rel="stylesheet" href="http://""" cssAddress += """openlayers.org/en/v3.12.1/css/ol.css" />""" jsAddress += """<script src="http://openlayers.org/en/v3.12.1/""" jsAddress += """build/ol.js"></script>""" geojsonVars = "" wfsVars = "" styleVars = "" for layer, encode2json in zip(layers, json): if layer.type() == layer.VectorLayer: if layer.providerType() != "WFS" or encode2json: geojsonVars += ('<script src="layers/%s"></script>' % (safeName(layer.name()) + ".js")) else: layerSource = layer.source() if not matchCRS: layerSource = re.sub('SRSNAME\=EPSG\:\d+', 'SRSNAME=EPSG:3857', layerSource) layerSource += "&outputFormat=text%2Fjavascript&" layerSource += "format_options=callback%3A" layerSource += "get" + safeName(layer.name()) + "Json" wfsVars += ('<script src="%s"></script>' % layerSource) styleVars += ('<script src="styles/%s_style.js"></script>' % (safeName(layer.name()))) popupLayers = "popupLayers = [%s];" % ",".join([ '"%s"' % field if (isinstance(field, basestring)) else unicode(field) for field in popup ]) controls = ['expandedAttribution'] # Check qgis2web.js 14:7 if settings["Appearance"]["Add scale bar"]: controls.append("new ol.control.ScaleLine({})") if settings["Appearance"]["Add layers list"]: controls.append( 'new ol.control.LayerSwitcher({tipLabel: "Layers"})') if settings["Appearance"]["Add measure tool"]: controls.append('new measureControl()') pageTitle = QgsProject.instance().title() mapSettings = iface.mapCanvas().mapSettings() backgroundColor = """ <style> html, body {{ background-color: {bgcol}; }} </style> """.format(bgcol=mapSettings.backgroundColor().name()) mapbounds = bounds(iface, settings["Scale/Zoom"]["Extent"] == "Canvas extent", layers, settings["Appearance"]["Match project CRS"]) mapextent = "extent: %s," % mapbounds if ( settings["Scale/Zoom"]["Restrict to extent"]) else "" maxZoom = int(settings["Scale/Zoom"]["Max zoom level"]) minZoom = int(settings["Scale/Zoom"]["Min zoom level"]) popupsOnHover = settings["Appearance"]["Show popups on hover"] highlightFeatures = settings["Appearance"]["Highlight features"] onHover = unicode(popupsOnHover).lower() highlight = unicode(highlightFeatures).lower() highlightFill = mapSettings.selectionColor().name() proj4 = "" projdef = "" view = "%s maxZoom: %d, minZoom: %d" % (mapextent, maxZoom, minZoom) if settings["Appearance"]["Match project CRS"]: proj4 = """ <script src="http://cdnjs.cloudflare.com/ajax/libs/proj4js/2.3.6/proj4.js">""" proj4 += "</script>" projdef = "<script>proj4.defs('{epsg}','{defn}');</script>".format( epsg=mapSettings.destinationCrs().authid(), defn=mapSettings.destinationCrs().toProj4()) view += ", projection: '%s'" % ( mapSettings.destinationCrs().authid()) if settings["Appearance"]["Add measure tool"]: measureControl = measureControlScript() measuring = measuringScript() measure = measureScript() measureStyle = measureStyleScript() else: measureControl = "" measuring = "" measure = "" measureStyle = "" geolocate = geolocation(settings["Appearance"]["Geolocate user"]) geocode = settings["Appearance"]["Add address search"] geocodingLinks = geocodeLinks(geocode) geocodingScript = geocodeScript(geocode) extracss = """ <link rel="stylesheet" href="./resources/ol3-layerswitcher.css"> <link rel="stylesheet" href="./resources/qgis2web.css">""" ol3layerswitcher = """ <script src="./resources/ol3-layerswitcher.js"></script>""" ol3popup = """<div id="popup" class="ol-popup"> <a href="#" id="popup-closer" class="ol-popup-closer"></a> <div id="popup-content"></div> </div>""" ol3qgis2webjs = """<script src="./resources/qgis2web.js"></script> <script src="./resources/Autolinker.min.js"></script>""" ol3layers = """ <script src="./layers/layers.js" type="text/javascript"></script>""" mapSize = iface.mapCanvas().size() values = { "@PAGETITLE@": pageTitle, "@CSSADDRESS@": cssAddress, "@EXTRACSS@": extracss, "@JSADDRESS@": jsAddress, "@MAP_WIDTH@": unicode(mapSize.width()) + "px", "@MAP_HEIGHT@": unicode(mapSize.height()) + "px", "@OL3_STYLEVARS@": styleVars, "@OL3_BACKGROUNDCOLOR@": backgroundColor, "@OL3_POPUP@": ol3popup, "@OL3_GEOJSONVARS@": geojsonVars, "@OL3_WFSVARS@": wfsVars, "@OL3_PROJ4@": proj4, "@OL3_PROJDEF@": projdef, "@OL3_GEOCODINGLINKS@": geocodingLinks, "@QGIS2WEBJS@": ol3qgis2webjs, "@OL3_LAYERSWITCHER@": ol3layerswitcher, "@OL3_LAYERS@": ol3layers, "@OL3_MEASURESTYLE@": measureStyle, "@LEAFLET_ADDRESSCSS@": "", "@LEAFLET_MEASURECSS@": "", "@LEAFLET_EXTRAJS@": "", "@LEAFLET_ADDRESSJS@": "", "@LEAFLET_MEASUREJS@": "", "@LEAFLET_CRSJS@": "", "@LEAFLET_CLUSTERCSS@": "", "@LEAFLET_CLUSTERJS@": "" } with open(os.path.join(folder, "index.html"), "w") as f: htmlTemplate = settings["Appearance"]["Template"] if htmlTemplate == "": htmlTemplate = "basic" templateOutput = replaceInTemplate(htmlTemplate + ".html", values) templateOutput = re.sub('\n[\s_]+\n', '\n', templateOutput) f.write(templateOutput) values = { "@BOUNDS@": mapbounds, "@CONTROLS@": ",".join(controls), "@POPUPLAYERS@": popupLayers, "@VIEW@": view, "@ONHOVER@": onHover, "@DOHIGHLIGHT@": highlight, "@HIGHLIGHTFILL@": highlightFill, "@GEOLOCATE@": geolocate, "@GEOCODINGSCRIPT@": geocodingScript, "@MEASURECONTROL@": measureControl, "@MEASURING@": measuring, "@MEASURE@": measure } with open(os.path.join(folder, "resources", "qgis2web.js"), "w") as f: f.write(replaceInScript("qgis2web.js", values)) except Exception as e: print "FAIL" print traceback.format_exc() finally: QApplication.restoreOverrideCursor() return os.path.join(folder, "index.html")
def writeOL(cls, iface, feedback, layers, groups, popup, visible, json, clustered, settings, folder): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) controlCount = 0 stamp = datetime.now().strftime("%Y_%m_%d-%H_%M_%S_%f") folder = os.path.join(folder, 'qgis2web_' + unicode(stamp)) restrictToExtent = settings["Scale/Zoom"]["Restrict to extent"] matchCRS = settings["Appearance"]["Match project CRS"] precision = settings["Data export"]["Precision"] optimize = settings["Data export"]["Minify GeoJSON files"] extent = settings["Scale/Zoom"]["Extent"] geolocateUser = settings["Appearance"]["Geolocate user"] maxZoom = int(settings["Scale/Zoom"]["Max zoom level"]) minZoom = int(settings["Scale/Zoom"]["Min zoom level"]) popupsOnHover = settings["Appearance"]["Show popups on hover"] highlightFeatures = settings["Appearance"]["Highlight on hover"] geocode = settings["Appearance"]["Add address search"] measureTool = settings["Appearance"]["Measure tool"] addLayersList = settings["Appearance"]["Add layers list"] htmlTemplate = settings["Appearance"]["Template"] layerSearch = unicode(settings["Appearance"]["Layer search"]) searchLayer = settings["Appearance"]["Search layer"] mapLibLocn = settings["Data export"]["Mapping library location"] writeFiles(folder, restrictToExtent, feedback) exportLayers(iface, layers, folder, precision, optimize, popup, json, restrictToExtent, extent, feedback) exportStyles(layers, folder, clustered) osmb = writeLayersAndGroups(layers, groups, visible, folder, popup, settings, json, matchCRS, clustered, iface, restrictToExtent, extent) (jsAddress, cssAddress, layerSearch, controlCount) = writeHTMLstart(settings, controlCount, osmb, mapLibLocn, layerSearch, searchLayer, feedback) (geojsonVars, wfsVars, styleVars) = writeScriptIncludes(layers, json, matchCRS) popupLayers = "popupLayers = [%s];" % ",".join( ['1' for field in popup]) controls = ['expandedAttribution'] project = QgsProject.instance() if project.readBoolEntry("ScaleBar", "/Enabled", False)[0]: controls.append("new ol.control.ScaleLine({})") if measureTool != "None": controls.append('new measureControl()') if geolocateUser: controls.append('new geolocateControl()') if (addLayersList and addLayersList != "" and addLayersList != "None"): layersList = """ var layerSwitcher = new ol.control.LayerSwitcher({tipLabel: "Layers"}); map.addControl(layerSwitcher);""" if addLayersList == "Expanded": layersList += """ layerSwitcher.hidePanel = function() {}; layerSwitcher.showPanel(); """ else: layersList = "" pageTitle = project.title() mapSettings = iface.mapCanvas().mapSettings() backgroundColor = """ <style> html, body {{ background-color: {bgcol}; }} </style> """.format(bgcol=mapSettings.backgroundColor().name()) (geolocateCode, controlCount) = geolocateStyle(geolocateUser, controlCount) backgroundColor += geolocateCode mapbounds = bounds(iface, extent == "Canvas extent", layers, matchCRS) mapextent = "extent: %s," % mapbounds if restrictToExtent else "" onHover = unicode(popupsOnHover).lower() highlight = unicode(highlightFeatures).lower() highlightFill = mapSettings.selectionColor().name() proj4 = "" proj = "" view = "%s maxZoom: %d, minZoom: %d" % (mapextent, maxZoom, minZoom) if matchCRS: proj4 = """ <script src="http://cdnjs.cloudflare.com/ajax/libs/proj4js/2.3.6/proj4.js">""" proj4 += "</script>" proj = "<script>proj4.defs('{epsg}','{defn}');</script>"\ .format( epsg=mapSettings.destinationCrs().authid(), defn=mapSettings.destinationCrs().toProj4()) view += ", projection: '%s'" % ( mapSettings.destinationCrs().authid()) if measureTool != "None": measureControl = measureControlScript() measuring = measuringScript() measure = measureScript() if measureTool == "Imperial": measureUnit = measureUnitFeetScript() else: measureUnit = measureUnitMetricScript() measureStyle = measureStyleScript(controlCount) controlCount = controlCount + 1 else: measureControl = "" measuring = "" measure = "" measureUnit = "" measureStyle = "" geolocateHead = geolocationHead(geolocateUser) geolocate = geolocation(geolocateUser) geocodingLinks = geocodeLinks(geocode) geocodingJS = geocodeJS(geocode) geocodingScript = geocodeScript(geocode) extracss = """ <link rel="stylesheet" href="./resources/ol3-layerswitcher.css"> <link rel="stylesheet" href="./resources/qgis2web.css">""" if geocode: geocodePos = 65 + (controlCount * 35) extracss += """ <style> .ol-geocoder.gcd-gl-container { top: %dpx!important; } .ol-geocoder .gcd-gl-btn { width: 21px!important; height: 21px!important; } </style>""" % geocodePos if geolocateUser: extracss += """ <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/""" extracss += """font-awesome/4.6.3/css/font-awesome.min.css">""" ol3layerswitcher = """ <script src="./resources/ol3-layerswitcher.js"></script>""" ol3popup = """<div id="popup" class="ol-popup"> <a href="#" id="popup-closer" class="ol-popup-closer"></a> <div id="popup-content"></div> </div>""" ol3qgis2webjs = """<script src="./resources/qgis2web.js"></script> <script src="./resources/Autolinker.min.js"></script>""" if osmb != "": ol3qgis2webjs += """ <script>{osmb}</script>""".format(osmb=osmb) ol3layers = """ <script src="./layers/layers.js" type="text/javascript"></script>""" mapSize = iface.mapCanvas().size() exp_js = """ <script src="resources/qgis2web_expressions.js"></script>""" values = { "@PAGETITLE@": pageTitle, "@CSSADDRESS@": cssAddress, "@EXTRACSS@": extracss, "@JSADDRESS@": jsAddress, "@MAP_WIDTH@": unicode(mapSize.width()) + "px", "@MAP_HEIGHT@": unicode(mapSize.height()) + "px", "@OL3_STYLEVARS@": styleVars, "@OL3_BACKGROUNDCOLOR@": backgroundColor, "@OL3_POPUP@": ol3popup, "@OL3_GEOJSONVARS@": geojsonVars, "@OL3_WFSVARS@": wfsVars, "@OL3_PROJ4@": proj4, "@OL3_PROJDEF@": proj, "@OL3_GEOCODINGLINKS@": geocodingLinks, "@OL3_GEOCODINGJS@": geocodingJS, "@QGIS2WEBJS@": ol3qgis2webjs, "@OL3_LAYERSWITCHER@": ol3layerswitcher, "@OL3_LAYERS@": ol3layers, "@OL3_MEASURESTYLE@": measureStyle, "@EXP_JS@": exp_js, "@LEAFLET_ADDRESSCSS@": "", "@LEAFLET_MEASURECSS@": "", "@LEAFLET_EXTRAJS@": "", "@LEAFLET_ADDRESSJS@": "", "@LEAFLET_MEASUREJS@": "", "@LEAFLET_CRSJS@": "", "@LEAFLET_LAYERSEARCHCSS@": "", "@LEAFLET_LAYERSEARCHJS@": "", "@LEAFLET_CLUSTERCSS@": "", "@LEAFLET_CLUSTERJS@": "" } with open(os.path.join(folder, "index.html"), "w") as f: htmlTemplate = htmlTemplate if htmlTemplate == "": htmlTemplate = "basic" templateOutput = replaceInTemplate(htmlTemplate + ".html", values) templateOutput = re.sub('\n[\s_]+\n', '\n', templateOutput) f.write(templateOutput) values = { "@GEOLOCATEHEAD@": geolocateHead, "@BOUNDS@": mapbounds, "@CONTROLS@": ",".join(controls), "@LAYERSLIST@": layersList, "@POPUPLAYERS@": popupLayers, "@VIEW@": view, "@LAYERSEARCH@": layerSearch, "@ONHOVER@": onHover, "@DOHIGHLIGHT@": highlight, "@HIGHLIGHTFILL@": highlightFill, "@GEOLOCATE@": geolocate, "@GEOCODINGSCRIPT@": geocodingScript, "@MEASURECONTROL@": measureControl, "@MEASURING@": measuring, "@MEASURE@": measure, "@MEASUREUNIT@": measureUnit } with open(os.path.join(folder, "resources", "qgis2web.js"), "w") as f: out = replaceInScript("qgis2web.js", values) f.write(out.encode("utf-8")) QApplication.restoreOverrideCursor() return os.path.join(folder, "index.html")
def writeOL(cls, iface, feedback, layers, groups, popup, visible, json, clustered, getFeatureInfo, settings, folder): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) mapSettings = iface.mapCanvas().mapSettings() controlCount = 0 stamp = datetime.now().strftime("%Y_%m_%d-%H_%M_%S_%f") folder = os.path.join(folder, 'qgis2ol5_' + unicode(stamp)) restrictToExtent = settings["Scale/Zoom"]["Restrict to extent"] matchCRS = settings["Appearance"]["Match project CRS"] precision = settings["Data export"]["Precision"] optimize = settings["Data export"]["Minify GeoJSON files"] debugLibs = settings["Data export"]["Use debug libraries"] extent = settings["Scale/Zoom"]["Extent"] mapbounds = bounds(iface, extent == "Canvas extent", layers, matchCRS) fullextent = bounds(iface, False, layers, matchCRS) geolocateUser = settings["Appearance"]["Geolocate user"] maxZoom = int(settings["Scale/Zoom"]["Max zoom level"]) minZoom = int(settings["Scale/Zoom"]["Min zoom level"]) popupsOnHover = settings["Appearance"]["Show popups on hover"] highlightFeatures = settings["Appearance"]["Highlight on hover"] geocode = settings["Appearance"]["Add address search"] measureTool = settings["Appearance"]["Measure tool"] addLayersList = settings["Appearance"]["Add layers list"] htmlTemplate = settings["Appearance"]["Template"] layerSearch = unicode(settings["Appearance"]["Layer search"]) searchLayer = settings["Appearance"]["Search layer"] mapLibLocn = settings["Data export"]["Mapping library location"] writeFiles(folder, restrictToExtent, feedback, debugLibs) exportLayers(iface, layers, folder, precision, optimize, popup, json, restrictToExtent, extent, feedback, matchCRS) mapUnitsLayers = exportStyles(layers, folder, clustered) mapUnitLayers = getMapUnitLayers(mapUnitsLayers) osmb = writeLayersAndGroups(layers, groups, visible, folder, popup, settings, json, matchCRS, clustered, getFeatureInfo, iface, restrictToExtent, extent, mapbounds, mapSettings.destinationCrs().authid()) (jsAddress, cssAddress, layerSearch, controlCount) = writeHTMLstart(settings, controlCount, osmb, mapLibLocn, layerSearch, searchLayer, feedback, debugLibs) (geojsonVars, wfsVars, styleVars) = writeScriptIncludes(layers, json, matchCRS) popupLayers = "popupLayers = [%s];" % ",".join( ['1' for field in popup]) project = QgsProject.instance() controls = getControls(project, measureTool, geolocateUser) layersList = getLayersList(addLayersList) pageTitle = project.title() backgroundColor = getBackground(mapSettings) (geolocateCode, controlCount) = geolocateStyle(geolocateUser, controlCount) backgroundColor += geolocateCode mapextent = "extent: %s," % mapbounds if restrictToExtent else "" onHover = unicode(popupsOnHover).lower() highlight = unicode(highlightFeatures).lower() highlightFill = mapSettings.selectionColor().name() (proj, proj4, view) = getCRSView(mapextent, fullextent, maxZoom, minZoom, matchCRS, mapSettings) (measureControl, measuring, measure, measureUnit, measureStyle, controlCount) = getMeasure(measureTool, controlCount) geolocateHead = geolocationHead(geolocateUser) geolocate = geolocation(geolocateUser) geocodingLinks = geocodeLinks(geocode) geocodingJS = geocodeJS(geocode) geocodingScript = geocodeScript(geocode) m2px = getM2px(mapUnitsLayers) (extracss, controlCount) = getCSS(geocode, geolocateUser, controlCount) ol3layerswitcher = getLayerSwitcher() ol3popup = getPopup() ol3qgis2ol5js = getJS(osmb) ol3layers = getLayers() mapSize = iface.mapCanvas().size() exp_js = getExpJS() grid = getGrid(project) values = { "@PAGETITLE@": pageTitle, "@CSSADDRESS@": cssAddress, "@EXTRACSS@": extracss, "@JSADDRESS@": jsAddress, "@MAP_WIDTH@": unicode(mapSize.width()) + "px", "@MAP_HEIGHT@": unicode(mapSize.height()) + "px", "@OL3_STYLEVARS@": styleVars, "@OL3_BACKGROUNDCOLOR@": backgroundColor, "@OL3_POPUP@": ol3popup, "@OL3_GEOJSONVARS@": geojsonVars, "@OL3_WFSVARS@": wfsVars, "@OL3_PROJ4@": proj4, "@OL3_PROJDEF@": proj, "@OL3_GEOCODINGLINKS@": geocodingLinks, "@OL3_GEOCODINGJS@": geocodingJS, "@qgis2ol5JS@": ol3qgis2ol5js, "@OL3_LAYERSWITCHER@": ol3layerswitcher, "@OL3_LAYERS@": ol3layers, "@OL3_MEASURESTYLE@": measureStyle, "@EXP_JS@": exp_js, "@LEAFLET_ADDRESSCSS@": "", "@LEAFLET_MEASURECSS@": "", "@LEAFLET_EXTRAJS@": "", "@LEAFLET_ADDRESSJS@": "", "@LEAFLET_MEASUREJS@": "", "@LEAFLET_CRSJS@": "", "@LEAFLET_LAYERSEARCHCSS@": "", "@LEAFLET_LAYERSEARCHJS@": "", "@LEAFLET_CLUSTERCSS@": "", "@LEAFLET_CLUSTERJS@": "" } with open(os.path.join(folder, "index.html"), "w") as f: htmlTemplate = htmlTemplate if htmlTemplate == "": htmlTemplate = "basic" templateOutput = replaceInTemplate(htmlTemplate + ".html", values) templateOutput = re.sub(r'\n[\s_]+\n', '\n', templateOutput) f.write(templateOutput.encode('utf-8')) values = { "@GEOLOCATEHEAD@": geolocateHead, "@BOUNDS@": mapbounds, "@CONTROLS@": ",".join(controls), "@LAYERSLIST@": layersList, "@POPUPLAYERS@": popupLayers, "@VIEW@": view, "@LAYERSEARCH@": layerSearch, "@ONHOVER@": onHover, "@DOHIGHLIGHT@": highlight, "@HIGHLIGHTFILL@": highlightFill, "@GEOLOCATE@": geolocate, "@GEOCODINGSCRIPT@": geocodingScript, "@MEASURECONTROL@": measureControl, "@MEASURING@": measuring, "@MEASURE@": measure, "@MEASUREUNIT@": measureUnit, "@GRID@": grid, "@M2PX@": m2px, "@MAPUNITLAYERS@": mapUnitLayers } with open(os.path.join(folder, "resources", "qgis2ol5.js"), "w") as f: out = replaceInScript("qgis2ol5.js", values) f.write(out.encode("utf-8")) QApplication.restoreOverrideCursor() return os.path.join(folder, "index.html")
def writeOL(iface, layers, groups, popup, visible, json, clustered, settings, folder): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) stamp = time.strftime("%Y_%m_%d-%H_%M_%S") folder = os.path.join(folder, 'qgis2web_' + unicode(stamp)) try: dst = os.path.join(folder, "resources") if not os.path.exists(dst): shutil.copytree(os.path.join(os.path.dirname(__file__), "resources"), dst) matchCRS = settings["Appearance"]["Match project CRS"] precision = settings["Data export"]["Precision"] optimize = settings["Data export"]["Minify GeoJSON files"] cleanUnusedFields = settings["Data export"]["Delete unused fields"] if not cleanUnusedFields: usedFields = [ALL_ATTRIBUTES] * len(popup) else: usedFields = popup exportLayers(iface, layers, folder, precision, optimize, usedFields, json) exportStyles(layers, folder, clustered) writeLayersAndGroups(layers, groups, visible, folder, settings, json, matchCRS, clustered) if settings["Data export"]["Mapping library location"] == "Local": cssAddress = """<link rel="stylesheet" """ cssAddress += """href="./resources/ol.css" />""" jsAddress = """<script src="./resources/ol.js"></script>""" else: cssAddress = """<link rel="stylesheet" href="http://""" cssAddress += """openlayers.org/en/v3.12.1/css/ol.css" />""" jsAddress = """<script src="http://openlayers.org/en/v3.12.1/""" jsAddress += """build/ol.js"></script>""" geojsonVars = "" wfsVars = "" styleVars = "" for layer, encode2json in zip(layers, json): if layer.type() == layer.VectorLayer: if layer.providerType() != "WFS" or encode2json: geojsonVars += ('<script src="layers/%s"></script>' % (safeName(layer.name()) + ".js")) else: layerSource = layer.source() if not matchCRS: layerSource = re.sub('SRSNAME\=EPSG\:\d+', 'SRSNAME=EPSG:3857', layerSource) layerSource += "&outputFormat=text%2Fjavascript&" layerSource += "format_options=callback%3A" layerSource += "get" + safeName(layer.name()) + "Json" wfsVars += ('<script src="%s"></script>' % layerSource) styleVars += ('<script src="styles/%s_style.js"></script>' % (safeName(layer.name()))) popupLayers = "popupLayers = [%s];" % ",".join(['"%s"' % field if ( isinstance(field, basestring)) else unicode(field) for field in popup]) controls = ['expandedAttribution'] # Check qgis2web.js 14:7 if settings["Appearance"]["Add scale bar"]: controls.append("new ol.control.ScaleLine({})") if settings["Appearance"]["Add layers list"]: controls.append( 'new ol.control.LayerSwitcher({tipLabel: "Layers"})') if settings["Appearance"]["Add measure tool"]: controls.append( 'new measureControl()') pageTitle = QgsProject.instance().title() mapSettings = iface.mapCanvas().mapSettings() backgroundColor = """ <style> html, body {{ background-color: {bgcol}; }} </style> """.format(bgcol=mapSettings.backgroundColor().name()) mapbounds = bounds(iface, settings["Scale/Zoom"]["Extent"] == "Canvas extent", layers, settings["Appearance"]["Match project CRS"]) mapextent = "extent: %s," % mapbounds if ( settings["Scale/Zoom"]["Restrict to extent"]) else "" maxZoom = int(settings["Scale/Zoom"]["Max zoom level"]) minZoom = int(settings["Scale/Zoom"]["Min zoom level"]) popupsOnHover = settings["Appearance"]["Show popups on hover"] highlightFeatures = settings["Appearance"]["Highlight features"] onHover = unicode(popupsOnHover).lower() highlight = unicode(highlightFeatures).lower() highlightFill = mapSettings.selectionColor().name() proj4 = "" projdef = "" view = "%s maxZoom: %d, minZoom: %d" % (mapextent, maxZoom, minZoom) if settings["Appearance"]["Match project CRS"]: proj4 = """ <script src="http://cdnjs.cloudflare.com/ajax/libs/proj4js/2.3.6/proj4.js">""" proj4 += "</script>" projdef = "<script>proj4.defs('{epsg}','{defn}');</script>".format( epsg=mapSettings.destinationCrs().authid(), defn=mapSettings.destinationCrs().toProj4()) view += ", projection: '%s'" % ( mapSettings.destinationCrs().authid()) if settings["Appearance"]["Add measure tool"]: measureControl = """ var measuring = false; measureControl = function(opt_options) { var options = opt_options || {}; var button = document.createElement('button'); button.innerHTML = '<img src="resources/measure-control.png" />'; var this_ = this; var handleMeasure = function(e) { if (!measuring) { this_.getMap().addInteraction(draw); measuring = true; } else { this_.getMap().removeInteraction(draw); measuring = false; } }; button.addEventListener('click', handleMeasure, false); button.addEventListener('touchstart', handleMeasure, false); var element = document.createElement('div'); element.className = 'measure-control ol-unselectable ol-control'; element.appendChild(button); ol.control.Control.call(this, { element: element, target: options.target }); }; ol.inherits(measureControl, ol.control.Control);""" measuring = """ if (evt.dragging) { return; } /** @type {string} */ var helpMsg = 'Click to start drawing'; if (sketch) { var geom = (sketch.getGeometry()); if (geom instanceof ol.geom.Polygon) { helpMsg = continuePolygonMsg; } else if (geom instanceof ol.geom.LineString) { helpMsg = continueLineMsg; } } helpTooltipElement.innerHTML = helpMsg; helpTooltip.setPosition(evt.coordinate); document.getElementById('helpTooltipElement').removeClass('hidden');""" measure = """ /** * Currently drawn feature. * @type {ol.Feature} */ var sketch; /** * The help tooltip element. * @type {Element} */ var helpTooltipElement; /** * Overlay to show the help messages. * @type {ol.Overlay} */ var helpTooltip; /** * The measure tooltip element. * @type {Element} */ var measureTooltipElement; /** * Overlay to show the measurement. * @type {ol.Overlay} */ var measureTooltip; /** * Message to show when the user is drawing a line. * @type {string} */ var continueLineMsg = 'Click to continue drawing the line'; var source = new ol.source.Vector(); var draw; // global so we can remove it later function addInteraction() { var type = 'LineString'; draw = new ol.interaction.Draw({ source: source, type: /** @type {ol.geom.GeometryType} */ (type), style: new ol.style.Style({ fill: new ol.style.Fill({ color: 'rgba(255, 255, 255, 0.2)' }), stroke: new ol.style.Stroke({ color: 'rgba(0, 0, 0, 0.5)', lineDash: [10, 10], width: 2 }), image: new ol.style.Circle({ radius: 5, stroke: new ol.style.Stroke({ color: 'rgba(0, 0, 0, 0.7)' }), fill: new ol.style.Fill({ color: 'rgba(255, 255, 255, 0.2)' }) }) }) }); //map.addInteraction(draw); createMeasureTooltip(); createHelpTooltip(); var listener; draw.on('drawstart', function(evt) { // set sketch sketch = evt.feature; /** @type {ol.Coordinate|undefined} */ var tooltipCoord = evt.coordinate; listener = sketch.getGeometry().on('change', function(evt) { var geom = evt.target; var output; output = formatLength( /** @type {ol.geom.LineString} */ (geom)); tooltipCoord = geom.getLastCoordinate(); measureTooltipElement.innerHTML = output; measureTooltip.setPosition(tooltipCoord); }); }, this); draw.on('drawend', function(evt) { measureTooltipElement.className = 'tooltip tooltip-static'; measureTooltip.setOffset([0, -7]); // unset sketch sketch = null; // unset tooltip so that a new one can be created measureTooltipElement = null; createMeasureTooltip(); ol.Observable.unByKey(listener); }, this); } /** * Creates a new help tooltip */ function createHelpTooltip() { if (helpTooltipElement) { helpTooltipElement.parentNode.removeChild(helpTooltipElement); } helpTooltipElement = document.createElement('div'); helpTooltipElement.className = 'tooltip hidden'; helpTooltip = new ol.Overlay({ element: helpTooltipElement, offset: [15, 0], positioning: 'center-left' }); map.addOverlay(helpTooltip); } /** * Creates a new measure tooltip */ function createMeasureTooltip() { if (measureTooltipElement) { measureTooltipElement.parentNode.removeChild(measureTooltipElement); } measureTooltipElement = document.createElement('div'); measureTooltipElement.className = 'tooltip tooltip-measure'; measureTooltip = new ol.Overlay({ element: measureTooltipElement, offset: [0, -15], positioning: 'bottom-center' }); map.addOverlay(measureTooltip); } /** * format length output * @param {ol.geom.LineString} line * @return {string} */ var formatLength = function(line) { var length; length = Math.round(line.getLength() * 100) / 100; var output; if (length > 100) { output = (Math.round(length / 1000 * 100) / 100) + ' ' + 'km'; } else { output = (Math.round(length * 100) / 100) + ' ' + 'm'; } return output; }; addInteraction();""" measureStyle = """ <style> .tooltip { position: relative; background: rgba(0, 0, 0, 0.5); border-radius: 4px; color: white; padding: 4px 8px; opacity: 0.7; white-space: nowrap; } .tooltip-measure { opacity: 1; font-weight: bold; } .tooltip-static { background-color: #ffcc33; color: black; border: 1px solid white; } .tooltip-measure:before, .tooltip-static:before { border-top: 6px solid rgba(0, 0, 0, 0.5); border-right: 6px solid transparent; border-left: 6px solid transparent; content: ""; position: absolute; bottom: -6px; margin-left: -7px; left: 50%; } .tooltip-static:before { border-top-color: #ffcc33; } .measure-control { top: 65px; left: .5em; } .ol-touch .measure-control { top: 80px; } </style>""" else: measureControl = "" measuring = "" measure = "" measureStyle = "" geolocate = geolocation(settings["Appearance"]["Geolocate user"]) geocode = settings["Appearance"]["Add address search"] geocodingLinks = geocodeLinks(geocode) geocodingScript = geocodeScript(geocode) extracss = """ <link rel="stylesheet" href="./resources/ol3-layerswitcher.css"> <link rel="stylesheet" href="./resources/qgis2web.css">""" ol3layerswitcher = """ <script src="./resources/ol3-layerswitcher.js"></script>""" ol3popup = """<div id="popup" class="ol-popup"> <a href="#" id="popup-closer" class="ol-popup-closer"></a> <div id="popup-content"></div> </div>""" ol3qgis2webjs = """<script src="./resources/qgis2web.js"></script>""" ol3layers = """ <script src="./layers/layers.js" type="text/javascript"></script>""" mapSize = iface.mapCanvas().size() values = {"@PAGETITLE@": pageTitle, "@CSSADDRESS@": cssAddress, "@EXTRACSS@": extracss, "@JSADDRESS@": jsAddress, "@MAP_WIDTH@": unicode(mapSize.width()) + "px", "@MAP_HEIGHT@": unicode(mapSize.height()) + "px", "@OL3_STYLEVARS@": styleVars, "@OL3_BACKGROUNDCOLOR@": backgroundColor, "@OL3_POPUP@": ol3popup, "@OL3_GEOJSONVARS@": geojsonVars, "@OL3_WFSVARS@": wfsVars, "@OL3_PROJ4@": proj4, "@OL3_PROJDEF@": projdef, "@OL3_GEOCODINGLINKS@": geocodingLinks, "@QGIS2WEBJS@": ol3qgis2webjs, "@OL3_LAYERSWITCHER@": ol3layerswitcher, "@OL3_LAYERS@": ol3layers, "@OL3_MEASURESTYLE@": measureStyle, "@LEAFLET_ADDRESSCSS@": "", "@LEAFLET_MEASURECSS@": "", "@LEAFLET_EXTRAJS@": "", "@LEAFLET_ADDRESSJS@": "", "@LEAFLET_MEASUREJS@": "", "@LEAFLET_CRSJS@": "", "@LEAFLET_CLUSTERCSS@": "", "@LEAFLET_CLUSTERJS@": ""} with open(os.path.join(folder, "index.html"), "w") as f: htmlTemplate = settings["Appearance"]["Template"] if htmlTemplate == "": htmlTemplate = "basic" f.write(replaceInTemplate(htmlTemplate + ".html", values)) values = {"@BOUNDS@": mapbounds, "@CONTROLS@": ",".join(controls), "@POPUPLAYERS@": popupLayers, "@VIEW@": view, "@ONHOVER@": onHover, "@DOHIGHLIGHT@": highlight, "@HIGHLIGHTFILL@": highlightFill, "@GEOLOCATE@": geolocate, "@GEOCODINGSCRIPT@": geocodingScript, "@MEASURECONTROL@": measureControl, "@MEASURING@": measuring, "@MEASURE@": measure} with open(os.path.join(folder, "resources", "qgis2web.js"), "w") as f: f.write(replaceInScript("qgis2web.js", values)) except Exception as e: print "FAIL" print traceback.format_exc() finally: QApplication.restoreOverrideCursor() return os.path.join(folder, "index.html")