def add_tiled_web_map_layer(self): """ Add tiled web map layer to project.""" zmin = "&zmin=0" zmax = "" if self.mCheckBoxZMax_2.isChecked(): zmax = "&zmax=" + self.mSpinZMax_2.text() if self.url_comboBox.currentText() == "OpenStreetMap": # open street map url_with_params = 'type=xyz&url=http://a.tile.openstreetmap.org/%7Bz%7D/%7Bx%7D/%7By%7D.png' + zmax + zmin elif self.url_comboBox.currentText() == "Google Hybrid": # per google maps url_with_params = 'type=xyz&url=https://mt1.google.com/vt/lyrs%3Dy%26x%3D%7Bx%7D%26y%3D%7By%7D%26z%3D%7Bz%7D' + zmax + zmin elif self.url_comboBox.currentText() == "Google Map": # per google maps url_with_params = 'type=xyz&url=https://mt1.google.com/vt/lyrs%3Dm%26x%3D%7Bx%7D%26y%3D%7By%7D%26z%3D%7Bz%7D' + zmax + zmin elif self.url_comboBox.currentText() == "Google Satelite": # per google maps url_with_params = 'type=xyz&url=https://mt1.google.com/vt/lyrs%3Ds%26x%3D%7Bx%7D%26y%3D%7By%7D%26z%3D%7Bz%7D' + zmax + zmin if self.mEditName_2.text() == "": self.mEditName_2.setText(self.url_comboBox.currentText()) xyz_layer = QgsRasterLayer(url_with_params, self.mEditName_2.text(), 'wms') if not xyz_layer.isValid(): logger.error("Failed to load layer!") QMessageBox.critical(self, "Add Layer", "Layer format is not recognised as a supported file format", QMessageBox.Close) self.msglog.logMessage("Failed to load layer " + xyz_layer.name(), "LoadingLayer", 1) else: self.proj.addMapLayer(xyz_layer) self.accept()
def create_default_project(available_maps, visible_maps, project_template, authcfg=None): """Create a default project from a template and return it as a string""" layers = [] for m in available_maps: connstring = u'type=xyz&url=%(url)s' if authcfg is not None: connstring = u'authcfg=%(authcfg)s&' + connstring layer = QgsRasterLayer(connstring % { 'url': quote(m['endpoint']), 'authcfg': authcfg, }, m['name'], 'wms') # I've no idea why the following is required even if the crs is specified # in the layer definition layer.setCrs(QgsCoordinateReferenceSystem('EPSG:3857')) layers.append(layer) if len(layers): xml = QgsMapLayer.asLayerDefinition(layers) maplayers = "\n".join(xml.toString().split("\n")[3:-3]) layer_tree_layer = "" custom_order = "" legend_layer = "" layer_coordinate_transform = "" for layer in layers: is_visible = layer.name() in visible_maps values = {'name': layer.name(), 'id': layer.id(), 'visible': ('1' if is_visible else '0'), 'checked': ('Qt::Checked' if is_visible else 'Qt::Unchecked')} custom_order += "<item>%s</item>" % layer.id() layer_tree_layer += """ <layer-tree-layer expanded="1" checked="%(checked)s" id="%(id)s" name="%(name)s"> <customproperties/> </layer-tree-layer>""" % values legend_layer += """ <legendlayer drawingOrder="-1" open="true" checked="%(checked)s" name="%(name)s" showFeatureCount="0"> <filegroup open="true" hidden="false"> <legendlayerfile isInOverview="0" layerid="%(id)s" visible="%(visible)s"/> </filegroup> </legendlayer>""" % values layer_coordinate_transform += '<layer_coordinate_transform destAuthId="EPSG:3857" srcAuthId="EPSG:3857" srcDatumTransform="-1" destDatumTransform="-1" layerid="%s"/>' % layer.id() tpl = "" with open(project_template, 'rb') as f: tpl = f.read() for tag in ['custom_order', 'layer_tree_layer', 'legend_layer', 'layer_coordinate_transform', 'maplayers']: tpl = tpl.replace("#%s#" % tag.upper(), locals()[tag]) return tpl else: return None
def createDefaultProject(available_maps, visible_maps, project_template, authcfg=None): """Create a default project from a template and return it as a string""" layers = [] for m in available_maps: connstring = u'type=xyz&url={url}' if authcfg is not None: connstring = u'authcfg={authcfg}&' + connstring layer = QgsRasterLayer(connstring.format(url=urllib2.quote("{}?version={}".format(m['endpoint'], pluginSetting("apiVersion"))), authcfg=authcfg), m['name'], "wms") # I've no idea why the following is required even if the crs is specified # in the layer definition layer.setCrs(QgsCoordinateReferenceSystem('EPSG:3857')) layers.append(layer) if len(layers): xml = QgsMapLayer.asLayerDefinition(layers) maplayers = "\n".join(xml.toString().split("\n")[3:-3]) layer_tree_layer = "" custom_order = "" legend_layer = "" layer_coordinate_transform = "" for layer in layers: is_visible = layer.name() in visible_maps values = {'name': layer.name(), 'id': layer.id(), 'visible': ('1' if is_visible else '0'), 'checked': ('Qt::Checked' if is_visible else 'Qt::Unchecked')} custom_order += "<item>%s</item>" % layer.id() layer_tree_layer += """ <layer-tree-layer expanded="1" checked="%(checked)s" id="%(id)s" name="%(name)s"> <customproperties/> </layer-tree-layer>""" % values legend_layer += """ <legendlayer drawingOrder="-1" open="true" checked="%(checked)s" name="%(name)s" showFeatureCount="0"> <filegroup open="true" hidden="false"> <legendlayerfile isInOverview="0" layerid="%(id)s" visible="%(visible)s"/> </filegroup> </legendlayer>""" % values layer_coordinate_transform += '<layer_coordinate_transform destAuthId="EPSG:3857" srcAuthId="EPSG:3857" srcDatumTransform="-1" destDatumTransform="-1" layerid="%s"/>' % layer.id() tpl = "" with open(project_template, 'rb') as f: tpl = f.read() for tag in ['custom_order', 'layer_tree_layer', 'legend_layer', 'layer_coordinate_transform', 'maplayers']: tpl = tpl.replace("#%s#" % tag.upper(), locals()[tag]) return tpl else: return None
def importLayer(self, layerType, providerKey, layerName, uriString, parent): global isImportVectorAvail if not isImportVectorAvail: return False if layerType == 'raster': return False # not implemented yet inLayer = QgsRasterLayer(uriString, layerName, providerKey) else: inLayer = QgsVectorLayer(uriString, layerName, providerKey) if not inLayer.isValid(): # invalid layer QMessageBox.warning( None, self.tr("Invalid layer"), self.tr("Unable to load the layer %s") % inLayer.name()) return False # retrieve information about the new table's db and schema outItem = parent.internalPointer() outObj = outItem.getItemData() outDb = outObj.database() outSchema = None if isinstance(outItem, SchemaItem): outSchema = outObj elif isinstance(outItem, TableItem): outSchema = outObj.schema() # toIndex will point to the parent item of the new table toIndex = parent if isinstance(toIndex.internalPointer(), TableItem): toIndex = toIndex.parent() if inLayer.type() == inLayer.VectorLayer: # create the output uri schema = outSchema.name if outDb.schemas( ) is not None and outSchema is not None else "" pkCol = geomCol = "" # default pk and geom field name value if providerKey in ['postgres', 'spatialite']: inUri = QgsDataSourceURI(inLayer.source()) pkCol = inUri.keyColumn() geomCol = inUri.geometryColumn() outUri = outDb.uri() outUri.setDataSource(schema, layerName, geomCol, "", pkCol) self.importVector.emit(inLayer, outDb, outUri, toIndex) return True return False
def _set_time_range(self, layer: QgsRasterLayer) -> None: """ Sets temporal settings for layer, especially start time and end time (since QGIS 3.14). Args: layer (QgsRasterLayer): Raster layer for which to set temporal settings """ time_delta = self._extract_time_delta_from_layer_name(layer.name()) timestamp_end = self._extract_timestamp_from_layername(layer.name()) timestamp_start = timestamp_end - time_delta self.out( f"Time range from {timestamp_start:%d.%m.%Y %H:%M} to {timestamp_end:%d.%m.%Y %H:%M}." ) temp_props = layer.temporalProperties() temp_props.setMode( QgsRasterLayerTemporalProperties.ModeFixedTemporalRange) temp_props.setFixedTemporalRange( QgsDateTimeRange(timestamp_start, timestamp_end)) temp_props.setIsActive(True)
def add_raster_layer(self): """ Add raster layer to project.""" self.raster_filename = self.raster_file_lineEdit.text() self.raster_base_name = self.raster_name_lineEdit.text() rlayer = QgsRasterLayer(self.raster_filename, self.raster_base_name) if not rlayer.isValid(): logger.error("Failed to load layer!") QMessageBox.critical(self, "Add Layer", "Layer format is not recognised as a supported file format", QMessageBox.Close) self.msglog.logMessage("Failed to load layer " + rlayer.name(), "LoadingLayer", 1) self.raster_file_lineEdit.setText('') self.raster_name_lineEdit.setText('') else: self.proj.addMapLayer(rlayer) self.canvas.setExtent(rlayer.extent()) self.accept()
def _build_pyramids(self, layer: QgsRasterLayer) -> QgsRasterLayer: """ Builds pyramids (overviews) for raster layer. Args: layer (QgsRasterLayer): Raster layer for which to build pyramids Returns: QgsRasterLayer: Raster layer with pyramids """ parameters = { "INPUT": layer, "LEVELS": "2 4 8 16", "CLEAN": False, "RESAMPLING": 0, "FORMAT": 0, "OUTPUT": layer, } result = processing.run("gdal:overviews", parameters) return QgsRasterLayer(result["OUTPUT"], layer.name())
def importLayer(self, layerType, providerKey, layerName, uriString, parent): global isImportVectorAvail if not isImportVectorAvail: return False if layerType == 'raster': return False # not implemented yet inLayer = QgsRasterLayer(uriString, layerName, providerKey) else: inLayer = QgsVectorLayer(uriString, layerName, providerKey) if not inLayer.isValid(): # invalid layer QMessageBox.warning(None, self.tr("Invalid layer"), self.tr("Unable to load the layer %s") % inLayer.name()) return False # retrieve information about the new table's db and schema outItem = parent.internalPointer() outObj = outItem.getItemData() outDb = outObj.database() outSchema = None if isinstance(outItem, SchemaItem): outSchema = outObj elif isinstance(outItem, TableItem): outSchema = outObj.schema() # toIndex will point to the parent item of the new table toIndex = parent if isinstance(toIndex.internalPointer(), TableItem): toIndex = toIndex.parent() if inLayer.type() == inLayer.VectorLayer: # create the output uri schema = outSchema.name if outDb.schemas() is not None and outSchema is not None else "" pkCol = geomCol = "" # default pk and geom field name value if providerKey in ['postgres', 'spatialite']: inUri = QgsDataSourceUri(inLayer.source()) pkCol = inUri.keyColumn() geomCol = inUri.geometryColumn() outUri = outDb.uri() outUri.setDataSource(schema, layerName, geomCol, "", pkCol) self.importVector.emit(inLayer, outDb, outUri, toIndex) return True return False
def cvt_vtr(self): QSWATMOD_path_dict = self.dirs_and_paths() selectedVector = self.dlg.comboBox_vector_lyrs.currentText() layer = QgsProject.instance().mapLayersByName(str(selectedVector))[0] # Find .dis file and read number of rows, cols, x spacing, and y spacing (not allowed to change) for filename in glob.glob(str(QSWATMOD_path_dict['SMfolder']) + "/*.dis"): with open(filename, "r") as f: data = [] for line in f.readlines(): if not line.startswith("#"): data.append(line.replace('\n', '').split()) nrow = int(data[0][1]) ncol = int(data[0][2]) delr = float(data[2][1]) # is the cell width along rows (y spacing) delc = float( data[3][1]) # is the cell width along columns (x spacing). # get extent ext = layer.extent() xmin = ext.xMinimum() xmax = ext.xMaximum() ymin = ext.yMinimum() ymax = ext.yMaximum() extent = "{a},{b},{c},{d}".format(a=xmin, b=xmax, c=ymin, d=ymax) fdnames = [ field.name() for field in layer.dataProvider().fields() if not (field.name() == 'fid' or field.name() == 'id' or field.name() == 'xmin' or field.name() == 'xmax' or field.name() == 'ymin' or field.name() == 'ymax' or field.name() == 'grid_id' or field.name() == 'row' or field.name() == 'col' or field.name() == 'elev_mf') ] # Create swatmf_results tree inside root = QgsProject.instance().layerTreeRoot() if root.findGroup("swatmf_results"): swatmf_results = root.findGroup("swatmf_results") else: swatmf_results = root.insertGroup(0, "swatmf_results") if root.findGroup(selectedVector): rastergroup = root.findGroup(selectedVector) else: rastergroup = swatmf_results.insertGroup(0, selectedVector) per = 0 self.dlg.progressBar_cvt_vtr.setValue(0) for fdnam in fdnames: QCoreApplication.processEvents() nodata = float(self.dlg.lineEdit_nodata.text()) mincolor = self.dlg.mColorButton_min_rmap.color().name() maxcolor = self.dlg.mColorButton_max_rmap.color().name() name = fdnam name_ext = "{}.tif".format(name) output_dir = QSWATMOD_path_dict['SMshps'] # create folder for each layer output rasterpath = os.path.join(output_dir, selectedVector) if not os.path.exists(rasterpath): os.makedirs(rasterpath) output_raster = os.path.join(rasterpath, name_ext) params = { 'INPUT': layer, 'FIELD': fdnam, 'UNITS': 1, 'WIDTH': delc, 'HEIGHT': delr, 'EXTENT': extent, 'NODATA': nodata, 'DATA_TYPE': 5, #Float32 'OUTPUT': output_raster } processing.run("gdal:rasterize", params) rasterlayer = QgsRasterLayer(output_raster, '{0} ({1})'.format(fdnam, selectedVector)) QgsProject.instance().addMapLayer(rasterlayer, False) rastergroup.insertChildNode(0, QgsLayerTreeLayer(rasterlayer)) stats = rasterlayer.dataProvider().bandStatistics( 1, QgsRasterBandStats.All) rmin = stats.minimumValue rmax = stats.maximumValue fnc = QgsColorRampShader() lst = [ QgsColorRampShader.ColorRampItem(rmin, QColor(mincolor)), QgsColorRampShader.ColorRampItem(rmax, QColor(maxcolor)) ] fnc.setColorRampItemList(lst) fnc.setColorRampType(QgsColorRampShader.Interpolated) shader = QgsRasterShader() shader.setRasterShaderFunction(fnc) renderer = QgsSingleBandPseudoColorRenderer(rasterlayer.dataProvider(), 1, shader) rasterlayer.setRenderer(renderer) rasterlayer.triggerRepaint() # create image img = QImage(QSize(800, 800), QImage.Format_ARGB32_Premultiplied) # set background color # bcolor = QColor(255, 255, 255, 255) bcolor = QColor(255, 255, 255, 0) img.fill(bcolor.rgba()) # create painter p = QPainter() p.begin(img) p.setRenderHint(QPainter.Antialiasing) # create map settings ms = QgsMapSettings() ms.setBackgroundColor(bcolor) # set layers to render flayer = QgsProject.instance().mapLayersByName(rasterlayer.name()) ms.setLayers([flayer[0]]) # set extent rect = QgsRectangle(ms.fullExtent()) rect.scale(1.1) ms.setExtent(rect) # set ouptut size ms.setOutputSize(img.size()) # setup qgis map renderer render = QgsMapRendererCustomPainterJob(ms, p) render.start() render.waitForFinished() # get timestamp p.drawImage(QPoint(), img) pen = QPen(Qt.red) pen.setWidth(2) p.setPen(pen) font = QFont() font.setFamily('Times') # font.setBold(True) font.setPointSize(18) p.setFont(font) # p.setBackground(QColor('sea green')) doesn't work p.drawText(QRect(0, 0, 800, 800), Qt.AlignRight | Qt.AlignBottom, fdnam) p.end() # save the image img.save(os.path.join(rasterpath, '{:03d}_{}.jpg'.format(per, fdnam))) # Update progress bar per += 1 progress = round((per / len(fdnames)) * 100) self.dlg.progressBar_cvt_vtr.setValue(progress) QCoreApplication.processEvents() self.dlg.raise_() duration = self.dlg.doubleSpinBox_ani_r_time.value() # filepaths fp_in = os.path.join(rasterpath, '*.jpg') fp_out = os.path.join(rasterpath, '{}.gif'.format(selectedVector)) # https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#gif fimg, *fimgs = [Image.open(f) for f in sorted(glob.glob(fp_in))] fimg.save(fp=fp_out, format='GIF', append_images=fimgs, save_all=True, duration=duration * 1000, loop=0, transparency=0) msgBox = QMessageBox() msgBox.setWindowIcon(QtGui.QIcon(':/QSWATMOD2/pics/sm_icon.png')) msgBox.setWindowTitle("Coverted!") msgBox.setText( "Fields from {} were converted successfully!".format(selectedVector)) msgBox.exec_() questionBox = QMessageBox() questionBox.setWindowIcon(QtGui.QIcon(':/QSWATMOD2/pics/sm_icon.png')) reply = QMessageBox.question(questionBox, 'Open?', 'Do you want to open the animated gif file?', QMessageBox.Yes, QMessageBox.No) if reply == QMessageBox.Yes: os.startfile(os.path.join(rasterpath, '{}.gif'.format(selectedVector)))
xorigin, xcellsize, xrotation, yorigion, yrotation, ycellsize = gt # Get and Print Projection Information projInfo=dem .GetProjection() print projInfo demLayer = QgsRasterLayer(os.path.join(input_Dir,dem_filename), "dem") if not demLayer.isValid(): print "DEM Layer failed to load!" # Load raster layer into canvas QgsMapLayerRegistry.instance().addMapLayer(demLayer) # Print Extent of the DEM layer (for use with raster calculator) print demLayer.extent().xMinimum(), demLayer.extent().xMaximum() print demLayer.extent().yMinimum(), demLayer.extent().yMaximum() print demLayer.width(), demLayer.height() name = demLayer.name() print name bands = demLayer.bandCount() print bands # Slope layer degslopeLayer = QgsRasterLayer(os.path.join(input_Dir,'slope_dec.tif'), "Degrees_Slope") if not degslopeLayer.isValid(): print "Slope (decimal degrees) Layer failed to load!" # Load raster layer into canvas QgsMapLayerRegistry.instance().addMapLayer(degslopeLayer) # Aspect layer degaspectLayer = QgsRasterLayer(os.path.join(input_Dir,'aspect_dec.tif'), "Degrees_Aspect") if not degaspectLayer.isValid(): print "Aspect (decimal degrees) Layer failed to load!" # Load raster layer into canvas QgsMapLayerRegistry.instance().addMapLayer(degaspectLayer)
def addToDefaultProject(maps, visibleMaps, authcfg=None): """Add basemaps to the existing default project""" layers = [] for m in maps: connstring = u'type=xyz&url={url}' if authcfg is not None: connstring = u'authcfg={authcfg}&' + connstring layer = QgsRasterLayer(connstring.format(url=urllib2.quote("{}?version={}".format(m['endpoint'], pluginSetting("apiVersion"))), authcfg=authcfg), m['name'], 'wms') # I've no idea why the following is required even if the crs is specified # in the layer definition layer.setCrs(QgsCoordinateReferenceSystem('EPSG:3857')) layers.append(layer) if os.path.isfile(defaultProjectPath()): backup = defaultProjectPath().replace( '.qgs', '-%s.qgs' % datetime.now().strftime('%Y-%m-%d-%H_%M_%S')) shutil.copy2(defaultProjectPath(), backup) # open default project with open(defaultProjectPath()) as f: content = f.read() doc = QDomDocument() setOk, errorString, errorLine, errorColumn = doc.setContent(content) if not setOk: return False root = doc.documentElement() for layer in layers: is_visible = layer.name() in visibleMaps xml = QgsMapLayer.asLayerDefinition([layer]) r = xml.documentElement() mapLayerElement = r.firstChildElement("maplayers").firstChildElement("maplayer") layerTreeLayerElement = doc.createElement("layer-tree-layer") layerTreeLayerElement.setAttribute("expanded", "1") layerTreeLayerElement.setAttribute("checked", "Qt::Checked" if is_visible else "Qt::Unchecked") layerTreeLayerElement.setAttribute("id", layer.id()) layerTreeLayerElement.setAttribute("name", layer.name()) customPropertiesElement = doc.createElement("customproperties") layerTreeLayerElement.appendChild(customPropertiesElement) legendLayerElement = doc.createElement("legendlayer") legendLayerElement.setAttribute("drawingOrder", "-1") legendLayerElement.setAttribute("open", "true") legendLayerElement.setAttribute("checked", "Qt::Checked" if is_visible else "Qt::Unchecked") legendLayerElement.setAttribute("name", layer.name()) legendLayerElement.setAttribute("showFeatureCount", "0") filegroupElement = doc.createElement("filegroup") filegroupElement.setAttribute("open", "true") filegroupElement.setAttribute("hidden", "false") legendlayerfileElement = doc.createElement("legendlayerfile") legendlayerfileElement.setAttribute("isInOverview", "0") legendlayerfileElement.setAttribute("layerid", layer.id()) legendlayerfileElement.setAttribute("visible", "1" if is_visible else "0") filegroupElement.appendChild(legendlayerfileElement) legendLayerElement.appendChild(filegroupElement) crsElement = doc.createElement("layer_coordinate_transform") crsElement.setAttribute("destAuthId", "EPSG:3857") crsElement.setAttribute("srcAuthId", "EPSG:3857") crsElement.setAttribute("srcDatumTransform", "-1") crsElement.setAttribute("destDatumTransform", "-1") crsElement.setAttribute("layerid", layer.id()) itemElement = doc.createElement("item") text = doc.createTextNode(layer.id()) itemElement.appendChild(text) e = root.firstChildElement("layer-tree-group") e.appendChild(layerTreeLayerElement) e = root.firstChildElement("mapcanvas").firstChildElement("layer_coordinate_transform_info") e.appendChild(crsElement) e = root.firstChildElement("layer-tree-canvas").firstChildElement("custom-order") e.appendChild(itemElement) e = root.firstChildElement("legend") e.appendChild(legendLayerElement) e = root.firstChildElement("projectlayers") e.appendChild(mapLayerElement) with open(defaultProjectPath(), "wb+") as f: f.write(doc.toString(2)) settings = QSettings() settings.setValue('/qgis/newProjectDefault', True) return True