def prepareExportPoint(self, pointLayer, polygon, contour): ringq = 0 csvdata = u'' for ring in polygon: for pt in ring: for pointfeature in pointLayer.getFeatures(): if pointfeature.geometry().equals(QgsGeometry.fromPoint(QgsPoint(pt.x(), pt.y()))): fullname = unicode(pointfeature.attribute(u'name')) if fullname[0] == u'н': name = fullname[1:]+u';' prefix = u'Н;' else: name = fullname + u';' prefix = u';' x = round(QgsGeometry.fromPoint(pt).asPoint().y(), 2) sx = unicode('{:.2f}'.format(x))+u';' y = round(QgsGeometry.fromPoint(pt).asPoint().x(), 2) sy = unicode('{:.2f}'.format(y))+u';' pref = unicode(pointfeature.attribute(u'prec'))+u';' hold = unicode(pointfeature.attribute(u'hold')) if ringq > 0: cnt = u'['+unicode(str(contour))+u'.'+unicode(str(ringq))+u'];' else: cnt = u'['+unicode(str(contour))+u'];' csvdata += cnt+prefix+name+u';;'+sx+sy+u';;;'+pref+hold+u'\n' if len(polygon) >= ringq+2: csvdata +=u';;;;;;;;;;;\n' ringq += 1 return csvdata
def createMemLayer(line, breaksList): ''' create memory layer storing all reaches :return: ''' # create layer vl = QgsVectorLayer("LineString", "sinuosity_river", "memory") pr = vl.dataProvider() # add fields pr.addAttributes([ QgsField("reach", QVariant.Int), QgsField("sinuosity", QVariant.Double), QgsField("Length", QVariant.Double) ]) vl.updateFields() # create breaks with initial and final bk = sorted(breaksList) bk.insert(0, 0) bk.append(line.length()) for breack in range(1, len(bk)): ptInt = line.interpolate(bk[breack - 1]) ptFin = line.interpolate(bk[breack]) reach = splitLine(line, ptInt, ptFin) # sinuosity calc dist = qgisdist(ptInt, ptFin) lenReach = bk[breack] - bk[breack - 1] # add a feature fet = QgsFeature() fet.setGeometry(QgsGeometry.fromPolylineXY(reach)) fet.setAttributes([breack, lenReach / dist, str(lenReach)]) pr.addFeatures([fet]) #vl.updateExtents() vl.commitChanges() return vl
def has_errors(self): if self.geom is None: geom = self.band.asGeometry() else: geom = self.geom errors = geom.validateGeometry() skippable = ["duplicate node", "Geometry has"] othererrors = [] def is_safe(message): for safe in skippable: if safe in message: return True return False # We need to remove errors that are "ok" and not really that bad # We are harder on what is considered valid for polygons. if self.is_polygon_mode: for error in errors: if not is_safe(error.what()): othererrors.append(error) if self.node_count < self.minpoints: error = QgsGeometry.Error("Number of nodes < {0}".format( self.minpoints)) othererrors.append(error) return othererrors
def paint_extent(self, rec): self.roi_x_max = rec.xMaximum() self.ui.XMaxLineEdit.setText(str(round(rec.xMaximum(), 3))) self.roi_y_min = rec.yMinimum() self.ui.YMinLineEdit.setText(str(round(rec.yMinimum(), 3))) self.roi_x_min = rec.xMinimum() self.ui.XMinLineEdit.setText(str(round(rec.xMinimum(), 3))) self.roi_y_max = rec.yMaximum() self.ui.YMaxLineEdit.setText(str(round(rec.yMaximum(), 3))) if self.extent: self.canvas.scene().removeItem(self.extent) self.extent = None self.extent = QgsRubberBand(self.canvas, True) points = [ QgsPoint(self.roi_x_max, self.roi_y_min), QgsPoint(self.roi_x_max, self.roi_y_max), QgsPoint(self.roi_x_min, self.roi_y_max), QgsPoint(self.roi_x_min, self.roi_y_min), QgsPoint(self.roi_x_max, self.roi_y_min) ] self.extent.setToGeometry(QgsGeometry.fromPolyline(points), None) self.extent.setColor(QColor(227, 26, 28, 255)) self.extent.setWidth(5) self.extent.setLineStyle(Qt.PenStyle(Qt.DashLine)) self.canvas.refresh()
def get_points(self, pipeline): pipe = [ QgsPointXY(pipeline.vertexAt(i)) for i in range(pipeline.get().childCount()) ] distances = [] breakForce = 0 while True: if breakForce == 1000: break # check isCanceled() to handle cancellation if self.isCanceled(): return False increment = 0 pipeline = QgsGeometry.fromMultiPointXY(pipe) for i in range(len(pipe) - 1): p1 = pipeline.vertexAt(i) p2 = pipeline.vertexAt(i + 1) d = QgsDistanceArea() distance = d.measureLine(QgsPointXY(p1), QgsPointXY(p2)) distances.append(distance) if distance > 10: self.split_line(p1, p2, i + 1 + increment, pipe) increment += 1 breakForce += 1 if distances: if max(distances) <= 10: break distances.clear() return pipeline
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 init_state(self): dirname = os.path.dirname(__file__) layer = QgsProject.instance().mapLayersByName('copy_energy_plant')[0] if layer.featureCount() < NUMB_ENERGY_PLANT: filename = os.path.join(dirname, 'dataset/global_power_plant_database.csv') layer.startEditing() with open(filename, 'r') as file: reader = csv.reader(file) for i, row in enumerate(reader): if i > 0 and row[7] == "Nuclear": pr = layer.dataProvider() # insert in attribute table poly = QgsFeature(layer.fields()) poly.setAttribute("Country", row[0]) poly.setAttribute("count_long", row[1]) poly.setAttribute("name", row[2]) poly.setAttribute("qppd_idnr", row[3]) poly.setAttribute("cap_mw", row[4]) poly.setAttribute("latitude", row[5]) poly.setAttribute("longitude", row[6]) poly.setAttribute("Radiation", random.randint(1, 200)) poly.setGeometry( QgsGeometry.fromPointXY( QgsPointXY(float(row[6]), float(row[5])))) pr.addFeatures([poly]) layer.updateExtents() layer.commitChanges() layer.reload()
def addPlaceMark(self, pos, name, description, category, timestamp): ''' adds a point to the layer :param pos: lat/lon position of the placemark :type pos: QgsPoint :param name: name of the placemark :type name: string :param description: extended text for the placemark :type description: string :param category: category to define the :type category: string :param timestamp: creation time of the placemark :type timestamp: string ''' if self.hasLayer: feat = QgsFeature(self.layer.pendingFields()) feat.setAttribute('name', name) feat.setAttribute('description', description) feat.setAttribute('class', category) feat.setAttribute('timestamp', timestamp) feat.setGeometry(QgsGeometry.fromPoint(pos)) (res, _) = self.layer.dataProvider().addFeatures([feat]) if res: self.layer.updateExtents() return res return False
def createABasicPointFeature(point, attrs): feature = QgsFeature() feature.initAttributes(len(attrs)) for (index, attr) in enumerate(attrs): feature.setAttribute(index, attr) geom = QgsGeometry.fromPoint(point) feature.setGeometry(geom) return feature
def doCatalogMapPlan(self): pointLayer = self.getLayerByName(u'Точки') file_name = QFileDialog.getSaveFileName(None, u'Сохраните ведомость координат для карта(план)', self.lastDir, u'HTML файлы(*.html *.HTML)') if not file_name == u'': htmldata_start = u'<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns:m="http://schemas.microsoft.com/office/2004/12/omml" xmlns="http://www.w3.org/TR/REC-html40"><head><meta http-equiv=Content-Type content="text/html; charset=windows-1251"><meta name=ProgId content=Word.Document><meta name=Generator content="Microsoft Word 15"><meta name=Originator content="Microsoft Word 15"></head><body lang=RU link=blue vlink=purple style=\'tab-interval:35.4pt\'><table class=MsoNormalTable border=1 cellspacing=0 cellpadding=0 width=718 style=\'width:19.0cm;margin-left:-1.7pt;border-collapse:collapse;border:none; mso-border-alt:solid windowtext .5pt;mso-yfti-tbllook:1184;mso-padding-alt: 0cm 5.4pt 0cm 5.4pt\'>' htmldata_row = u'<tr style=\'mso-yfti-irow:0;mso-yfti-firstrow:yes;mso-yfti-lastrow:yes\'> <td width=85 style=\'width:63.8pt;border:solid windowtext 1.0pt;mso-border-alt: solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt\'> <p class=MsoNormal style=\'mso-margin-top-alt:auto;mso-margin-bottom-alt:auto\'><span style=\'font-size:10.0pt;color:black\'>{0}<o:p></o:p></span></p> </td> <td width=113 valign=top style=\'width:3.0cm;border:solid windowtext 1.0pt; border-left:none;mso-border-left-alt:solid windowtext .5pt;mso-border-alt: solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt\'> <p class=MsoNormal align=center style=\'mso-margin-top-alt:auto;mso-margin-bottom-alt: auto;text-align:center\'><span style=\'font-size:10.0pt\'>{1}<o:p></o:p></span></p> </td> <td width=113 valign=top style=\'width:3.0cm;border:solid windowtext 1.0pt; border-left:none;mso-border-left-alt:solid windowtext .5pt;mso-border-alt: solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt\'> <p class=MsoNormal align=center style=\'mso-margin-top-alt:auto;mso-margin-bottom-alt: auto;text-align:center\'><span style=\'font-size:10.0pt\'>{2}<o:p></o:p></span></p></td> <td width=227 valign=top style=\'width:6.0cm;border:solid windowtext 1.0pt; border-left:none;mso-border-left-alt:solid windowtext .5pt;mso-border-alt: solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt\'> <p class=MsoNormal align=center style=\'mso-margin-top-alt:auto;mso-margin-bottom-alt: auto;text-align:center\'><span style=\'font-size:10.0pt;color:black\'>{4}<o:p></o:p></span></p></td> <td width=180 valign=top style=\'width:134.65pt;border:solid windowtext 1.0pt; border-left:none;mso-border-left-alt:solid windowtext .5pt;mso-border-alt: solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt\'> <p class=MsoNormal align=centerstyle=\'mso-margin-top-alt:auto;mso-margin-bottom-alt: auto;text-align:center\'><b style=\'mso-bidi-font-weight:normal\'><sub><span style=\'font-size:10.0pt\'>{3}</span></sub></b><spanstyle=\'font-size:10.0pt\'><o:p></o:p></span></p> </td> </tr>' htmldata_end = u'</table></body></html>' exportData = htmldata_start for feat in self.iface.mapCanvas().currentLayer().selectedFeatures(): polygone = feat.geometry().asPolygon() ringq = 0 for ring in polygone: for pt in ring: for pointfeature in pointLayer.getFeatures(): if pointfeature.geometry().equals(QgsGeometry.fromPoint(QgsPoint(pt.x(), pt.y()))): fullname = unicode(pointfeature.attribute(u'name')) # if fullname[0] == u'н': # name = fullname[1:]+u';' # prefix = u'н;' # else: # name = fullname + u';' # prefix = u';' x = round(QgsGeometry.fromPoint(pt).asPoint().y(), 2) sx = unicode('{:.2f}'.format(x)) y = round(QgsGeometry.fromPoint(pt).asPoint().x(), 2) sy = unicode('{:.2f}'.format(y)) exportData += htmldata_row.format(fullname, sx, sy, u'–––––––', u'картометрический') # pref = unicode(pointfeature.attribute(u'prec'))+u';' # hold = unicode(pointfeature.attribute(u'hold')) if len(polygone) >= ringq+2: exportData += htmldata_row.format(u'', u'', u'', u'', u'') ringq += 1 exportData += htmldata_end try: ccf = open(file_name, 'w') # + u'.csv' ccf.write(exportData.encode('cp1251')) except Exception as err: print err finally: ccf.close()
def createASiteFeature(point, attrs): feature = QgsFeature() feature.initAttributes(len(attrs) + 1) for (index, attr) in enumerate(attrs): feature.setAttribute(index + 1, attr) # 如果是小区要素,id为(RNC-BSC_SiteId_CellId) feature.setAttribute(0, str(uuid4()).replace('-', '')) geom = QgsGeometry.fromPoint(point) feature.setGeometry(geom) return feature
def createACellFeature(point, attrs): feature = QgsFeature() feature.initAttributes(len(attrs) + 1) for (index, attr) in enumerate(attrs): feature.setAttribute(index + 1, attr) # 如果是小区要素,id为(RNC-BSC_SiteId_CellId) feature.setAttribute( 0, str(attrs[6]) + '_' + str(attrs[0]) + '_' + str(attrs[2])) geom = QgsGeometry.fromPolygon([point]) feature.setGeometry(geom) return feature
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 canvasMoveEvent(self, event: QgsMapMouseEvent): if self.is_tracking and not self.capturing or self.editvertex is None: return point = QgsGeometry(point_from_event(event, self.snapping)).asPoint() if not self.editmode: self.pointband.movePoint(point) if self.capturing: self.band.movePoint(point) if self.editmode and self.editvertex is not None: found, vertexid = self.geom.vertexIdFromVertexNr(self.editvertex) self.geom.get().moveVertex(vertexid, QgsPoint(point)) self.feature.setGeometry(self.geom) self.currentVectorLayer().updateFeature(self.feature) self.pointband.setToGeometry(self.toMultiPoint(self.geom), self.currentVectorLayer()) self.band.setToGeometry(self.geom, self.currentVectorLayer())
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 paint(self, p, *args): super(RubberBand, self).paint(p) # p.drawRect(self.boundingRect()) if not roam.config.settings.get("draw_distance", True): return offset = QPointF(5, 5) nodescount = self.numberOfVertices() for index in range(nodescount, -1, -1): if index == 0: return qgspoint = self.getPoint(0, index) qgspointbefore = self.getPoint(0, index - 1) # No point before means we are the first index and there is nothing # before us. if not qgspointbefore: return if qgspoint and qgspointbefore: distance = self.distancearea.measureLine( qgspoint, qgspointbefore) if int(distance) == 0: continue text = QgsDistanceArea.formatDistance(distance, 3, self.unit, keepBaseUnit=False) linegeom = QgsGeometry.fromPolyline( [QgsPoint(qgspoint), QgsPoint(qgspointbefore)]) midpoint = linegeom.centroid().asPoint() midpoint = self.toCanvasCoordinates(midpoint) - self.pos() midpoint += offset path = QPainterPath() path.addText(midpoint, self.font, text) p.setPen(self.blackpen) p.setRenderHints(QPainter.Antialiasing) p.setFont(self.font) p.setBrush(self.whitebrush) p.drawPath(path)
def endcapture(self): # if not self.editmode: # self.band.removeLastPoint() self.update_valid_state() errors = self.has_errors() if errors and self.config.get("geometry_validation", True): self.error.emit("Invalid geometry. <br>" "Please recapture. Last capture shown in grey <br>" "<h2>Errors</h2> {0}".format("<br>".join( error.what() for error in errors))) self.endinvalidcapture(errors) return self.capturing = False self.set_tracking(False) self.captureaction.setChecked(True) self.undoaction.setEnabled(False) self.endcaptureaction.setEnabled(False) self.clearErrors() self.geometryComplete.emit(QgsGeometry(self.get_geometry()))
def paint_extent(self, rec): self.roi_x_max = rec.xMaximum() self.ui.XMaxLineEdit.setText(str(round(rec.xMaximum(), 3))) self.roi_y_min = rec.yMinimum() self.ui.YMinLineEdit.setText(str(round(rec.yMinimum(), 3))) self.roi_x_min = rec.xMinimum() self.ui.XMinLineEdit.setText(str(round(rec.xMinimum(), 3))) self.roi_y_max = rec.yMaximum() self.ui.YMaxLineEdit.setText(str(round(rec.yMaximum(), 3))) if self.extent: self.canvas.scene().removeItem(self.extent) self.extent = None self.extent = QgsRubberBand(self.canvas, True) points = [QgsPoint(self.roi_x_max, self.roi_y_min), QgsPoint(self.roi_x_max, self.roi_y_max), QgsPoint(self.roi_x_min, self.roi_y_max), QgsPoint(self.roi_x_min, self.roi_y_min), QgsPoint(self.roi_x_max, self.roi_y_min)] self.extent.setToGeometry(QgsGeometry.fromPolyline(points), None) self.extent.setColor(QColor(227, 26, 28, 255)) self.extent.setWidth(5) self.extent.setLineStyle(Qt.PenStyle(Qt.DashLine)) self.canvas.refresh()
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 canvasPressEvent(self, event): geom = self.band.asGeometry() if not geom: return point = QgsGeometry(point_from_event(event, self.snapping)).asPoint() if self.editmode: layer = self.currentVectorLayer() event.snapToGrid(layer.geometryOptions().geometryPrecision(), layer.crs()) tol = QgsTolerance.vertexSearchRadius(self.canvas.mapSettings()) loc = self.canvas.snappingUtils().locatorForLayer(layer) matches = loc.verticesInRect(point, tol) if matches: for match in matches: if match.featureId() != self.feature.id(): continue self.editpart = 0 self.editvertex = match.vertexIndex() break else: self.editvertex = None self.editpart = 0
def run(self): QgsMessageLog.logMessage(f'Started task {self.description()}', 'TracingCAJ', Qgis.Info) epsg = self.__hidrometers.crs().postgisSrid() uri = "LineString?crs=epsg:" + str( epsg ) + "&field=id:integer" "&field=distance:double(20,2)&index=yes" dist = QgsVectorLayer(uri, 'dist', 'memory') QgsProject.instance().addMapLayer(dist) prov = dist.dataProvider() points_features = [ point_feature for point_feature in self.__hidrometers.getFeatures() ] feats = [] if len(points_features) > 0: for p in points_features: nearest_pipe = self.find_nearest_pipelines(p.geometry()) try: minDistPoint = nearest_pipe.closestSegmentWithContext( p.geometry().asPoint())[1] feat = QgsFeature() feat.setGeometry( QgsGeometry.fromPolylineXY( [p.geometry().asPoint(), minDistPoint])) feat.setAttributes( [points_features.index(p), feat.geometry().length()]) feats.append(feat) except Exception as e: print(p.id()) prov.addFeatures(feats)
def create_point(self, geometry): # add point to the layer self.seg = QgsFeature() self.seg.setGeometry(QgsGeometry.fromPoint(geometry)) self.pr.addFeatures([self.seg]) self.layer.updateExtents()
def toMultiPoint(self, geom): points = QgsMultiPoint() for count, v in enumerate(geom.vertices()): points.addGeometry(v.clone()) newgeom = QgsGeometry(points) return newgeom
def addPoint(self, ref, attrs): refLen = len(ref) if refLen > 3: code = ref[0:2].upper() #print code e = self.east[code] n = self.north[code] #print "East: ", e, " North: ", n # Should now have the northings and eastings values... now need to add some more precision metres = ref[2:] l = len(metres) # print l if l & 0x1: # bad news, shouldn't have an odd number of digits... bomb out! self.badGridError() return 1 else: # Good news so far... even number of digits... split 'em in half and pad with zeroes l /= 2 eMetres = metres[0:l] while len(eMetres) < 5: eMetres = eMetres + "0" nMetres = metres[l:] while len(nMetres) < 5: nMetres = nMetres + "0" # Add the metres onto the eastings and northings e += eMetres n += nMetres # print e # print n # Great... now have out coordinates in QGIS acceptable format... add a new point # Get active layer layer = qgis.utils.iface.activeLayer() caps = layer.dataProvider().capabilities() if caps: # Declare a feature feat = QgsFeature() # Add attributes if len(attrs) > 0: # Just use comma delimited attList attList = attrs.split(",") # print attList feat.setAttributes(attList) # Add the points feat.setGeometry(QgsGeometry.fromPoint(QgsPoint(int(e), int(n)))) res, outFeats = layer.dataProvider().addFeatures([feat]) if not res: qgis.utils.iface.messageBar().pushMessage("Error", "An error occurred adding points", level=QgsMessageBar.CRITICAL) self.stayOpen = False return 1 # Must update the UI for user to enjoy the new points layer.triggerRepaint() else: self.badGridError() else: self.badGridError() return 1 # Must be OK return 0
def init_geometry(self): geometry = QgsGeometry.fromWkt(self.acquisition.footprint_wkt) self.setGeometry(geometry)
def addCellFeature1(self): if self.__dataprovider.capabilities( ) & QgsVectorDataProvider.AddFeatures: cellfeatures = [] ncells = {} ncell_dict = self.getNCellList() allCells = self.cellLayer.getFeatures() update_dict = {} # 要更新的features dict updateGemo_dict = {} # 要更新的features gemotry dict '''获得该小区的相邻小区数''' count = {} count = self.countCell(self.SCell, count) '''获得服务小区的基站ID''' scell = self.getCell() scell_SiteId = (scell[u'基站ID']) scell_point = QgsPoint(scell[u"经度"], scell[u"纬度"]) '''添加小区到相邻小区表中''' for ncell in self.selections: ncell_id = ncell[u'RNC-BSC'] + '_' + (ncell[u'基站ID']) + '_' + ( ncell[u'小区ID']) ncells[ncell_id] = str(ncell[u'基站ID']) '''若服务小区与选中的小区重叠,返回 1 ''' if ncell_id == self.SCell: return 1 '''检查相邻小区表中是否已存在要添加的相邻小区信息,若否则添加''' if not ncell_dict.has_key((self.SCell, ncell_id)): ncell_point = QgsPoint(ncell[u"经度"], ncell[u"纬度"]) if (scell_point is not None) and (ncell_point is not None): d = QgsDistanceArea() distance = d.convertMeasurement( d.measureLine(scell_point, ncell_point), 2, 0, False)[0] cellfaeture = QgsFeature() cellfaeture.initAttributes(8) cellfaeture.setAttribute(0, str(uuid4()).replace( '-', '')) # 生成唯一标识id cellfaeture.setAttribute(1, self.SCell) cellfaeture.setAttribute(2, ncell_id) # 判断是否存在对称相邻小区 if ncell_dict.has_key((ncell_id, self.SCell)): # 如果存在对称小区,则新添加的小区为双向邻区 cellfaeture.setAttribute(3, '2') # 把要更新的对称小区的 NType 信息加入到 update_dict 中 update_data_id = ncell_dict[(ncell_id, self.SCell)] update_data_value = { self.scellLayer.fieldNameIndex('NType'): 2 } update_dict[update_data_id] = update_data_value else: # 如是单向相邻小区 NType 置为 1 cellfaeture.setAttribute(3, '1') if distance >= 0 and (distance is not None): cellfaeture.setAttribute(7, distance) cellfaeture.setGeometry( QgsGeometry.fromPolyline( [scell_point, ncell_point])) cellfeatures.append(cellfaeture) '''再次计算服务小区的相邻小区数''' if count.has_key(self.SCell): count[self.SCell] = count[self.SCell] + 1 else: count[self.SCell] = 1 else: # 若已存在则更新信息 update_data_id = ncell_dict[(self.SCell, ncell_id)] update_data_value = {} # 需要更新的 features 的值得dict # 计算距离 ncell_point = QgsPoint(ncell[u"经度"], ncell[u"纬度"]) if (scell_point is not None) and (ncell_point is not None): d = QgsDistanceArea() distance = d.convertMeasurement( d.measureLine(scell_point, ncell_point), 2, 0, False)[0] update_data_value[self.scellLayer.fieldNameIndex( 'Distance')] = distance # 判断是否存在对称相邻小区 if ncell_dict.has_key((ncell_id, self.SCell)): # 若存在对称小区则 NType 设为 2 update_data_value[self.scellLayer.fieldNameIndex( 'NType')] = 2 else: # 反之,NType 设为 1 update_data_value[self.scellLayer.fieldNameIndex( 'NType')] = 1 update_dict[update_data_id] = update_data_value updateGemo_dict[update_data_id] = QgsGeometry.fromPolyline( [scell_point, ncell_point]) '''若服务小区的相邻小区数大于31则不添加,并返回 2 ''' if count[self.SCell] > 31: return 2 '''添加''' self.__dataprovider.addFeatures(cellfeatures) # 更新相邻小区表内数据 if len(update_dict) > 0: modifyFeatures(self.scellLayer, update_dict) if len(updateGemo_dict) > 0: modifyFeaturesGeom(self.scellLayer, updateGemo_dict) return 0 else: # 图层不能够添加新的Feature,提示错误消息给用户 self.iface.messageBar().pushMessage(u'错误', u'添加相邻小区失败', QgsMessageBar.CRITICAL, 3)
def showCellFeature(self): # 清空元素选择 self.cellLayer.selectAll() self.cellLayer.invertSelection() self.scellLayer.selectAll() self.scellLayer.invertSelection() ncell_dict = self.getNCellList() # 提取所有相邻小区数据 '''变量声明''' showNCellList = [] showNCellIdDict = {} # key 为 NCell, value 为 NType showCellList = [] distanceList = {} t_switchTimes_list = [] s_switchTime_list = [] s_switchRate_list = [] count1 = 0 count2 = 0 '''清空涂色''' if len(self.HL_NCell_O) > 0: for h in self.HL_NCell_O: self.iface.mapCanvas().scene().removeItem(h) if len(self.HL_NCell_D) > 0: for h in self.HL_NCell_D: self.iface.mapCanvas().scene().removeItem(h) '''补全所选中的服务小区的相邻小区信息''' update_dict = {} # 要更新的features dict updateGemo_dict = {} # 要更新的features gemotry dict #featureUtils = FeatureUtils(u'相邻小区', self.iface) allNCells = self.scellLayer.getFeatures() for NCell in allNCells: feature_id = None # 需要更新的相邻小区的features_id if NCell['SCell'] == self.SCell: if NCell.geometry() == None: # 相邻小区的 geometry 不存在才更新信息 feature_id = NCell.id() scell_point = None # 服务小区经纬度 scell_siteId = None # 服务小区所属基站 ncell_point = None # 相邻小区经纬度 ncell_siteId = None # 相邻小区所属基站 allCells = self.cellLayer.getFeatures() for Cell in allCells: if Cell['id'] == NCell['SCell']: scell_point = QgsPoint(Cell[u"经度"], Cell[u"纬度"]) if Cell['id'] == NCell['NCell']: ncell_point = QgsPoint(Cell[u"经度"], Cell[u"纬度"]) if scell_point != None and ncell_point != None: break # 更新相邻小区信息 if feature_id != None and scell_point != None and ncell_point != None: features_value = {} # 需要更新的 features 的值得dict # 判断相邻小区类型 if not ncell_dict.has_key( (NCell['NCell'], NCell['SCell'])): features_value[self.scellLayer.fieldNameIndex( 'NType')] = 1 else: features_value[self.scellLayer.fieldNameIndex( 'NType')] = 2 # 计算距离 d = QgsDistanceArea() distance = d.convertMeasurement( d.measureLine(scell_point, ncell_point), 2, 0, False)[0] features_value[self.scellLayer.fieldNameIndex( 'Distance')] = distance update_dict[feature_id] = features_value updateGemo_dict[feature_id] = QgsGeometry.fromPolyline( [scell_point, ncell_point]) if len(update_dict) > 0 and len(updateGemo_dict) > 0: modifyFeatures(self.scellLayer, update_dict) modifyFeaturesGeom(self.scellLayer, updateGemo_dict) else: pass '''获得相邻小区表中服务小区的相邻小区id,计算各类型相邻小区的数量,并保存其距离到 distanceList 中''' allNCells = self.scellLayer.getFeatures() for NCell in allNCells: if NCell['SCell'] == self.SCell: # 在相邻小区表中找出 SCell 为所设置的服务小区的项 showNCellIdDict[NCell['NCell']] = NCell['NType'] showNCellList.append(NCell.id()) if NCell['NType'] == '1': count1 = count1 + 1 if NCell['NType'] == '2': count2 = count2 + 1 distanceList[(NCell['SCell'], NCell['NCell'])] = NCell['Distance'] t_switchTimes_list.append(str(NCell['HOAttempt'])) s_switchTime_list.append(str(NCell['HOSucc'])) s_switchRate_list.append(str(NCell['HOSuccRate'])) else: pass '''在小区图层中选中相邻小区,并找到服务小区的名字''' allCells = self.cellLayer.getFeatures() for cell in allCells: for (NCell, NType) in showNCellIdDict.items(): if cell[u'RNC-BSC'] + '_' + (cell[u'基站ID']) + '_' + ( cell[u'小区ID']) == NCell: showCellList.append(cell.id()) # 涂色 self.iface.actionZoomFullExtent().trigger( ) # 涂色前将画布缩放到全图显示 if NType == u"1": # 单向小区涂粉色 h = QgsHighlight(self.iface.mapCanvas(), cell.geometry(), self.cellLayer) h.setFillColor(QColor('Pink')) self.HL_NCell_O.append(h) else: h = QgsHighlight(self.iface.mapCanvas(), cell.geometry(), self.cellLayer) h.setFillColor(QColor('Blue')) self.HL_NCell_D.append(h) if cell[u'RNC-BSC'] + '_' + (cell[u'基站ID']) + '_' + ( cell[u'小区ID']) == self.SCell: scell_name = cell[u'小区名'] '''获得相邻小区的名字,并显示服务小区与相邻小区的距离''' i = 0 allCells = self.cellLayer.getFeatures() info_list = [] for cell2 in allCells: for ncell, distance in distanceList.items(): if ncell[1] == (cell2[u'RNC-BSC'] + '_' + (cell2[u'基站ID']) + '_' + (cell2[u'小区ID'])): ncell_name = cell2[u"小区名"] try: # 显示服务小区与相邻小区的相关信息 info = unicode(scell_name) + u' <----> ' + unicode( ncell_name) + u'之间的距离为: ' + unicode( str(distance)) + u'米' info_list.append(info) i = i + 1 except UnicodeEncodeError: pass '''显示相邻小区''' if len(showCellList) == 0: return False else: self.cellLayer.setSelectedFeatures(showCellList) self.scellLayer.setSelectedFeatures(showNCellList) self.iface.actionZoomToSelected().trigger() self.scellwin = SCellInfoUI(info_list, scell_name, count1, count2) self.scellwin.show() self.scellwin.exec_() return (scell_name, count1, count2)
def createPart(self, layer, ring): c = len(ring) curr = 1 pointLayer = self.getLayerByName(u'Точки') if pointLayer is None: idx = -1 else: idx = pointLayer.fieldNameIndex('name') cadastreLayer = self.getLayerByName(u'Кадастр') for point in ring: if curr < c: point1 = point point2 = ring[curr] isEqual = False pt1stst = False pt2stst = False curr += 1 #print point1, point2 line_geometry=QgsGeometry.fromPolyline([QgsPoint(point1.x(), point1.y()), QgsPoint(point2.x(), point2.y())]) # find point for pointfeature in pointLayer.getFeatures(): if pointfeature.geometry().equals(QgsGeometry.fromPoint(QgsPoint(point1.x(), point1.y()))): name = unicode(pointfeature.attribute(u'name')) if name[0] == u'н': pt1stst = True if pointfeature.geometry().equals(QgsGeometry.fromPoint(QgsPoint(point2.x(), point2.y()))): name = unicode(pointfeature.attribute(u'name')) if name[0] == u'н': pt2stst = True # check for identity features = layer.getFeatures() for f in features: if line_geometry.equals(f.geometry()): self.iface.messageBar().pushMessage(u'Найдена дублирующая часть границы, пропущена', level=QgsMessageBar.INFO) isEqual = True break #check for cadastre if not pt1stst and not pt2stst: findInCadastre = False print 'cadastre check' if cadastreLayer is not None and not findInCadastre: cadObjs = cadastreLayer.getFeatures() for cadObj in cadObjs: #print 'cadastre check iteration' if cadObj.geometry().isMultipart(): for cpoly in cadObj.geometry().asMultiPolygon(): if not findInCadastre: for cring in cpoly: cadCurr = 1 if not findInCadastre: cc = len(cring) for cpoint in cring: if cadCurr < cc: cpoint1 = cpoint cpoint2 = cring[cadCurr] cadCurr += 1 cadLine=QgsGeometry.fromPolyline([QgsPoint(cpoint1.x(), cpoint1.y()), QgsPoint(cpoint2.x(), cpoint2.y())]) #print 'checking line' if line_geometry.within(cadLine.buffer(0.000001, 16)): print 'find in cadastre' findInCadastre = True break else: findInCadastre = False else: if not findInCadastre: for cring in cadObj.geometry().asPolygon(): cadCurr = 1 if not findInCadastre: cc = len(cring) for cpoint in cring: if cadCurr < cc: cpoint1 = cpoint cpoint2 = cring[cadCurr] cadCurr += 1 cadLine=QgsGeometry.fromPolyline([QgsPoint(cpoint1.x(), cpoint1.y()), QgsPoint(cpoint2.x(), cpoint2.y())]) #print 'checking line' if line_geometry.within(cadLine.buffer(0.000001, 16)): print 'finded in cadastre' findInCadastre = True break else: findInCadastre = False if not findInCadastre: pt2stst = True if not isEqual: feat = QgsFeature() feat.setGeometry(line_geometry) typeidx = layer.fieldNameIndex('type') feat.initAttributes(2) if pt1stst or pt2stst: feat.setAttribute(typeidx, 2) else: feat.setAttribute(typeidx, 0) layer.dataProvider().addFeatures([feat])
def painting(self, data, fileType): currentInputCRS = self.dlg.inputCRS.text().replace(" ", "") table = data.sheets()[0] nrows = table.nrows if fileType == '4G': vl = QgsVectorLayer("Polygon?crs=EPSG:"+currentInputCRS, u"4G基础信息图层", "memory") vlLabel = QgsVectorLayer("Polygon?crs=EPSG:"+currentInputCRS, u"4G基础信息标签层", "memory") elif fileType == '3G': vl = QgsVectorLayer("Polygon?crs=EPSG:"+currentInputCRS, u"3G基础信息图层", "memory") vlLabel = QgsVectorLayer("Polygon?crs=EPSG:"+currentInputCRS, u"3G基础信息标签层", "memory") elif fileType == '2G': vl = QgsVectorLayer("Polygon?crs=EPSG:"+currentInputCRS, u"2G基础信息图层", "memory") vlLabel = QgsVectorLayer("Polygon?crs=EPSG:"+currentInputCRS, u"2G基础信息标签层", "memory") pr = vl.dataProvider() vlLabelPr = vlLabel.dataProvider() attrs = self.createAttributesTable(fileType) pr.addAttributes(attrs) vlLabelPr.addAttributes(attrs) vl.updateFields() vlLabel.updateFields() fet = QgsFeature() self.dlg.progressBar.setVisible(True) '''开始读取到内存''' list = [[] for row in range(nrows-1)] for i in range(nrows): if i > 0: try: if fileType == '4G': for j in range(21): list[i - 1].append(table.cell(i, j).value) if j == 20: list[i - 1].append(table.cell(i, 13).value % 3) if fileType == '3G': for j in range(73): list[i - 1].append(table.cell(i, j).value) if j == 72: list[i - 1].append(int(table.cell(i, 5).value) % 3) if fileType =='2G': for j in range(67): list[i - 1].append(table.cell(i, j).value) if j == 66: list[i - 1].append(int(table.cell(i, 2).value) % 3) except: self.showErrorDialog(u'文档读取出错', u'文档可能存在错误或格式不符合规范') self.dlg.progressBar.setVisible(False) return '''完成读取到内存''' PCI_Types = { '0': ('#F49ECC', 'Mod3=0'), '1': ('#65F0FF', 'Mod3=1'), '2': ('#00FF00', 'Mod3=2'), '3': ('#000', u'未知值'), } categories = [] for pci_type, (color, label) in PCI_Types.items(): symbol = QgsSymbolV2.defaultSymbol(vl.geometryType()) # symbol = QgsFillSymbolV2.createSimple({'color': color, 'color_border': color, 'width_border': '2'}) symbol.setColor(QColor(color)) # symbol.symbolLayer(0).setOutlineColor(QColor('#75263b')) category = QgsRendererCategoryV2(pci_type, symbol, label) categories.append(category) for i in range(len(list)): fetAttrs =[] if fileType == '4G': for j in range(22): fetAttrs.append(list[i][j]) elif fileType == '3G': for j in range(74): fetAttrs.append(list[i][j]) elif fileType == '2G': for j in range(68): fetAttrs.append(list[i][j]) fet.setAttributes(fetAttrs) if fileType == '4G': Longitude = 11 Latitude = 12 Azimuth = list[i][14] elif fileType == '3G': Longitude = 12 Latitude = 13 Azimuth = list[i][15] elif fileType == '2G': Longitude = 15 Latitude = 16 Azimuth = list[i][5] points = [QgsPoint(list[i][Longitude], list[i][Latitude])] # start point startAngle = -20 endAngle = 20 while startAngle <= endAngle: # midway points points.append(QgsPoint(list[i][Longitude] + 0.001 * math.sin(math.radians(Azimuth + startAngle)), list[i][Latitude] + 0.001 * math.cos(math.radians(Azimuth + startAngle)))) startAngle += 2 points.append(QgsPoint(list[i][Longitude], list[i][Latitude])) # end point # create the renderer and assign it to a layer expression = 'Mod3' # field name renderer = QgsCategorizedSymbolRendererV2(expression, categories) vl.setRendererV2(renderer) fet.setGeometry(QgsGeometry.fromPolygon([points])) pr.addFeatures([fet]) # fet.setGeometry(QgsGeometry.fromPoint(QgsPoint(Longitude, Latitude))) vlLabelPr.addFeatures([fet]) vlLabel.setLayerTransparency(100) vl.updateExtents() vlLabel.updateExtents() vl.commitChanges() vlLabel.commitChanges() vl.updateFields() vlLabel.updateFields() if i % 200 == 0: print 'progress:', float(pr.featureCount()) / nrows * 100 self.dlg.progressBar.setValue(float(pr.featureCount()) / nrows * 100.0) palyr = QgsPalLayerSettings() # palyr.readFromLayer(vl) palyr.enabled = True palyr.fieldName = 'CellName' if fileType =='2G': palyr.fieldName = 'CELL_NAME' palyr.placement = QgsPalLayerSettings.OverPoint # palyr.setDataDefinedProperty(QgsPalLayerSettings.Size,False,False,'','') palyr.writeToLayer(vlLabel) QgsMapLayerRegistry.instance().addMapLayer(vl) QgsMapLayerRegistry.instance().addMapLayer(vlLabel) print 'progress:', 100 self.dlg.progressBar.setValue(0) self.dlg.progressBar.setVisible(False) self.iface.messageBar().clearWidgets() qgis.utils.iface.setActiveLayer(vl) self.saveEPSGChange() self.dlg.close()
def ltefpsOKBtn(self): currentInputCRS = self.dlg.inputCRS.text().replace(" ", "") try: sourceLayer = QgsMapLayerRegistry.instance().mapLayersByName(u'4G基础信息图层')[0] except: self.showErrorDialog(u'未找到图层', u'请检查是否已加载“4G基础信息图层”') return try: inputFreq = int(self.ltefpsdlg.inputFreq.text()) inputPCI = int(self.ltefpsdlg.inputPCI.text()) except: self.showErrorDialog(u'错误的输入', u'请输入数字') return # 隐藏之前的同名图层 try: sameLayers = QgsMapLayerRegistry.instance().mapLayersByName(u'4G图层频点PCI查找') for oneLayer in sameLayers: qgis.utils.iface.legendInterface().setLayerVisible(oneLayer, False) except: pass ltefpsLayer = QgsVectorLayer("Polygon?crs=EPSG:"+currentInputCRS, u"4G图层频点PCI查找", "memory") ltefpsPr = ltefpsLayer.dataProvider() ltefpsPr.addAttributes(self.createAttributesTable('4GFreqPCISearch')) ltefpsLayer.updateFields() qgis.utils.iface.legendInterface().setLayerVisible(sourceLayer, False) ltefpsFet = QgsFeature() PCI_Types = { 1: ('#FFFF00', u'频点='+str(inputFreq)+',PCI='+str(inputPCI)), 0: ('#EEEEEE', u'无关频点PCI') } categories = [] for pci_type, (color, label) in PCI_Types.items(): symbol = QgsSymbolV2.defaultSymbol(ltefpsLayer.geometryType()) symbol.setColor(QColor(color)) category = QgsRendererCategoryV2(pci_type, symbol, label) categories.append(category) # 创建属性表 fetAttrs = [] relatedAttrs = [] Longitude, Latitude, Azimuth = 11, 12, 14 for feature in sourceLayer.getFeatures(): attrs = feature.attributes() if (inputFreq == attrs[9]) & (inputPCI == int(attrs[13])): temp = [] for j in range(21): temp.append(attrs[j]) temp.append(1) relatedAttrs.append(temp) else: temp = [] for j in range(21): temp.append(attrs[j]) temp.append(0) fetAttrs.append(temp) for one in relatedAttrs: fetAttrs.append(one) for fetAttr in fetAttrs: ltefpsFet.setAttributes(fetAttr) # 开始画图 points = [QgsPoint(fetAttr[Longitude], fetAttr[Latitude])] # start point startAngle = -20 endAngle = 20 while startAngle <= endAngle: points.append( QgsPoint(fetAttr[Longitude] + 0.001 * math.sin(math.radians(fetAttr[Azimuth] + startAngle)), fetAttr[Latitude] + 0.001 * math.cos(math.radians(fetAttr[Azimuth] + startAngle)))) startAngle += 2 points.append(QgsPoint(fetAttr[Longitude], fetAttr[Latitude])) # end point ltefpsFet.setGeometry(QgsGeometry.fromPolygon([points])) ltefpsPr.addFeatures([ltefpsFet]) # 根据字段值渲染颜色 expression = 'FreqPCI' # field name renderer = QgsCategorizedSymbolRendererV2(expression, categories) ltefpsLayer.setRendererV2(renderer) ltefpsLayer.updateExtents() ltefpsLayer.commitChanges() ltefpsLayer.updateFields() # 更新图层 QgsMapLayerRegistry.instance().addMapLayer(ltefpsLayer) self.ltefpsdlg.close() self.saveEPSGChange() self.dlg.close()
def gsmfsOKBtn(self): currentInputCRS = self.dlg.inputCRS.text().replace(" ", "") inputFreq = self.gsmfsdlg.inputFreq.text() try: sourceLayer = QgsMapLayerRegistry.instance().mapLayersByName(u'2G基础信息图层')[0] except: self.showErrorDialog(u'未找到图层', u'请检查是否已加载“2G基础信息图层”') return # 隐藏之前的同名图层 try: sameLayer = QgsMapLayerRegistry.instance().mapLayersByName(u'2G图层频点查找') for oneLayer in sameLayer: qgis.utils.iface.legendInterface().setLayerVisible(oneLayer, False) except: pass gsmfsLayer = QgsVectorLayer("Polygon?crs=EPSG:"+currentInputCRS, u"2G图层频点查找", "memory") gsmfsPr = gsmfsLayer.dataProvider() gsmfsPr.addAttributes(self.createAttributesTable('2GFreqSearch')) gsmfsLayer.updateFields() # QgsMapLayerRegistry.instance().addMapLayer(gsmfsLayer) qgis.utils.iface.legendInterface().setLayerVisible(sourceLayer, False) gsmfsFet = QgsFeature() try: inputFreq.replace(" ", "") B = int(inputFreq) except: self.showErrorDialog(u'错误的输入', u'请输入数字') return A = B - 1 C = B + 1 PCI_Types = { A: ('#FF63F2', u'频点='+ str(A)), B: ('#FFFF00', u'指定频点='+ str(B)), C: ('#01FF8D', u'频点='+ str(C)), '-1': ('#eeeeee', u'无关频点') } categories = [] for pci_type, (color, label) in PCI_Types.items(): symbol = QgsSymbolV2.defaultSymbol(gsmfsLayer.geometryType()) symbol.setColor(QColor(color)) category = QgsRendererCategoryV2(pci_type, symbol, label) categories.append(category) # 创建属性表 fetAttrs = [] relatedAttrs = [] Longitude, Latitude, Azimuth = 15, 16, 5 for feature in sourceLayer.getFeatures(): attrs = feature.attributes() if (int(inputFreq) == attrs[3]): temp = [] for j in range(67): temp.append(attrs[j]) temp.append(B) relatedAttrs.append(temp) elif int(inputFreq) == int(attrs[3]) - 1: temp = [] for j in range(67): temp.append(attrs[j]) temp.append(A) relatedAttrs.append(temp) elif int(inputFreq) == int(attrs[3]) + 1: temp = [] for j in range(67): temp.append(attrs[j]) temp.append(C) relatedAttrs.append(temp) else: temp = [] for j in range(67): temp.append(attrs[j]) if j == 66: if (int(inputFreq) != attrs[3]) & (int(inputFreq) != int(attrs[3])-1) & (int(inputFreq) != int(attrs[3])+1): temp.append('-1') fetAttrs.append(temp) for one in relatedAttrs: fetAttrs.append(one) for fetAttr in fetAttrs: gsmfsFet.setAttributes(fetAttr) #开始画图 points = [QgsPoint(fetAttr[Longitude], fetAttr[Latitude])] # start point startAngle = -20 endAngle = 20 while startAngle <= endAngle: points.append(QgsPoint(fetAttr[Longitude] + 0.001 * math.sin(math.radians(fetAttr[Azimuth] + startAngle)), fetAttr[Latitude] + 0.001 * math.cos(math.radians(fetAttr[Azimuth] + startAngle)))) startAngle += 2 points.append(QgsPoint(fetAttr[Longitude], fetAttr[Latitude])) # end point gsmfsFet.setGeometry(QgsGeometry.fromPolygon([points])) gsmfsPr.addFeatures([gsmfsFet]) #根据字段值渲染颜色 expression = 'Condition' # field name renderer = QgsCategorizedSymbolRendererV2(expression, categories) gsmfsLayer.setRendererV2(renderer) gsmfsLayer.updateExtents() gsmfsLayer.commitChanges() gsmfsLayer.updateFields() QgsMapLayerRegistry.instance().addMapLayer(gsmfsLayer) self.gsmfsdlg.close() self.saveEPSGChange() self.dlg.close()
def geometry(self): if self.geom.type() == QgsWkbTypes.PointGeometry: x = float(self.xedit.text()) y = float(self.yedit.text()) return QgsGeometry.fromPointXY(QgsPoint(x, y))
def addCellFeature2(self): if self.__dataprovider.capabilities( ) & QgsVectorDataProvider.AddFeatures: cellfeatures = [] ncells = {} ncell_dict = self.getNCellList() allCells = self.cellLayer.getFeatures() update_dict = {} # 要更新的features dict updateGemo_dict = {} # 要更新的features gemotry dict '''获得该小区的相邻小区数''' count = {} count = self.countCell(self.SCell, count) '''获得服务小区的SiteId''' scell = self.getCell() scell_SiteId = (scell[u"基站ID"]) scell_point = QgsPoint(scell[u'经度'], scell[u'纬度']) '''添加小区到相邻小区表中''' for ncell in self.selections: ncell_id = ncell[u'RNC-BSC'] + '_' + (ncell[u"基站ID"]) + '_' + ( ncell[u"小区ID"]) ncells[ncell_id] = str(ncell[u"基站ID"]) '''计算ncell的相邻小区个数''' count = self.countCell(ncell_id, count) '''若服务小区与选中的小区重叠,返回 1 ''' if ncell_id == self.SCell: return 1 if not ncell_dict.has_key((self.SCell, ncell_id)): '''若相邻小区表中不存在要添加的相邻小区信息,则添加''' ncell_point = QgsPoint(ncell[u'经度'], ncell[u'纬度']) if (scell_point is not None) and (ncell_point is not None): d = QgsDistanceArea() distance = d.convertMeasurement( d.measureLine(scell_point, ncell_point), 2, 0, False)[0] cellfaeture = QgsFeature() cellfaeture.initAttributes(8) cellfaeture.setAttribute(0, str(uuid4()).replace( '-', '')) # 生成唯一标识id cellfaeture.setAttribute(1, self.SCell) cellfaeture.setAttribute(2, ncell_id) # 把 NType 置为 2 (双向) cellfaeture.setAttribute(3, '2') if distance >= 0 and (distance is not None): cellfaeture.setAttribute(7, distance) cellfaeture.setGeometry( QgsGeometry.fromPolyline( [scell_point, ncell_point])) cellfeatures.append(cellfaeture) if count.has_key(self.SCell): count[self.SCell] = count[self.SCell] + 1 else: count[self.SCell] = 1 else: # 若已存在则更新信息 update_data_id = ncell_dict[(self.SCell, ncell_id)] update_data_value = {} # 需要更新的 features 的值得dict # 计算距离 ncell_point = QgsPoint(ncell[u'经度'], ncell[u'纬度']) if (scell_point is not None) and (ncell_point is not None): d = QgsDistanceArea() distance = d.convertMeasurement( d.measureLine(scell_point, ncell_point), 2, 0, False)[0] update_data_value[self.scellLayer.fieldNameIndex( 'Distance')] = distance # NType 设为 2(双向) update_data_value[self.scellLayer.fieldNameIndex( 'NType')] = 2 update_dict[update_data_id] = update_data_value updateGemo_dict[update_data_id] = QgsGeometry.fromPolyline( [scell_point, ncell_point]) '''判断原先是否存在对称相邻小区''' if not ncell_dict.has_key((ncell_id, self.SCell)): # 如果不存在则添加对称相邻小区信息 ncell_point = QgsPoint(ncell[u'经度'], ncell[u'纬度']) if (scell_point is not None) and (ncell_point is not None): d = QgsDistanceArea() distance = d.convertMeasurement( d.measureLine(ncell_point, scell_point), 2, 0, False)[0] cellfaeture = QgsFeature() cellfaeture.initAttributes(8) cellfaeture.setAttribute(0, str(uuid4()).replace( '-', '')) # 生成唯一标识id cellfaeture.setAttribute(1, ncell_id) cellfaeture.setAttribute(2, self.SCell) # NType 置为 2 (双向) cellfaeture.setAttribute(3, '2') if distance >= 0 and (distance is not None): cellfaeture.setAttribute(7, distance) cellfaeture.setGeometry( QgsGeometry.fromPolyline( [ncell_point, scell_point])) cellfeatures.append(cellfaeture) '''再次计算服务小区的相邻小区数''' if count.has_key(ncell_id): count[ncell_id] = count[ncell_id] + 1 else: count[ncell_id] = 1 else: # 若已存在则对称小区的更新信息 # 把要更新的对称小区的 NType 信息加入到 update_dict 中 update_data_id = ncell_dict[(ncell_id, self.SCell)] update_data_value = {} # 需要更新的 features 的值得dict # 计算距离 ncell_point = QgsPoint(ncell[u'经度'], ncell[u'纬度']) if (scell_point is not None) and (ncell_point is not None): d = QgsDistanceArea() distance = d.convertMeasurement( d.measureLine(scell_point, ncell_point), 2, 0, False)[0] update_data_value[self.scellLayer.fieldNameIndex( 'Distance')] = distance # NType 设为 2 (双向) update_data_value[self.scellLayer.fieldNameIndex( 'NType')] = 2 update_dict[update_data_id] = update_data_value '''若服务小区的相邻小区数大于31则不添加,并返回 2 ''' if count[self.SCell] > 31: return 2 if count[ncell_id] > 31: return 3 '''添加''' self.__dataprovider.addFeatures(cellfeatures) # 更新相邻小区表内数据 if len(update_dict) > 0: modifyFeatures(self.scellLayer, update_dict) if len(updateGemo_dict) > 0: modifyFeaturesGeom(self.scellLayer, updateGemo_dict) return 0