def accept(self): """Handler for when OK is clicked. """ input_path = self.input_path.text() input_title = self.line_edit_title.text() input_source = self.line_edit_source.text() output_path = self.output_path.text() if not output_path.endswith('.tif'): # noinspection PyArgumentList,PyCallByClass,PyTypeChecker QMessageBox.warning( self, self.tr('InaSAFE'), (self.tr('Output file name must be tif file'))) if not os.path.exists(input_path): # noinspection PyArgumentList,PyCallByClass,PyTypeChecker QMessageBox.warning( self, self.tr('InaSAFE'), (self.tr('Input file does not exist'))) return if self.nearest_mode.isChecked(): algorithm = 'nearest' else: algorithm = 'invdist' QtGui.qApp.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor)) file_name = convert_mmi_data( input_path, input_title, input_source, output_path, algorithm=algorithm, algorithm_filename_flag=True) QtGui.qApp.restoreOverrideCursor() if self.load_result.isChecked(): file_info = QFileInfo(file_name) base_name = file_info.baseName() layer = QgsRasterLayer(file_name, base_name) # noinspection PyTypeChecker mmi_ramp(layer) layer.saveDefaultStyle() if not layer.isValid(): LOGGER.debug("Failed to load") else: # noinspection PyArgumentList QgsMapLayerRegistry.instance().addMapLayers([layer]) iface.zoomToActiveLayer() self.done(self.Accepted)
def showNewImage(self, image): """ Will order this UI to post a new image to the user through the qgis window. :param image: a tuple consisting of (imageOrLayerObject, Name, Service) :type image: (QgsRasterLayer, String, String) """ self.postInformationMessageToUser("Layer '"+image[1]+"' ["+image[2]+"]retrieved") layer = image[0] if layer.isValid() is True: QgsMapLayerRegistry.instance().addMapLayer(layer) iface.zoomToActiveLayer() iface.legendInterface().refreshLayerSymbology(layer) else: self.postInformationMessageToUser("There was a problem loading the layer.")
def showNewImage(self, image): """ Will order this UI to post a new image to the user through the qgis window. :param image: a tuple consisting of (imageOrLayerObject, Name, Service) :type image: (QgsRasterLayer, String, String) """ self.postInformationMessageToUser("Layer '" + image[1] + "' [" + image[2] + "]retrieved") layer = image[0] if layer and layer.isValid(): QgsMapLayerRegistry.instance().addMapLayer(layer) iface.zoomToActiveLayer() iface.legendInterface().refreshLayerSymbology(layer) else: self.postInformationMessageToUser( "There was a problem loading the layer.")
def job_display(self, job_id): """ Displays the job of the given row of the job table on a new QGis Layer. This method is called after the "Display" button is clicked at the job table. :param job_id: Integer number of the job id the button is clicked. """ job = self.backend.get_job(job_id) process_graph_job = self.backend.job_pg_info(job_id) download_dir = self.backend.job_result_download(job_id) failed_files = [] if download_dir: for ddir in download_dir: info(self.iface, "Downloaded to {}".format(ddir)) result = Result(path=ddir, process_graph=process_graph_job) if iface.activeLayer(): crs_background = iface.activeLayer().crs().authid() QSettings().setValue('/Projections/defaultBehaviour', 'useGlobal') QSettings().setValue('/Projections/layerDefaultCrs', crs_background) else: QSettings().setValue('/Projections/defaultBehaviour', 'useGlobal') QSettings().setValue('/Projections/layerDefaultCrs', 'EPSG:4326') if job.title: title = job.title else: title = "NoTitle" if not result.display(layer_name="{}-{}".format(title, job.created.strftime("%Y-%m-%d_%H-%M-%S"))): failed_files.append(ddir) iface.zoomToActiveLayer() if failed_files: warning(self.iface, "The following result files could not be loaded to layer: {}" .format(str(failed_files).replace("[", "").replace("]", ""))) self.refresh_jobs()
def accept(self): """Handler for when OK is clicked.""" input_path = self.input_path.text() input_title = self.line_edit_title.text() input_source = self.line_edit_source.text() output_path = self.output_path.text() if not output_path.endswith('.tif'): # noinspection PyArgumentList,PyCallByClass,PyTypeChecker QMessageBox.warning( self, self.tr('InaSAFE'), (self.tr('Output file name must be tif file'))) if not os.path.exists(input_path): # noinspection PyArgumentList,PyCallByClass,PyTypeChecker QMessageBox.warning( self, self.tr('InaSAFE'), (self.tr('Input file does not exist'))) return if self.nearest_mode.isChecked(): algorithm = 'nearest' else: algorithm = 'invdist' QtGui.qApp.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor)) file_name = convert_mmi_data( input_path, input_title, input_source, output_path, algorithm=algorithm, algorithm_filename_flag=True) # reclassify raster file_info = QFileInfo(file_name) base_name = file_info.baseName() self.output_layer = QgsRasterLayer(file_name, base_name) self.output_layer.keywords = KeywordIO.read_keywords(self.output_layer) self.output_layer.keywords['classification'] = ( earthquake_mmi_scale['key']) keywords = self.output_layer.keywords if self.output_layer.isValid(): self.output_layer = reclassify( self.output_layer, overwrite_input=True) KeywordIO.write_keywords(self.output_layer, keywords) else: LOGGER.debug("Failed to load") QtGui.qApp.restoreOverrideCursor() if self.load_result.isChecked(): # noinspection PyTypeChecker mmi_ramp_roman(self.output_layer) self.output_layer.saveDefaultStyle() if not self.output_layer.isValid(): LOGGER.debug("Failed to load") else: # noinspection PyArgumentList QgsMapLayerRegistry.instance().addMapLayer(self.output_layer) iface.zoomToActiveLayer() if (self.keyword_wizard_checkbox.isChecked() and self.keyword_wizard_checkbox.isEnabled()): self.launch_keyword_wizard() self.done(self.Accepted)
def onLoad(self): """Load LOG file as a new QGIS point map layer. Input LOG file is given by user via open dialog. Loaded point layer is symbolized using default internal style. Layer is inserted into layer tree (TOC) on first position. Shows error dialog on failure. """ # get last used directory path from settings sender = '{}-lastUserFilePath'.format(self.sender().objectName()) lastPath = self._settings.value(sender, '') filePath = QFileDialog.getOpenFileName( self, self.tr("Load Safecast LOG file"), lastPath, self.tr("LOG file (*.LOG)")) if not filePath: # action canceled return filePath = os.path.normpath(filePath) try: # create reader for input data reader = SafecastReader(filePath) # create new QGIS map layer (read-only) layer = SafecastLayer(filePath) # load data by reader into new layer and set style layer.load(reader) layer.loadNamedStyle(self.stylePath()) # add map layer to the canvas (do not add into TOC) QgsMapLayerRegistry.instance().addMapLayer(layer, False) # force register layer in TOC as a first item QgsProject.instance().layerTreeRoot().insertLayer(0, layer) # select this layer (this must be done manually since we # are inserting item into layer tree) iface.legendInterface().setCurrentLayer(layer) # collapse layer iface.legendInterface().setLayerExpanded(layer, False) # register new layer in plugin's internal list self._layers.append(layer) except (SafecastError, SafecastReaderError) as e: # show error message on failure iface.messageBar().clearWidgets() QMessageBox.critical( None, self.tr("Error"), self.tr( "Failed to load input file '{0}'.\n\nDetails: {1}").format( filePath, e), QMessageBox.Abort) return # enable save, select, style buttons when new layer is # successfully loaded if not self.actionSave.isEnabled(): self.actionSave.setEnabled(True) self.actionSelect.setEnabled(True) self.styleButton.setEnabled(True) # zoom to the new layer (already selected) iface.zoomToActiveLayer() # remember directory path self._settings.setValue(sender, os.path.dirname(filePath))
def accept(self): """Handler for when OK is clicked.""" input_path = self.input_path.text() input_title = self.line_edit_title.text() input_source = self.line_edit_source.text() output_path = self.output_path.text() if not output_path.endswith('.tif'): # noinspection PyArgumentList,PyCallByClass,PyTypeChecker QMessageBox.warning(self, tr('InaSAFE'), tr('Output file name must be tif file')) if not os.path.exists(input_path): # noinspection PyArgumentList,PyCallByClass,PyTypeChecker QMessageBox.warning(self, tr('InaSAFE'), tr('Input file does not exist')) return algorithm = 'nearest' if self.nearest_mode.isChecked(): algorithm = 'nearest' elif self.inverse_distance_mode.isChecked(): algorithm = 'invdist' elif self.use_ascii_mode.isChecked(): algorithm = 'use_ascii' # Smoothing smoothing_method = NONE_SMOOTHING if self.numpy_smoothing.isChecked(): smoothing_method = NUMPY_SMOOTHING if self.scipy_smoothing.isChecked(): smoothing_method = SCIPY_SMOOTHING # noinspection PyUnresolvedReferences QgsApplication.instance().setOverrideCursor( QtGui.QCursor(QtCore.Qt.WaitCursor)) extra_keywords = {} if self.check_box_custom_shakemap_id.isChecked(): event_id = self.line_edit_shakemap_id.text() extra_keywords[extra_keyword_earthquake_event_id['key']] = event_id current_index = self.combo_box_source_type.currentIndex() source_type = self.combo_box_source_type.itemData(current_index) if source_type: extra_keywords[ extra_keyword_earthquake_source['key']] = source_type file_name = convert_mmi_data(input_path, input_title, input_source, output_path, algorithm=algorithm, algorithm_filename_flag=True, smoothing_method=smoothing_method, extra_keywords=extra_keywords) file_info = QFileInfo(file_name) base_name = file_info.baseName() self.output_layer = QgsRasterLayer(file_name, base_name) # noinspection PyUnresolvedReferences QgsApplication.instance().restoreOverrideCursor() if self.load_result.isChecked(): # noinspection PyTypeChecker mmi_ramp_roman(self.output_layer) self.output_layer.saveDefaultStyle() if not self.output_layer.isValid(): LOGGER.debug("Failed to load") else: # noinspection PyArgumentList QgsProject.instance().addMapLayer(self.output_layer) iface.zoomToActiveLayer() if (self.keyword_wizard_checkbox.isChecked() and self.keyword_wizard_checkbox.isEnabled()): self.launch_keyword_wizard() self.done(self.Accepted)
Processing.initialize() # открытие проекта с уже загруженным слоем со спутниковой подложкой Microsoft Bing project = QgsProject.instance() project.read('/home/zav/mbtiles/main.qgz') # путь к уже сгенерированному шейп-файлу path_to_shapefile = '/home/zav/mbtiles/block.shp' # добавление шейп-файла в проект block_layer = QgsVectorLayer(path_to_shapefile, "Block layer", "ogr") project.addMapLayer(block_layer) iface.setActiveLayer(block_layer) # приближение к требуемой области (Zoom in to the selected area) iface.zoomToActiveLayer() # определение угловых точек области e = iface.mapCanvas().extent() x_min = e.xMinimum() x_max = e.xMaximum() y_min = e.yMinimum() y_max = e.yMaximum() extent = str(x_min) + ',' + str(x_max) + ',' + str(y_min) + ',' + str( y_max) + ' ' + '[EPSG:4326]' # запуск генерации файла result = processing.run( "qgis:tilesxyzmbtiles", { 'EXTENT': extent, 'ZOOM_MIN': 1,
def onLoad(self): """Load LOG file as a new QGIS point map layer. Input LOG file is given by user via open dialog. Loaded point layer is symbolized using default internal style. Layer is inserted into layer tree (TOC) on first position. Shows error dialog on failure. """ # get last used directory/extension path from settings senderPath = '{}-lastUserFilePath'.format(self.sender().objectName()) lastPath = self._settings.value(senderPath, os.path.expanduser("~")) senderExt, lastExt = self._lastUsedFileExt(getSender=True) fileMask = "{u} files (*.{u} *.{l}".format(u=lastExt.upper(), l=lastExt) if lastExt == 'pei': fileMask += ' *.P46' fileMask += ')' for ext in self._supported_ext: if ext in fileMask: # already defined as default, skip continue extra = ' *.P46' if ext == 'pei' else '' fileMask += ";;{u} files (*.{u} *.{l} {extra})".format( u=ext.upper(), l=ext, extra=extra) filePath, __ = QtWidgets.QFileDialog.getOpenFileName( self, self.tr("Load radiation data file").format(lastExt.upper()), lastPath, self.tr(fileMask)) if not filePath: # action canceled return # storage format storage_idx = self.storageCombo.currentIndex() if storage_idx == 0: storageFormat = 'SQLite' elif storage_idx == 1: storageFormat = 'GPKG' else: storageFormat = 'memory' filePath = os.path.normpath(filePath) fileExt = os.path.splitext(filePath)[1][1:].lower() # remove '.' helper = None if fileExt == 'log': from .reader.safecast import SafecastReader from .layer.safecast import SafecastLayer, SafecastLayerHelper # create reader for input data reader = SafecastReader(filePath) # create new QGIS map layer (read-only) layer = SafecastLayer(filePath, storageFormat) # register new layer in plugin's internal list # helper must be assigned before loading data (!) self._layers[layer.id()] = helper = SafecastLayerHelper(layer) elif fileExt == 'ers': from .reader.ers import ERSReader from .layer.ers import ERSLayer # create reader for input data reader = ERSReader(filePath) # create new QGIS map layer (read-only) layer = ERSLayer(filePath, storageFormat) elif fileExt in ('pei', 'p46'): from .reader.pei import PEIReader from .layer.pei import PEILayer # create reader for input data reader = PEIReader(filePath) # create new QGIS map layer (read-only) layer = PEILayer(filePath, storageFormat) fileExt = 'pei' # do not store p46 in settings else: iface.messageBar().pushMessage( self.tr("Critical"), self.tr("Unsupported file extension {}").format(fileExt), level=Qgis.Critical, duration=10) return try: # load data by reader into new layer layer.load(reader) if helper: helper.recalculateAttributes() # set style # must be called after each loading since file extension can change self._initStyles(layer) layer.setStyle(self.styleBox.currentIndex()) layer.setAliases() # loadNameStyle removes aliases (why?) except (RadiationToolboxError, LoadError, StyleError) as e: # show error message on failure iface.messageBar().clearWidgets() iface.messageBar().pushMessage( self.tr("Critical"), self.tr( "Failed to load input file '{0}'.\n\nDetails: {1}").format( filePath, e), level=Qgis.Critical, duration=10) return # add map layer to tree view self._addMapLayer(layer) # zoom to the new layer (already selected) iface.zoomToActiveLayer() # remember directory path / file extension self._settings.setValue(senderPath, os.path.dirname(filePath)) self._settings.setValue(senderExt, fileExt)
def accept(self): """Handler for when OK is clicked.""" input_path = self.input_path.text() input_title = self.line_edit_title.text() input_source = self.line_edit_source.text() output_path = self.output_path.text() if not output_path.endswith('.tif'): # noinspection PyArgumentList,PyCallByClass,PyTypeChecker QMessageBox.warning( self, tr('InaSAFE'), tr('Output file name must be tif file')) if not os.path.exists(input_path): # noinspection PyArgumentList,PyCallByClass,PyTypeChecker QMessageBox.warning( self, tr('InaSAFE'), tr('Input file does not exist')) return algorithm = 'nearest' if self.nearest_mode.isChecked(): algorithm = 'nearest' elif self.inverse_distance_mode.isChecked(): algorithm = 'invdist' elif self.use_ascii_mode.isChecked(): algorithm = 'use_ascii' # Smoothing smoothing_method = NONE_SMOOTHING if self.numpy_smoothing.isChecked(): smoothing_method = NUMPY_SMOOTHING if self.scipy_smoothing.isChecked(): smoothing_method = SCIPY_SMOOTHING # noinspection PyUnresolvedReferences QgsApplication.instance().setOverrideCursor( QtGui.QCursor(QtCore.Qt.WaitCursor) ) extra_keywords = {} if self.check_box_custom_shakemap_id.isChecked(): event_id = self.line_edit_shakemap_id.text() extra_keywords[extra_keyword_earthquake_event_id['key']] = event_id current_index = self.combo_box_source_type.currentIndex() source_type = self.combo_box_source_type.itemData(current_index) if source_type: extra_keywords[ extra_keyword_earthquake_source['key']] = source_type file_name = convert_mmi_data( input_path, input_title, input_source, output_path, algorithm=algorithm, algorithm_filename_flag=True, smoothing_method=smoothing_method, extra_keywords=extra_keywords ) file_info = QFileInfo(file_name) base_name = file_info.baseName() self.output_layer = QgsRasterLayer(file_name, base_name) # noinspection PyUnresolvedReferences QgsApplication.instance().restoreOverrideCursor() if self.load_result.isChecked(): # noinspection PyTypeChecker mmi_ramp_roman(self.output_layer) self.output_layer.saveDefaultStyle() if not self.output_layer.isValid(): LOGGER.debug("Failed to load") else: # noinspection PyArgumentList QgsProject.instance().addMapLayer(self.output_layer) iface.zoomToActiveLayer() if (self.keyword_wizard_checkbox.isChecked() and self.keyword_wizard_checkbox.isEnabled()): self.launch_keyword_wizard() self.done(self.Accepted)
def zoomToLayer(self, layer): #Zooma sul layer in input attivandolo iface.setActiveLayer(layer) iface.zoomToActiveLayer()
def import_layer_from_csv(parent, csv_path, layer_name, iface, longitude_field='lon', latitude_field='lat', delimiter=',', quote='"', lines_to_skip_count=0, wkt_field=None, save_format=None, save_dest=None, zoom_to_layer=True, has_geom=True, subset=None, add_to_legend=True, add_on_top=False): if not lines_to_skip_count: lines_to_skip_count = count_heading_commented_lines(csv_path) url = QUrl.fromLocalFile(csv_path) url_query = QUrlQuery() url_query.addQueryItem('type', 'csv') if has_geom: if wkt_field is not None: url_query.addQueryItem('wktField', wkt_field) else: url_query.addQueryItem('xField', longitude_field) url_query.addQueryItem('yField', latitude_field) url_query.addQueryItem('spatialIndex', 'no') url_query.addQueryItem('crs', 'epsg:4326') url_query.addQueryItem('subsetIndex', 'no') url_query.addQueryItem('watchFile', 'no') url_query.addQueryItem('delimiter', delimiter) url_query.addQueryItem('quote', quote) url_query.addQueryItem('skipLines', str(lines_to_skip_count)) url_query.addQueryItem('trimFields', 'yes') if subset is not None: # NOTE: it loads all features and applies a filter in visualization url_query.addQueryItem('subset', subset) # i.e. '"fieldname" != 0' url.setQuery(url_query) layer_uri = url.toString() layer = QgsVectorLayer(layer_uri, layer_name, "delimitedtext") if save_format: if save_format == 'ESRI Shapefile': fmt = '.shp' fmt_text = 'Shapefiles (*.shp)' elif save_format == 'GPKG': fmt = '.gpkg' fmt_text = 'Geopackages (*.gpkg)' else: raise NotImplementedError( 'Only shapefiles and geopackages are supported. Got %s' % save_format) dest_filename = save_dest if not dest_filename: dest_filename, file_filter = QFileDialog.getSaveFileName( parent, 'Save as...', os.path.expanduser("~"), fmt_text) if dest_filename: if os.path.splitext(dest_filename)[1] != fmt: dest_filename += fmt else: return writer_error, error_msg = save_layer_as( layer, dest_filename, save_format) if writer_error: raise RuntimeError( 'Could not save layer. %s: %s' % (writer_error, error_msg)) layer = QgsVectorLayer(dest_filename, layer_name, 'ogr') if layer.isValid(): if add_to_legend: if add_on_top: root = QgsProject.instance().layerTreeRoot() QgsProject.instance().addMapLayer(layer, False) root.insertLayer(0, layer) else: QgsProject.instance().addMapLayer(layer, True) iface.setActiveLayer(layer) if zoom_to_layer: iface.zoomToActiveLayer() else: raise RuntimeError('Unable to load layer') return layer