def disconnect_projectsignals(self): safe_disconnect(QgsMapLayerRegistry.instance().layerWasAdded, self.connect_layer_signals) safe_disconnect(QgsMapLayerRegistry.instance().layersRemoved, self.layers_removed) safe_disconnect(self.canvas.layersChanged, self.layers_changed) safe_disconnect(self.iface.projectRead, self.connect_signals) safe_disconnect(self.canvas.selectionChanged, self.selection_changed) safe_disconnect(self.canvas.selectionChanged, self.viewer.selection_changed)
def handle(self, **kwargs): self.logger.debug('>>> Handler: 7...') __config = load_config() params = __config[PLUGIN_CRITICIDADE] criticidade_layer = kwargs['criticidade_layer'] output_vector = kwargs['output_criticidade_vector'] try: save_file(criticidade_layer, output_vector) layers = [kwargs['criticidade_layer']] remove_layers(layers) output_layer = QgsVectorLayer(output_vector, 'criticidade', 'ogr') QgsMapLayerRegistry.instance().addMapLayers([output_layer]) style = params['style'] set_layer_style(output_layer, PLUGIN_CRITICIDADE, style['criticidade']) self.next(**kwargs) except Exception as e: raise RuntimeError(str(e))
def draw_layer(self, layer_name): displayed = layer_name in self.layers if displayed: if self.layers[layer_name].isValid(): self.layers[layer_name].setCacheImage(None) self.layers[layer_name].triggerRepaint() return # Specify the view and the column to use for the layer self.uri.setDataSource('public', 'measure_formated', layer_name) # Specify the primary key of the entries. For the record, the only unique column is measure_id self.uri.setKeyColumn('measure_id') # Create a layer based on the information previously specified (database and column). The layer is # not yet added to the UI. The layer is a Postgres type layer = QgsVectorLayer(self.uri.uri(), layer_name, 'postgres') # Check if the Layer is valid or not (in case of the column/table/... does not exist if not layer.isValid(): # print("Erreur au chargement de " + layer_name) return # Save the layer into the layer list (reminder: the layer list is useful to refresh all layers when # a notification is received) # Add the created layer to the QGIS project QgsMapLayerRegistry.instance().addMapLayer(layer) self.layers[layer_name] = layer # refresh the layer layer.setCacheImage(None) layer.triggerRepaint()
def getPoint(self, mapPoint): self.set_rad.setEnabled(True) # change tool so you don't get more than one POI self.canvas.unsetMapTool(self.emitPoint) self.canvas.setMapTool(self.userTool) # Get the click if mapPoint: self.atk_pt = QgsPoint(mapPoint) self.distance() # Specify the geometry type layer = QgsVectorLayer('Point?crs=epsg:28992', 'Attack Point', 'memory') style = "style_attack.qml" qml_path = self.plugin_dir + "/data/" + style layer.loadNamedStyle(qml_path) layer.triggerRepaint() # Set the provider to accept the data source prov = layer.dataProvider() # Add a new feature and assign the geometry feat = QgsFeature() feat.setGeometry(QgsGeometry.fromPoint(mapPoint)) prov.addFeatures([feat]) # Update extent of the layer layer.updateExtents() # Add the layer to the Layers panel QgsMapLayerRegistry.instance().addMapLayers([layer])
def deleteEvac(self): routes_layer = uf.getLegendLayerByName(self.iface, "Routes") if routes_layer: QgsMapLayerRegistry.instance().removeMapLayer(routes_layer.id()) lineLayer = uf.getLegendLayerByName(iface, "road_net") lineLayer.removeSelection() layers = ["Buildings to evacuate", "Shelters"] for layer in layers: uf.getLegendLayerByName(self.iface, layer).removeSelection() self.refreshCanvas(lineLayer) item = '' for i in range(5): # i is the table row, items must be added as QTableWidgetItems self.to_evac_info.setItem(i, 0, QtGui.QTableWidgetItem(unicode(item))) self.shelter_info.setItem(i, 0, QtGui.QTableWidgetItem(unicode(item))) self.select_POI.setEnabled(True) self.select_shelter.setEnabled(False) self.shortestRouteButton.setEnabled(False) self.warning_msg.setVisible(False) self.big_button.setEnabled(False)
def new(self, recalcular=False, layerName=None): mapCanvas = self.iface.mapCanvas() itens = [] for i in range(mapCanvas.layerCount() - 1, -1, -1): try: layer = mapCanvas.layer(i) layerName = layer.name() itens.append(layerName) except: pass if len(itens) == 0: return None if not recalcular: filename, ok = QtGui.QInputDialog.getText(None, "Nome do arquivo", u"Nome do arquivo:") if not ok: return None else: filename = '' if layerName is None: layerList = QgsMapLayerRegistry.instance().mapLayersByName( layerName) layer = None if layerList: layer = layerList[-1] else: itens = [] for i in range(mapCanvas.layerCount() - 1, -1, -1): try: layer = mapCanvas.layer(i) layerName = layer.name() itens.append(layerName) except: pass item, ok = QtGui.QInputDialog.getItem( None, "Camada com tracado", u"Selecione a camada com o traçado:", itens, 0, False) if not (ok) or not (item): return None else: layerList = QgsMapLayerRegistry.instance().mapLayersByName( item) layer = None if layerList: layer = layerList[0] dist, ok = QtGui.QInputDialog.getDouble(None, "Distancia", u"Distancia entre estacas:", 20.0, -10000, 10000, 2) if not ok or dist <= 0: return None estaca, ok = QtGui.QInputDialog.getInteger(None, "Estaca Inicial", u"Estaca Inicial:", 0, -10000, 10000, 2) if not ok: return None return filename, layer, dist, estaca
def enterShel(self): self.shortestRouteButton.setEnabled(False) routes_layer = uf.getLegendLayerByName(self.iface, "Routes") if routes_layer: QgsMapLayerRegistry.instance().removeMapLayer(routes_layer.id()) if self.shel_layer: self.shel_layer.deselect(self.shel_feat.id()) lineLayer = uf.getLegendLayerByName(iface, "road_net") lineLayer.deselect(self.shelId) self.canvas.setMapTool(self.emitShel)
def createLayer(self, mtype, directory=''): layerName = '' # 图层名称 layerType = '' # 图层类型 landus = [] # Symbol分类 if mtype == LayerType.SITE: layerName = u'基站' layerType = QGis.WKBPoint landus = SiteSymbol elif mtype == LayerType.CELL: layerName = u'小区' layerType = QGis.WKBPolygon landus = CellSymbol else: layerName = u'相邻小区' layerType = QGis.WKBLineString landus = ServingCellSymbol # 删除原有图层文件 deleteShapefile(directory, layerName) shapPath = os.path.join(directory, layerName + u".shp") fileds = self.createAttributesByType(mtype) # 创建出Shap文件 # 数据源编码模式为GBK2312(否则中文字段会乱码) wr = QgsVectorFileWriter(shapPath, "GBK2312", fileds, layerType, None, "ESRI Shapefile") # 如果保存的时候没有错误 if wr.hasError() == QgsVectorFileWriter.NoError: pass else: print wr.hasError() raise Exception, wr.errorMessage() # 发生错误,抛出异常交给外面的方法处理异常 del wr # 使添加的字段生效 layer = QgsVectorLayer(shapPath, layerName, 'ogr') # 只有当Symbol分类规则不为空时才设置 if landus != None and len(landus) > 0: myLandus = {} for i, (color, lab) in landus.items(): if i == u'移动': myLandus[i] = (self.ydcolor, lab) elif i == u'联通': myLandus[i] = (self.ltcolor, lab) elif i == u'电信': myLandus[i] = (self.dxcolor, lab) else: myLandus[i] = (self.ttcolor, lab) self.initSymbol(myLandus, layer, mtype) QgsMapLayerRegistry.instance().addMapLayer(layer)
def remove_layer(self, layer_name): """ Remove a layer from the canvas and the legend, if it exists :param layer_name: :return: """ print("removeLayer" + layer_name) for layer in QgsMapLayerRegistry.instance().mapLayers(): if layer.find(layer_name) != -1: QgsMapLayerRegistry.instance().removeMapLayer(layer) if layer_name in self.layers: del self.layers[layer_name]
def dup_layer(self, crs, names): for name in names: layer = uf.getLegendLayerByName(self.iface, "POI_Evacu8") layer_type = {'0': 'Point', '1': 'LineString', '2': 'Polygon'} mem_layer = QgsVectorLayer( layer_type[str(layer.geometryType())] + "?crs=epsg:" + str(crs), name, "memory") feats = [feat for feat in layer.getFeatures()] mem_layer_data = mem_layer.dataProvider() attr = layer.dataProvider().fields().toList() mem_layer_data.addAttributes(attr) mem_layer.updateFields() mem_layer_data.addFeatures(feats) QgsMapLayerRegistry.instance().addMapLayer(mem_layer)
def viewerReady(self): """ Called once the viewer is loaded and ready to get location events. """ self.disconnect_signals() self.connect_signals() self.iface.projectRead.connect(self.connect_signals) self.canvas.layersChanged.connect(self.layers_changed) self.canvas.selectionChanged.connect(self.selection_changed) self.canvas.selectionChanged.connect(self.viewer.selection_changed) QgsMapLayerRegistry.instance().layersRemoved.connect(self.layers_removed) QgsMapLayerRegistry.instance().layerWasAdded.connect(self.connect_layer_signals) self.center_on_canvas() self.viewer.activelayercombo.setLayer(self.iface.activeLayer())
def getLayerFromId(layerId): try: layer = QgsMapLayerRegistry.instance().mapLayers()[layerId] return layer except: warn("Could not get layer for id {}".format(layerId)) return None
def viewerReady(self): """ Called once the viewer is loaded and ready to get location events. """ self.disconnect_signals() self.connect_signals() self.iface.projectRead.connect(self.connect_signals) self.canvas.layersChanged.connect(self.layers_changed) self.canvas.selectionChanged.connect(self.selection_changed) self.canvas.selectionChanged.connect(self.viewer.selection_changed) QgsMapLayerRegistry.instance().layersRemoved.connect( self.layers_removed) QgsMapLayerRegistry.instance().layerWasAdded.connect( self.connect_layer_signals) self.center_on_canvas() self.viewer.activelayercombo.setLayer(self.iface.activeLayer())
def layer_from_name(layerName): # Important: If multiple layers with same name exist, it will return the # first one it finds for (id, layer) in QgsMapLayerRegistry.instance().mapLayers().iteritems(): if unicode(layer.name()) == layerName: return layer return None
def create_point(self, p1, name): layer = QgsVectorLayer('Point?crs=%s' % int(self.crs), name, "memory") mycrs = QgsCoordinateReferenceSystem(int(self.crs), 0) self.reprojectgeographic = QgsCoordinateTransform( self.iface.mapCanvas().mapRenderer().destinationCrs(), mycrs) pr = layer.dataProvider() point = QgsFeature() point.setGeometry( QgsGeometry.fromPoint(self.reprojectgeographic.transform(p1))) pr.addFeatures([point]) #layer.setCrs(QgsCoordinateReferenceSystem(int(self.crs), 0)) layer.updateExtents() QgsMapLayerRegistry.instance().addMapLayer(layer) return p1
def getAllLayerIds(filter_func): # FIXME Make this nicer res = [] for (id, layer) in QgsMapLayerRegistry.instance().mapLayers().iteritems(): if filter_func(layer): res.append(id) return res
def enterPoi(self): if not (QgsMapLayerRegistry.instance().mapLayersByName('Attack Point') ): # remember currently selected tool self.userTool = self.canvas.mapTool() # activate coordinate capture tool self.canvas.setMapTool(self.emitPoint)
def get_layer(layer_name): layermap = QgsMapLayerRegistry.instance().mapLayers() for name, layer in layermap.iteritems(): if layer.name() == layer_name: if layer.isValid(): return layer else: return None
def poly(self): geom = self.rubberband.asGeometry() # Set the provider to accept the data source pr = self.layer.dataProvider() # Add a new feature and assign the geometry feat = QgsFeature() feat.setGeometry(geom) pr.addFeatures([feat]) # Update extent of the layer self.layer.updateExtents() self.refreshCanvas(self.layer) # Add the layer to the Layers panel QgsMapLayerRegistry.instance().addMapLayers([self.layer])
def getLayerAttributes(layerId): try: layer = QgsMapLayerRegistry.instance().mapLayers()[layerId] fieldmap = layer.pendingFields() return fieldmap except: # OpenLayers, Raster layers don't work with this warn("Could not get attributes of layer {}".format(layerId)) return None
def exit_dialog(self, points, crs): self.dialog.close() layer = QgsVectorLayer('LineString', self.name_tracado, "memory") pr = layer.dataProvider() print points anterior = QgsPoint(points[0]) fets = [] for p in points[1:]: fet = QgsFeature(layer.pendingFields()) fet.setGeometry(QgsGeometry.fromPolyline([anterior, QgsPoint(p)])) fets.append(fet) anterior = QgsPoint(p) pr.addFeatures(fets) self.crs = crs layer.setCrs(QgsCoordinateReferenceSystem(int(crs), 0)) layer.updateExtents() QgsMapLayerRegistry.instance().addMapLayer(layer)
def setup_gui(self): """ Function to combos creation """ self.shapeButton.clicked.connect(self.writeTxt) self.rasterCombo.clear() layers = QgsMapLayerRegistry.instance().mapLayers().values() layerRasters = [] layerVectors = [] for layer in layers: if layer.type() == QgsMapLayer.RasterLayer: self.rasterCombo.addItem(layer.name(), layer)
def getLayerAttributes(layerId): try: layer=QgsMapLayerRegistry.instance().mapLayers()[layerId] fieldmap = layer.pendingFields() #TODO v1.7 figure out what to do for fields with fieldmap.fieldOrigin(idx) = QgsFields.OriginEdit/OriginExpression return fieldmap except: # OpenLayers, Raster layers don't work with this warn("Could not get attributes of layer {}".format(layerId)) return None
def getLayerAttributes(layerId): try: layer = QgsMapLayerRegistry.instance().mapLayers()[layerId] fieldmap = layer.pendingFields() #TODO v1.7 figure out what to do for fields with fieldmap.fieldOrigin(idx) = QgsFields.OriginEdit/OriginExpression return fieldmap except: # OpenLayers, Raster layers don't work with this warn("Could not get attributes of layer {}".format(layerId)) return None
def get_layer(self, layer_name): if self.layer.name() != layer_name: self.ini_dialog() layermap = QgsMapLayerRegistry.instance().mapLayers() for name, layer in layermap.iteritems(): if layer.name() == layer_name: if layer.isValid(): self.layer = layer self.get_raster_properties() else: self.layer = None
def populate(self, comboBox, isMaster, idx=0, update=True): idlayers = list(QgsMapLayerRegistry.instance().mapLayers().iteritems()) self.populateFromLayers(comboBox, idlayers, isMaster) if not idlayers: return if not update: return if isMaster: self.masterUpdated(idx) else: self.slaveUpdated(idx)
def setResultLayer(self, result_list): layerName = u'规划基站结果' layerType = QGis.WKBPoint project_dir = getProjectDir(self.iface) # 先判断是否已存在规划基站结果图层 result_layer = getLayerByName(layerName, self.iface) if result_layer: #清空数据 delAllFeatures(result_layer) else: # 删除原有图层文件 deleteShapefile(project_dir, layerName) shapPath = os.path.join(project_dir, layerName + u".shp") # 生成图层 fileds = self.createFields() # 创建出Shap文件 # 数据源编码模式为GBK2312(否则中文字段会乱码) wr = QgsVectorFileWriter(shapPath, "GBK2312", fileds, layerType, None, "ESRI Shapefile") # 如果保存的时候没有错误 if wr.hasError() == QgsVectorFileWriter.NoError: pass else: print wr.hasError() raise Exception, wr.errorMessage() # 发生错误,抛出异常交给外面的方法处理异常 del wr # 使添加的字段生效 result_layer = QgsVectorLayer(shapPath, layerName, 'ogr') QgsMapLayerRegistry.instance().addMapLayer(result_layer) # 添加数据 features_list = [] for result in result_list: feature = createABasicPointFeature(QgsPoint(float(result[1]),float(result[2])), result) features_list.append(feature) importFeaturesToLayer(result_layer, features_list) # 合并站点 mergeNSite = OptimizateNewSite(result_layer, self.parent) if mergeNSite.run(): QMessageBox.information(self.parent, u"自动规划基站", u"自动规划基站成功!") else: QMessageBox.critical(self.parent, u"自动规划基站", u"自动规划基站失败!")
def getLayerAttributes(layerId): try: layer = QgsMapLayerRegistry.instance().mapLayers()[layerId] #QgsMessageLog.logMessage(str(QgsMapLayerRegistry.instance().mapLayers())) #QgsMessageLog.logMessage("layer"+str(layer)) provider = layer.dataProvider() # this will crash on OpenLayers layers fieldmap = provider.fields( ) # this function will crash on raster layers return fieldmap except: QgsMessageLog.logMessage( "Could not get attributes of layer {}".format(layerId)) return None
def plotar(self): vl = QgsVectorLayer("Point", "temporary_points", "memory") pr = vl.dataProvider() # Enter editing mode vl.startEditing() # add fields pr.addAttributes([ QgsField("estaca", QVariant.String), QgsField("descrição", QVariant.String), QgsField("north", QVariant.String), QgsField("este", QVariant.String), QgsField("cota", QVariant.String), QgsField("azimite", QVariant.String) ]) fets = [] for r in range(self.tableWidget.rowCount()): ident = self.tableWidget.item(r, 0).text() if ident in ["", None]: break fet = QgsFeature(vl.pendingFields()) n = 0.0 e = 0.0 try: es = self.tableWidget.item(r, 0).text() d = self.tableWidget.item(r, 1).text() n = float(self.tableWidget.item(r, 3).text()) e = float(self.tableWidget.item(r, 4).text()) c = float(self.tableWidget.item(r, 5).text()) a = self.tableWidget.item(r, 6).text() except: break fet.setGeometry(QgsGeometry.fromPoint(QgsPoint(e, n))) fet.setAttributes([es, d, n, e, c, a]) fets.append(fet) pr.addFeatures(fets) vl.commitChanges() QgsMapLayerRegistry.instance().addMapLayer(vl)
def loadCsvFiles(self): # 清除画布上的所有图层 # QgsMapLayerRegistry.instance().removeAllMapLayers() # 图标样式,圆,大小设为1 # symbol = QgsMarkerSymbolV2.createSimple({'name':'circle', 'size':'1'}) filepath = self.dlg.lineEdit.text() # 获取文件夹中的所有文件,并过滤不是csv格式的文件 files = os.listdir(filepath) for file in files: if not os.path.isdir(file) and os.path.splitext( file)[1] == '.csv' and not file.startswith('.'): uri = "file:///" + filepath + "/" + file + "?delimiter=%s&crs=epsg:4326&xField=%s&yField=%s" % ( ",", "longitude", "latitude") vlayer = QgsVectorLayer(uri, os.path.splitext(file)[0], "delimitedtext") vlayer.rendererV2().symbol().setSize(1.3) if vlayer.isValid(): QgsMapLayerRegistry.instance().addMapLayer(vlayer)
def createNodeLayer(self): project_dir = getProjectDir(self.iface, u"基站") if not project_dir: QMessageBox.critical(self, u"错误", u"基站图层不存在!") return False else: project = QgsProject.instance() VoronoiName = u"泰森多边形" NodesName = u"泰森结点" # 若已存在泰森多边形和泰森结点图层,则先移除图层再删除shape文件 voronoi_layer = getLayerByName(VoronoiName, self.iface) if voronoi_layer: QgsMapLayerRegistry.instance().removeMapLayer(voronoi_layer) else: deleteShapefile(project_dir, VoronoiName) nodes_layer = getLayerByName(NodesName, self.iface) if nodes_layer: QgsMapLayerRegistry.instance().removeMapLayer(nodes_layer) else: deleteShapefile(project_dir, NodesName) if (voronoi_layer) or (nodes_layer): project.write() QMessageBox.critical(self, u"错误", u"相应文件已被占用,请重启QGIS软件!") return False site_layer = getLayerByName(u'基站', self.iface) # 生成泰森多边形 VoronoiFile = os.path.join(project_dir, VoronoiName + u".shp") Vor = processing.runalg("qgis:voronoipolygons", site_layer, 0, VoronoiFile) Voronoi = processing.load(Vor['OUTPUT'], VoronoiName) # 生成泰森结点 NodesFile = os.path.join(project_dir, NodesName + u".shp") Nod = processing.runalg("qgis:extractnodes", Voronoi, NodesFile) Nodes = processing.load(Nod['OUTPUT'], NodesName) return Nodes
def getAllJoinedLayers(layerIds): """get the ids of the layers that are joined on the given layerIds""" allJoined = set() allLayers = QgsMapLayerRegistry.instance().mapLayers() for (id, layer) in allLayers.iteritems(): if isRaster(layer): continue if id in layerIds: # let's see what the given layers are joined on allJoined |= getAllJoinIdsOfLayer(layer) else: # let's see if the other layers join with the given layers joinsOfCurrentLayer = getAllJoinIdsOfLayer(layer) if len(joinsOfCurrentLayer & layerIds) > 0: allJoined.add(id) return allJoined
def populate(self, layerIds): self.tempLayerIndexToId = {} i = 0 for (id,layer) in QgsMapLayerRegistry.instance().mapLayers().iteritems(): if id in layerIds: unicode_name = unicode(layer.name()) self.add_layer_to_select(unicode_name) self.tempLayerIndexToId[i] = id i+=1 if self.layer_count()== 0: msg = 'There are no unmanaged layers of requested type in the project!' QMessageBox.information(self.dialog,'Error', msg) raise Exception(msg) # add the attributes of the first layer in the select for gui initialization self.add_layer_attributes(0) self.add_connections()
def populate(self, layerIds): idlayers_it = QgsMapLayerRegistry.instance().mapLayers().iteritems() selected_idlayers = filter(lambda idlayer: idlayer[0] in layerIds, idlayers_it) self.populateFromLayers(selected_idlayers)
def layer_count(): return len(QgsMapLayerRegistry.instance().mapLayers())
def get_all_layer_names(): return QgsMapLayerRegistry.instance().mapLayers().keys()
def maplayers(): return QgsMapLayerRegistry.instance().mapLayers().values()
def layer_by_name(name): return QgsMapLayerRegistry.instance().mapLayersByName(name)[0]
def layer_by_id(layerid): return QgsMapLayerRegistry.instance().mapLayer(layerid)
def load_layer_to_qgis(layer): QgsMapLayerRegistry.instance().addMapLayer(layer) sleep(0.2)
def remove_layer_from_qgis(id): QgsMapLayerRegistry.instance().removeMapLayer(id) sleep(0.1)
def getNameFromLayerId(layerId): layer = QgsMapLayerRegistry.instance().mapLayers()[layerId] return unicode(layer.name())