def testPainterClipPath(self): region = QgsMapClippingRegion(QgsGeometry.fromWkt('Polygon((0 0, 1 0, 1 1, 0 1, 0 0))')) region.setFeatureClip(QgsMapClippingRegion.FeatureClippingType.ClipPainterOnly) region2 = QgsMapClippingRegion(QgsGeometry.fromWkt('Polygon((0 0, 0.1 0, 0.1 2, 0 2, 0 0))')) region2.setFeatureClip(QgsMapClippingRegion.FeatureClippingType.NoClipping) region3 = QgsMapClippingRegion(QgsGeometry.fromWkt('Polygon((0 0, 0.1 0, 0.1 2, 0 2, 0 0))')) region3.setFeatureClip(QgsMapClippingRegion.FeatureClippingType.ClipPainterOnly) rc = QgsRenderContext() for t in [QgsMapLayerType.VectorLayer, QgsMapLayerType.RasterLayer, QgsMapLayerType.MeshLayer, QgsMapLayerType.VectorTileLayer]: path, should_clip = QgsMapClippingUtils.calculatePainterClipRegion([], rc, t) self.assertFalse(should_clip) self.assertEqual(path.elementCount(), 0) for t in [QgsMapLayerType.VectorLayer, QgsMapLayerType.RasterLayer, QgsMapLayerType.MeshLayer, QgsMapLayerType.VectorTileLayer]: path, should_clip = QgsMapClippingUtils.calculatePainterClipRegion([region], rc, t) self.assertTrue(should_clip) self.assertEqual(QgsGeometry.fromQPolygonF(path.toFillPolygon()).asWkt(1), 'Polygon ((0 1, 1 1, 1 0, 0 0, 0 1))') # region2 is a Intersects type clipping region, should not apply for vector layers path, should_clip = QgsMapClippingUtils.calculatePainterClipRegion([region2], rc, QgsMapLayerType.VectorLayer) self.assertFalse(should_clip) self.assertEqual(path.elementCount(), 0) for t in [QgsMapLayerType.RasterLayer, QgsMapLayerType.MeshLayer, QgsMapLayerType.VectorTileLayer]: path, should_clip = QgsMapClippingUtils.calculatePainterClipRegion([region2], rc, t) self.assertTrue(should_clip) self.assertEqual(QgsGeometry.fromQPolygonF(path.toFillPolygon()).asWkt(1), 'Polygon ((0 1, 0.1 1, 0.1 -1, 0 -1, 0 1))') for t in [QgsMapLayerType.VectorLayer, QgsMapLayerType.RasterLayer, QgsMapLayerType.MeshLayer, QgsMapLayerType.VectorTileLayer]: path, should_clip = QgsMapClippingUtils.calculatePainterClipRegion([region, region2, region3], rc, t) self.assertTrue(should_clip) geom = QgsGeometry.fromQPolygonF(path.toFillPolygon()) geom.normalize() self.assertEqual(geom.asWkt(1), 'Polygon ((0 0, 0 1, 0.1 1, 0.1 0, 0 0))') rc.setMapToPixel(QgsMapToPixel(5, 10, 11, 200, 150, 0)) for t in [QgsMapLayerType.VectorLayer, QgsMapLayerType.RasterLayer, QgsMapLayerType.MeshLayer, QgsMapLayerType.VectorTileLayer]: path, should_clip = QgsMapClippingUtils.calculatePainterClipRegion([region, region3], rc, t) self.assertTrue(should_clip) self.assertEqual(QgsGeometry.fromQPolygonF(path.toFillPolygon()).asWkt(0), 'Polygon ((98 77, 98 77, 98 77, 98 77, 98 77))')
def AddDrawPolygonOnMap(poly_coordinates): """ Add Polygon Layer """ polyLyr = selectLayerByName(Polygon_lyr, groupName) if polyLyr is None: return polyLyr.startEditing() feature = QgsFeature() point = QPointF() # create float polygon --> construcet out of 'point' list_polygon = QPolygonF() for x in range(0, len(poly_coordinates)): if x % 2 == 0: point.setX(poly_coordinates[x]) point.setY(poly_coordinates[x + 1]) list_polygon.append(point) point.setX(poly_coordinates[0]) point.setY(poly_coordinates[1]) list_polygon.append(point) geomP = QgsGeometry.fromQPolygonF(list_polygon) feature.setGeometry(geomP) # Calculate Area WSG84 (Meters) area_wsg84 = QgsDistanceArea() area_wsg84.setSourceCrs( QgsCoordinateReferenceSystem.fromOgcWmsCrs("EPSG:4326"), _layerreg.transformContext(), ) if area_wsg84.sourceCrs().isGeographic(): area_wsg84.setEllipsoid(area_wsg84.sourceCrs().ellipsoidAcronym()) # Calculate Centroid try: centroid = feature.geometry().centroid().asPoint() except Exception: iface.vectorLayerTools().stopEditing(polyLyr, False) return False feature.setAttributes([ centroid.x(), centroid.y(), 0.0, area_wsg84.measurePolygon(geomP.asPolygon()[0]), ]) polyLyr.addFeatures([feature]) CommonLayer(polyLyr) return True
def get_polygon_filter(self, index=0): if self.linked_map and self.plot_settings[index].properties.get('layout_filter_by_map', False): polygon_filter = FilterRegion(QgsGeometry.fromQPolygonF(self.linked_map.visibleExtentPolygon()), self.linked_map.crs()) visible_features_only = True elif self.plot_settings[index].properties.get('layout_filter_by_atlas', False) and \ self.layout().reportContext().layer() and self.layout().reportContext().feature().isValid(): polygon_filter = FilterRegion(self.layout().reportContext().currentGeometry(), self.layout().reportContext().layer().crs()) visible_features_only = True else: polygon_filter = None visible_features_only = False return polygon_filter, visible_features_only
def create_plot(self): if self.linked_map and self.filter_by_map: polygon_filter = FilterRegion( QgsGeometry.fromQPolygonF( self.linked_map.visibleExtentPolygon()), self.linked_map.crs()) visible_features_only = True elif self.filter_by_atlas and self.layout().reportContext().layer( ) and self.layout().reportContext().feature().isValid(): polygon_filter = FilterRegion( self.layout().reportContext().currentGeometry(), self.layout().reportContext().layer().crs()) visible_features_only = True else: polygon_filter = None visible_features_only = False config = {'displayModeBar': False, 'staticPlot': True} if len(self.plot_settings) == 1: plot_factory = PlotFactory(self.plot_settings[0], self, polygon_filter=polygon_filter) self.plot_settings[0].properties[ 'visible_features_only'] = visible_features_only return plot_factory.build_html(config) # to plot many plots in the same figure elif len(self.plot_settings) > 1: # plot list ready to be called within go.Figure pl = [] plot_factory = PlotFactory(self.plot_settings[0], self, polygon_filter=polygon_filter) for plot_setting in self.plot_settings: plot_setting.properties[ 'visible_features_only'] = visible_features_only factory = PlotFactory(plot_setting, self, polygon_filter=polygon_filter) pl.append(factory.trace[0]) plot_path = plot_factory.build_figures( self.plot_settings[0].plot_type, pl, config=config) with open(plot_path, 'r') as myfile: return myfile.read()
def AddDrawPolygonOnMap(poly_coordinates): ''' Add Polygon Layer ''' polyLyr = qgsu.selectLayerByName(Polygon_lyr) if polyLyr is None: return polyLyr.startEditing() feature = QgsFeature() point = QPointF() # create float polygon --> construcet out of 'point' list_polygon = QPolygonF() for x in range(0, len(poly_coordinates)): if x % 2 == 0: point.setX(poly_coordinates[x]) point.setY(poly_coordinates[x + 1]) list_polygon.append(point) point.setX(poly_coordinates[0]) point.setY(poly_coordinates[1]) list_polygon.append(point) geomP = QgsGeometry.fromQPolygonF(list_polygon) feature.setGeometry(geomP) # Calculate Area WSG84 (Meters) area_wsg84 = QgsDistanceArea() area_wsg84.setSourceCrs( QgsCoordinateReferenceSystem.fromOgcWmsCrs('EPSG:4326'), QgsProject.instance().transformContext()) if (area_wsg84.sourceCrs().isGeographic()): area_wsg84.setEllipsoid(area_wsg84.sourceCrs().ellipsoidAcronym()) # Calculate Centroid centroid = feature.geometry().centroid().asPoint() feature.setAttributes([ centroid.x(), centroid.y(), 0.0, area_wsg84.measurePolygon(geomP.asPolygon()[0]) ]) polyLyr.addFeatures([feature]) CommonLayer(polyLyr) return
def processAlgorithm(self, parameters, context, feedback): layout_name = self.parameterAsString(parameters, self.LAYOUT, context) map_uuid = self.parameterAsString(parameters, self.MAP, context) layout = context.project().layoutManager().layoutByName(layout_name) if layout is None: raise QgsProcessingException( 'Cannot find layout with name "{}"'.format(layout_name)) item = layout.itemByUuid(map_uuid) if item is None: raise QgsProcessingException( 'Cannot find matching map item with uuid "{}"'.format( map_uuid)) map = sip.cast(item, QgsLayoutItemMap) fields = QgsFields() fields.append(QgsField('width', QVariant.Double)) fields.append(QgsField('height', QVariant.Double)) fields.append(QgsField('scale', QVariant.Double)) fields.append(QgsField('rotation', QVariant.Double)) sink, dest = self.parameterAsSink(parameters, self.OUTPUT, context, fields, QgsWkbTypes.Polygon, map.crs()) if sink is None: raise QgsProcessingException( self.invalidSinkError(parameters, self.OUTPUT)) extent = QgsGeometry.fromQPolygonF(map.visibleExtentPolygon()) f = QgsFeature() f.setAttributes([ map.rect().width(), map.rect().height(), map.scale(), map.mapRotation() ]) f.setGeometry(extent) sink.addFeature(f, QgsFeatureSink.FastInsert) return {self.OUTPUT: dest}
def create_plot(self): if self.linked_map and self.filter_by_map: polygon_filter = FilterRegion( QgsGeometry.fromQPolygonF( self.linked_map.visibleExtentPolygon()), self.linked_map.crs()) self.plot_settings.properties['visible_features_only'] = True elif self.filter_by_atlas and self.layout().reportContext().layer( ) and self.layout().reportContext().feature().isValid(): polygon_filter = FilterRegion( self.layout().reportContext().currentGeometry(), self.layout().reportContext().layer().crs()) self.plot_settings.properties['visible_features_only'] = True else: polygon_filter = None self.plot_settings.properties['visible_features_only'] = False factory = PlotFactory(self.plot_settings, self, polygon_filter=polygon_filter) config = {'displayModeBar': False, 'staticPlot': True} return factory.build_html(config)
def create_grid_halo(crs): min_x = -180 min_y = -90 max_x = 180 max_y = 90 step = 2 coords = [] for y in range(min_y, max_y + step, step): coords.append((min_x, y)) for x in range(min_x + step, max_x + step, step): coords.append((x, max_y)) for y in reversed(range(min_y, max_y + step, step)): coords.append((max_x, y)) for x in reversed(range(min_x + step, max_x + step, step)): coords.append((x, min_y)) coords.append(coords[0]) # noinspection PyCallByClass,PyArgumentList geom = QgsGeometry.fromPolygonXY( [[QgsPointXY(pair[0], pair[1]) for pair in coords]]).asQPolygonF() # noinspection PyArgumentList transformer = QgsCoordinateTransform(WGS84, crs, QgsProject.instance()) transformer.transformPolygon(geom) # noinspection PyArgumentList return QgsGeometry.fromQPolygonF(geom)
def paint(self, painter, option, widget): self.draw_background(painter) painter.setClipRect(0, 0, self.__width - 1, self.__height - 1) context = qgis_render_context(painter, self.__width, self.__height) context.setExtent(QgsRectangle(0, 0, self.__width, self.__height)) fields = self.__layer.fields() has_formation_code = "formation_code_column" in self.__column_mapping \ and self.__column_mapping["formation_code_column"] is not None # need to set fields in context so they can be evaluated in expression. # if not QgsExpressionNodeColumnRef prepareNode methods will fail when # checking that variable EXPR_FIELDS is defined (this variable is set # by setFields method context.expressionContext().setFields(fields) self.__renderer.startRender(context, fields) try: for i, f in enumerate(self.__data): depth_from = float(self.__field_value(f, "depth_from_column")) depth_to = float(self.__field_value(f, "depth_to_column")) if abs((self.__max_z - self.__min_z) * self.__height) > 0: y1 = (depth_from - self.__min_z) / ( self.__max_z - self.__min_z) * self.__height y2 = (depth_to - self.__min_z) / ( self.__max_z - self.__min_z) * self.__height painter.setPen(QPen()) painter.setBrush(QBrush()) if i == 0: painter.drawLine(0, y1, self.__width - 1, y1) painter.drawLine(0, y2, self.__width - 1, y2) if has_formation_code: # legend text formation_code = str( self.__field_value(f, "formation_code_column")) if formation_code: fm = painter.fontMetrics() w = fm.width(formation_code) x = (self.__width / 2 - w) / 2 + self.__width / 2 y = (y1 + y2) / 2 if y - fm.ascent() > y1 and y + fm.descent() < y2: painter.drawText(x, y, formation_code) geom = QgsGeometry.fromQPolygonF( QPolygonF( QRectF(0, self.__height - y1, self.__width / 2, y1 - y2))) else: geom = QgsGeometry.fromQPolygonF( QPolygonF( QRectF(0, self.__height - y1, self.__width, y1 - y2))) feature = QgsFeature(fields, 1) for field in fields: feature[field.name()] = f[field.name()] feature.setGeometry(geom) self.__renderer.renderFeature(feature, context) finally: self.__renderer.stopRender(context)
def paint(self, painter, option, widget): self.draw_background(painter) if self.__data_rect is None: return context = qgis_render_context(painter, self.width(), self.height()) context.setExtent(QgsRectangle(0, 0, self.width(), self.height())) fields = self.__layer.fields() context.expressionContext().setFields(fields) if not self.__y_values: self._populate_cache() if self.__x_orientation == ORIENTATION_LEFT_TO_RIGHT and self.__y_orientation == ORIENTATION_UPWARD: rw = self.width() / self.__data_rect.width() rh = self.height() / self.__data_rect.height() elif self.__x_orientation == ORIENTATION_DOWNWARD and self.__y_orientation == ORIENTATION_LEFT_TO_RIGHT: rw = self.height() / self.__data_rect.width() rh = self.width() / self.__data_rect.height() self.__renderer.startRender(context, fields) for i in range(len(self.__y_values)): f = QgsFeature(self.__layer.fields()) min_x, max_x = self.__min_x_values[i], self.__max_x_values[i] value = self.__y_values[i] min_xx = (min_x - self.__data_rect.left()) * rw max_xx = (max_x - self.__data_rect.left()) * rw yy = (value - self.__data_rect.top()) * rh if self.__render_type == POLYGON_RENDERER: if self.__x_orientation == ORIENTATION_LEFT_TO_RIGHT and self.__y_orientation == ORIENTATION_UPWARD: geom = QgsGeometry.fromQPolygonF( QPolygonF(QRectF(min_xx, 0, max_xx - min_xx, yy))) elif self.__x_orientation == ORIENTATION_DOWNWARD and self.__y_orientation == ORIENTATION_LEFT_TO_RIGHT: geom = QgsGeometry.fromQPolygonF( QPolygonF( QRectF(0, self.height() - max_xx, yy, max_xx - min_xx))) elif self.__render_type == LINE_RENDERER: if self.__x_orientation == ORIENTATION_LEFT_TO_RIGHT and self.__y_orientation == ORIENTATION_UPWARD: geom = QgsGeometry.fromPolylineXY( [QgsPointXY(min_xx, yy), QgsPointXY(max_xx, yy)]) elif self.__x_orientation == ORIENTATION_DOWNWARD and self.__y_orientation == ORIENTATION_LEFT_TO_RIGHT: geom = QgsGeometry.fromPolylineXY( [QgsPointXY(yy, min_xx), QgsPointXY(yy, max_xx)]) f.setGeometry(geom) self.__renderer.renderFeature(f, context) self.__renderer.stopRender(context) if self.__point_to_label is not None: i = self.__point_to_label if i >= len(self.__min_x_values): return x1, x2, y = self.__min_x_values[i], self.__max_x_values[ i], self.__y_values[i] if self.__x_orientation == ORIENTATION_LEFT_TO_RIGHT and self.__y_orientation == ORIENTATION_UPWARD: px1 = (x1 - self.__data_rect.x()) * rw px2 = (x2 - self.__data_rect.x()) * rw px = (px1 + px2) / 2.0 py = self.height() - (y - self.__data_rect.y()) * rh elif self.__x_orientation == ORIENTATION_DOWNWARD and self.__y_orientation == ORIENTATION_LEFT_TO_RIGHT: py1 = (x1 - self.__data_rect.x()) * rw py2 = (x2 - self.__data_rect.x()) * rw py = (py1 + py2) / 2.0 px = (y - self.__data_rect.y()) * rh painter.drawLine(px - 5, py - 5, px + 5, py + 5) painter.drawLine(px - 5, py + 5, px + 5, py - 5)