def test_3(self): sym = self.lines_layer.renderer().symbol() # double headed sym_layer = QgsArrowSymbolLayer.create( { "arrow_width": "7", "head_length": "6", "head_thickness": "8", "head_type": "0", "arrow_type": "1", "is_curved": "0", } ) fill_sym = QgsFillSymbol.createSimple( {"color": "#8bcfff", "outline_color": "#000000", "outline_style": "solid", "outline_width": "1"} ) sym_layer.setSubSymbol(fill_sym) sym.changeSymbolLayer(0, sym_layer) rendered_layers = [self.lines_layer] self.mapsettings.setLayers(rendered_layers) renderchecker = QgsMultiRenderChecker() ms = self.mapsettings ms.setExtent(QgsRectangle(-101, 35, -99, 37)) renderchecker.setMapSettings(ms) renderchecker.setControlName("expected_arrowsymbollayer_3") self.assertTrue(renderchecker.runTest("arrowsymbollayer_3"))
def testColors(self): """ Test colors, need to make sure colors are passed/retrieved from subsymbol """ sym_layer = QgsArrowSymbolLayer.create() sym_layer.setColor(QColor(150, 50, 100)) self.assertEqual(sym_layer.color(), QColor(150, 50, 100)) self.assertEqual(sym_layer.subSymbol().color(), QColor(150, 50, 100)) sym_layer.subSymbol().setColor(QColor(250, 150, 200)) self.assertEqual(sym_layer.subSymbol().color(), QColor(250, 150, 200)) self.assertEqual(sym_layer.color(), QColor(250, 150, 200))
def set_linestring_arrow_symbology(layer: QgsVectorLayer): layer_symbol = layer.renderer().symbol() # noinspection PyCallByClass,PyArgumentList arrow_symbol_layer = QgsArrowSymbolLayer.create( {'arrow_width': '3', 'head_length': '4', 'head_thickness': '4', 'head_type': '0', "is_curved": "0"} ) # noinspection PyCallByClass,PyArgumentList arrow_fill_sub_symbol = QgsFillSymbol.createSimple( {'color': '#8bcfff', 'outline_color': '#000000', 'outline_style': 'solid', 'outline_width': '0.5'} ) arrow_symbol_layer.setSubSymbol(arrow_fill_sub_symbol) layer_symbol.changeSymbolLayer(0, arrow_symbol_layer)
def testDataDefinedOpacity(self): line_shp = os.path.join(TEST_DATA_DIR, 'lines.shp') line_layer = QgsVectorLayer(line_shp, 'Lines', 'ogr') self.assertTrue(line_layer.isValid()) sym = QgsLineSymbol() sym_layer = QgsArrowSymbolLayer.create({ 'arrow_width': '7', 'head_length': '6', 'head_thickness': '8', 'head_type': '0', 'arrow_type': '0', 'is_repeated': '0', 'is_curved': '0' }) fill_sym = QgsFillSymbol.createSimple({ 'color': '#8bcfff', 'outline_color': '#000000', 'outline_style': 'solid', 'outline_width': '1' }) fill_sym.symbolLayer(0).setDataDefinedProperty( QgsSymbolLayer.PropertyFillColor, QgsProperty.fromExpression("if(Name='Arterial', 'red', 'green')")) fill_sym.symbolLayer(0).setDataDefinedProperty( QgsSymbolLayer.PropertyStrokeColor, QgsProperty.fromExpression( "if(Name='Arterial', 'magenta', 'blue')")) sym_layer.setSubSymbol(fill_sym) sym.changeSymbolLayer(0, sym_layer) sym.setDataDefinedProperty( QgsSymbol.PropertyOpacity, QgsProperty.fromExpression("if(\"Value\" = 1, 25, 50)")) line_layer.setRenderer(QgsSingleSymbolRenderer(sym)) ms = QgsMapSettings() ms.setOutputSize(QSize(400, 400)) ms.setOutputDpi(96) ms.setExtent(QgsRectangle(-118.5, 19.0, -81.4, 50.4)) ms.setLayers([line_layer]) # Test rendering renderchecker = QgsMultiRenderChecker() renderchecker.setMapSettings(ms) renderchecker.setControlPathPrefix('symbol_arrow') renderchecker.setControlName('expected_arrow_ddopacity') res = renderchecker.runTest('expected_arrow_ddopacity') self.report += renderchecker.report() self.assertTrue(res)
def test_2(self): sym = self.lines_layer.renderer().symbol() # double headed sym_layer = QgsArrowSymbolLayer.create({'arrow_width': '5', 'head_length': '4', 'head_thickness': '6', 'head_type': '2'}) fill_sym = QgsFillSymbol.createSimple({'color': '#8bcfff', 'outline_color': '#000000', 'outline_style': 'solid', 'outline_width': '1'}) sym_layer.setSubSymbol(fill_sym) sym.changeSymbolLayer(0, sym_layer) rendered_layers = [self.lines_layer] self.mapsettings.setLayers(rendered_layers) renderchecker = QgsMultiRenderChecker() renderchecker.setMapSettings(self.mapsettings) renderchecker.setControlName('expected_arrowsymbollayer_2') self.assertTrue(renderchecker.runTest('arrowsymbollayer_2'))
def changeSymbol(self): """Change symbology from seleted layer""" if isinstance(self.lyr.renderer(),QgsSingleSymbolRenderer) == True: symbLyr = QgsArrowSymbolLayer() symbLyr.setIsCurved(False) symbLyr.setIsRepeated(True) self.lyr.renderer().symbol().changeSymbolLayer(0, symbLyr) self.lyr.triggerRepaint() self.iface.layerTreeView().refreshLayerSymbology(self.lyr.id()) else: QMessageBox.warning(None,"Can't change symbology","The layer must be single symbol")
def test_3(self): sym = self.lines_layer.renderer().symbol() # double headed sym_layer = QgsArrowSymbolLayer.create({'arrow_width': '7', 'head_length': '6', 'head_thickness': '8', 'head_type': '0', 'arrow_type': '1', 'is_curved': '0'}) fill_sym = QgsFillSymbol.createSimple({'color': '#8bcfff', 'outline_color': '#000000', 'outline_style': 'solid', 'outline_width': '1'}) sym_layer.setSubSymbol(fill_sym) sym.changeSymbolLayer(0, sym_layer) rendered_layers = [self.lines_layer] self.mapsettings.setLayers(rendered_layers) renderchecker = QgsMultiRenderChecker() ms = self.mapsettings ms.setExtent(QgsRectangle(-101, 35, -99, 37)) renderchecker.setMapSettings(ms) renderchecker.setControlName('expected_arrowsymbollayer_3') self.assertTrue(renderchecker.runTest('arrowsymbollayer_3'))
def _render_route_layer(self, _list): self.routeLayer = QgsVectorLayer( "LineString?crs=" + self.featLayer.crs().authid(), self.featLayer.name() + "_Route", "memory") routePr = self.routeLayer.dataProvider() self.routeLayer.startEditing() _symbol = QgsLineSymbol() _symbol.appendSymbolLayer(QgsArrowSymbolLayer()) self.routeLayer.renderer().setSymbol(_symbol) for idx in range(len(_list) - 1): route_seg = [_list[idx], _list[idx + 1]] feat = QgsFeature() feat.setGeometry(QgsGeometry.fromPolylineXY(route_seg)) routePr.addFeatures([feat]) self.routeLayer.commitChanges() self._add_layer(self.routeLayer)
def testRingNumberVariable(self): # test test geometry_ring_num variable s3 = QgsFillSymbol() s3.deleteSymbolLayer(0) s3.appendSymbolLayer(QgsArrowSymbolLayer()) s3.symbolLayer(0).setIsCurved(False) s3.symbolLayer(0).subSymbol()[0].setDataDefinedProperty( QgsSymbolLayer.PropertyFillColor, QgsProperty.fromExpression( 'case when @geometry_ring_num=0 then \'green\' when @geometry_ring_num=1 then \'blue\' when @geometry_ring_num=2 then \'red\' end' )) g = QgsGeometry.fromWkt( 'Polygon((0 0, 10 0, 10 10, 0 10, 0 0),(1 1, 1 2, 2 2, 2 1, 1 1),(8 8, 9 8, 9 9, 8 9, 8 8))' ) rendered_image = self.renderGeometry(s3, g) assert self.imageCheck('arrow_ring_num', 'arrow_ring_num', rendered_image)
def test_1(self): sym = self.lines_layer.rendererV2().symbol() sym_layer = QgsArrowSymbolLayer.create({'head_size': '6.5'}) dd = QgsDataDefined("(@geometry_point_num % 4) * 2") sym_layer.setDataDefinedProperty("arrow_width", dd) dd2 = QgsDataDefined("(@geometry_point_num % 4) * 2") sym_layer.setDataDefinedProperty("head_size", dd2) fill_sym = QgsFillSymbolV2.createSimple({'color': '#8bcfff', 'outline_color': '#000000', 'outline_style': 'solid', 'outline_width': '1'}) sym_layer.setSubSymbol(fill_sym) sym.changeSymbolLayer(0, sym_layer) rendered_layers = [self.lines_layer.id()] self.mapsettings.setLayers(rendered_layers) renderchecker = QgsMultiRenderChecker() renderchecker.setMapSettings(self.mapsettings) renderchecker.setControlName('expected_arrowsymbollayer_1') self.assertTrue(renderchecker.runTest('arrowsymbollayer_1'))
def test_unrepeated(self): sym = self.lines_layer.rendererV2().symbol() # double headed sym_layer = QgsArrowSymbolLayer.create({'arrow_width': '7', 'head_length': '6', 'head_thickness': '8', 'head_type': '0', 'arrow_type': '0'}) # no repetition sym_layer.setIsRepeated(False) fill_sym = QgsFillSymbolV2.createSimple({'color': '#8bcfff', 'outline_color': '#000000', 'outline_style': 'solid', 'outline_width': '1'}) sym_layer.setSubSymbol(fill_sym) sym.changeSymbolLayer(0, sym_layer) rendered_layers = [self.lines_layer.id()] self.mapsettings.setLayers(rendered_layers) renderchecker = QgsMultiRenderChecker() ms = self.mapsettings ms.setExtent(QgsRectangle(-119, 17, -82, 50)) renderchecker.setMapSettings(ms) renderchecker.setControlName('expected_arrowsymbollayer_4') self.assertTrue(renderchecker.runTest('arrowsymbollayer_4'))
def test_2(self): sym = self.lines_layer.renderer().symbol() # double headed sym_layer = QgsArrowSymbolLayer.create( {"arrow_width": "5", "head_length": "4", "head_thickness": "6", "head_type": "2"} ) fill_sym = QgsFillSymbol.createSimple( {"color": "#8bcfff", "outline_color": "#000000", "outline_style": "solid", "outline_width": "1"} ) sym_layer.setSubSymbol(fill_sym) sym.changeSymbolLayer(0, sym_layer) rendered_layers = [self.lines_layer] self.mapsettings.setLayers(rendered_layers) renderchecker = QgsMultiRenderChecker() renderchecker.setMapSettings(self.mapsettings) renderchecker.setControlName("expected_arrowsymbollayer_2") self.assertTrue(renderchecker.runTest("arrowsymbollayer_2"))
def test_1(self): sym = self.lines_layer.renderer().symbol() sym_layer = QgsArrowSymbolLayer.create({'head_length': '6.5', 'head_thickness': '6.5'}) dd = QgsProperty.fromExpression("(@geometry_point_num % 4) * 2") sym_layer.setDataDefinedProperty(QgsSymbolLayer.PropertyArrowWidth, dd) dd2 = QgsProperty.fromExpression("(@geometry_point_num % 4) * 2") sym_layer.setDataDefinedProperty(QgsSymbolLayer.PropertyArrowHeadLength, dd2) dd3 = QgsProperty.fromExpression("(@geometry_point_num % 4) * 2") sym_layer.setDataDefinedProperty(QgsSymbolLayer.PropertyArrowHeadThickness, dd3) fill_sym = QgsFillSymbol.createSimple({'color': '#8bcfff', 'outline_color': '#000000', 'outline_style': 'solid', 'outline_width': '1'}) sym_layer.setSubSymbol(fill_sym) sym.changeSymbolLayer(0, sym_layer) rendered_layers = [self.lines_layer] self.mapsettings.setLayers(rendered_layers) renderchecker = QgsMultiRenderChecker() renderchecker.setMapSettings(self.mapsettings) renderchecker.setControlName('expected_arrowsymbollayer_1') self.assertTrue(renderchecker.runTest('arrowsymbollayer_1'))
def test_1(self): sym = self.lines_layer.renderer().symbol() sym_layer = QgsArrowSymbolLayer.create({"head_length": "6.5", "head_thickness": "6.5"}) dd = QgsDataDefined("(@geometry_point_num % 4) * 2") sym_layer.setDataDefinedProperty("arrow_width", dd) dd2 = QgsDataDefined("(@geometry_point_num % 4) * 2") sym_layer.setDataDefinedProperty("head_length", dd2) dd3 = QgsDataDefined("(@geometry_point_num % 4) * 2") sym_layer.setDataDefinedProperty("head_thickness", dd3) fill_sym = QgsFillSymbol.createSimple( {"color": "#8bcfff", "outline_color": "#000000", "outline_style": "solid", "outline_width": "1"} ) sym_layer.setSubSymbol(fill_sym) sym.changeSymbolLayer(0, sym_layer) rendered_layers = [self.lines_layer] self.mapsettings.setLayers(rendered_layers) renderchecker = QgsMultiRenderChecker() renderchecker.setMapSettings(self.mapsettings) renderchecker.setControlName("expected_arrowsymbollayer_1") self.assertTrue(renderchecker.runTest("arrowsymbollayer_1"))
def __getQgsLineSymbolLayer(self, msstyle): """docstring for __getLineSymbolLayer""" props = {} type_marker = '' symbol = msstyle.get('symbol', False) if symbol: (type_marker, symbolname, msSymbol, props) = self.__getMsSymbol(symbol, props) opacity = self.__getMsOpacity(msstyle) self.__getMsColor(msstyle, props, opacity, isline=True) self.__getMsOutlinecolor(msstyle, props, opacity, isline=True) self.__getMsLinecap(msstyle, props) self.__getMsLinejoin(msstyle, props) self.__getMsPattern(msstyle, props) self.__getMsWidth(msstyle, props) self.__getMsOutline(msstyle, props) self.__getMsScale(msstyle, props) offset = self.__getMsOffset(msstyle, props) if not type_marker: self.deleteProperties(props, _qgis.SIMPLE_LINE_SYMBOL_LAYER) qgsSymbol = QgsSimpleLineSymbolLayerV2.create(props) else: props_parent = {} self.__setMsOffsetXY(offset, props) self.__getMsAngle(msstyle, props, props_parent) gap = self.__getMsGap(msstyle) if type_marker == _ms.MS_SYMBOL_ARROW: #El estilo de relleno de la flecha, no soportado por mapserver #[solid|horizontal|vertical|cross|b_diagonal|f_diagonal|diagonal_x|dense1|dense2|dense3|dense4|dense5|dense6|dense7|no] if QGis.QGIS_VERSION_INT >= 21600: props['style'] = 'solid' props_parent['head_type'] = _qgis.MARKERS_ARROW[ symbolname][0] props_parent['arrow_type'] = _qgis.MARKERS_ARROW[ symbolname][1] props_parent['is_repeated'] = '1' if gap else '0' self.deleteProperties(props, _qgis.SIMPLE_FILL_SYMBOL_LAYER) qgsSubSymbol = self.__getSubSymbol( QgsFillSymbolV2, QgsSimpleFillSymbolLayerV2, QGis.Fill, props) self.deleteProperties(props_parent, _qgis.ARROW_SYMBOL_LAYER) qgsSymbol = QgsArrowSymbolLayer.create(props_parent) else: self.deleteProperties(props, _qgis.SIMPLE_MARKER_SYMBOL_LAYER) qgsSubSymbol = self.__getSubSymbol( QgsMarkerSymbolV2, QgsSimpleMarkerSymbolLayerV2, QGis.Point, props) self.deleteProperties(props_parent, _qgis.MARKER_LINE_SYMBOL_LAYER) qgsSymbol = QgsMarkerLineSymbolLayerV2.create(props_parent) qgsSymbol.setSubSymbol(qgsSubSymbol) else: size = self.__getMsSize(msstyle, props) self.__getMarkerDisplacementAndRotate(msstyle, gap, size, props_parent) self.__getMsInitialGap(msstyle, gap, props_parent) self.__getMsAnchorpoint(msSymbol, props) qgsSubSymbol = self.__getQgsMarkerSubSymbol( type_marker, msSymbol, size, props) self.deleteProperties(props_parent, _qgis.MARKER_LINE_SYMBOL_LAYER) qgsSymbol = QgsMarkerLineSymbolLayerV2.create(props_parent) qgsSymbol.setSubSymbol(qgsSubSymbol) #print(props) return qgsSymbol
def route(self): try: import urllib.request import json origin_dest = [] featurelist = [] if self.dlg.inputpoint.isChecked(): vp_layer = self.dlg.point.currentLayer() countfeat = vp_layer.featureCount() else: vp_layer = iface.activeLayer() vp_layer.commitChanges() countfeat = vp_layer.featureCount() result = processing.run( "native:addautoincrementalfield", { 'INPUT': vp_layer, 'FIELD_NAME': 'id', 'START': 1, 'GROUP_FIELDS': [], 'SORT_EXPRESSION': '\"id\"', 'SORT_ASCENDING': True, 'SORT_NULLS_FIRST': False, 'OUTPUT': 'memory:{0}'.format(self.dlg.route_id.text()) }) QgsProject.instance().removeMapLayer(vp_layer) vp_layer = result['OUTPUT'] QgsProject.instance().addMapLayer(vp_layer) features = vp_layer.getFeatures() points = [] pointdist = [] waypoints = [] # if vp_layer.featureCount() == 2: for feature in vp_layer.getFeatures(): point = feature.geometry().asPoint() xpoint = point.x() ypoint = point.y() Qpoint = QgsPointXY(xpoint, ypoint) points.append(Qpoint) distcheck = 0 if self.dlg.direction.currentText() == 'Start->End': # for i in points: # distance = QgsDistanceArea() # Qpoint1 = i # for j in points: # Qpoint2 = j # dist = distance.measureLine(Qpoint1, Qpoint2) # pointdist.append(dist) # if dist > distcheck: # distcheck = dist self.origin = points[0] self.destination = points[countfeat - 1] # print('End->Start', self.origin, self.destination) elif self.dlg.direction.currentText() == 'End->Start': # for i in points: # distance = QgsDistanceArea() # Qpoint1 = i # for j in points: # Qpoint2 = j # dist = distance.measureLine(Qpoint1, Qpoint2) # pointdist.append(dist) # if dist > distcheck: # distcheck = dist self.origin = points[countfeat - 1] self.destination = points[0] # print('Start->End', self.origin, self.destination) # print(vp_layer.featureCount()) if vp_layer.featureCount() > 3: for i in range(countfeat - 1): if i != 0 and i != countfeat - 1: if self.dlg.direction.currentText() == 'Start->End': if len(waypoints) < 1: waypoints.append('optimize:true|via:' + str(points[i].y()) + ',' + str(points[i].x())) else: waypoints.append('via:' + str(points[i].y()) + ',' + str(points[i].x())) elif self.dlg.direction.currentText() == 'End->Start': if len(waypoints) < 1: waypoints.append( 'optimize:true|via:' + str(points[countfeat - i].y()) + ',' + str(points[countfeat - i].x())) else: waypoints.append( 'via:' + str(points[countfeat - i].y()) + ',' + str(points[countfeat - i].x())) print('|'.join(waypoints)) elif vp_layer.featureCount() == 3: for i in points: if i != self.origin and i != self.destination: waypoints.append('optimize:true|via:' + str(i.y()) + ',' + str(i.x())) else: pass # print(waypoints[0], 'waypoints') # print(distcheck, 'dist') # print(pointdist, 'pointdist') # print(origin.x(),origin.y(), destination.x(),destination.y(), 'origin_dest') # vp_layer.select(origin) # vp_layer.select(destination) for feature in vp_layer.getFeatures(): geometry = feature.geometry() origin_dest.append( {geometry.asPoint().y(), geometry.asPoint().x()}) # print(origin_dest) endpoint = 'https://maps.googleapis.com/maps/api/directions/json?' APIkey = self.dlg.api.text() # mode = 'driving' origin_str = self.origin.y(), self.origin.x() destination_str = self.destination.y(), self.destination.x() # departure_time = (self.dlg.timeEdit.time().hour()*3600 + self.dlg.timeEdit.time().minute()*60+ self.dlg.timeEdit.time().second()) # print(departure_time) import time import datetime # departure = self.totimestamp(self.dlg.timeEdit.dateTime()) if self.dlg.nowtime.isChecked(): departure = 'now' else: departure = self.dlg.timeEdit.dateTime().toSecsSinceEpoch() print(departure) if vp_layer.featureCount() > 3: if self.dlg.avoid.currentText() == 'None': nav_request = 'origin={0},{1}&destination={2},{3}&waypoints={4}&departure_time={5}&mode={6}&model={7}&key={8}'.format( self.origin.y(), self.origin.x(), self.destination.y(), self.destination.x(), '|'.join(waypoints), departure, self.dlg.mode.currentText(), self.dlg.model.currentText(), api_key) else: nav_request = 'origin={0},{1}&destination={2},{3}&waypoints={4}&departure_time={5}&avoid={6}&mode={7}&model={8}&key={9}'.format( self.origin.y(), self.origin.x(), self.destination.y(), self.destination.x(), '|'.join(waypoints), departure, self.dlg.avoid.currentText(), self.dlg.mode.currentText(), self.dlg.model.currentText(), api_key) elif vp_layer.featureCount() == 3: if self.dlg.avoid.currentText() == 'None': nav_request = 'origin={0},{1}&destination={2},{3}&waypoints={4}&departure_time={5}&mode={6}&model={7}&key={8}'.format( self.origin.y(), self.origin.x(), self.destination.y(), self.destination.x(), waypoints[0], departure, self.dlg.mode.currentText(), self.dlg.model.currentText(), api_key) else: nav_request = 'origin={0},{1}&destination={2},{3}&waypoints={4}&departure_time={5}&avoid={6}&mode={7}&model={8}&key={9}'.format( self.origin.y(), self.origin.x(), self.destination.y(), self.destination.x(), waypoints[0], departure, self.dlg.avoid.currentText(), self.dlg.mode.currentText(), self.dlg.model.currentText(), api_key) else: if self.dlg.avoid.currentText() == 'None': nav_request = 'origin={0},{1}&destination={2},{3}&departure_time={4}&mode={5}&model={6}&key={7}'.format( self.origin.y(), self.origin.x(), self.destination.y(), self.destination.x(), departure, self.dlg.mode.currentText(), self.dlg.model.currentText(), api_key) # print(nav_request) else: nav_request = 'origin={0},{1}&destination={2},{3}&departure_time{4}&avoid={5}&mode={6}&model={7}&key={8}'.format( self.origin.y(), self.origin.x(), self.destination.y(), self.destination.x(), departure, self.dlg.avoid.currentText(), self.dlg.mode.currentText(), self.dlg.model.currentText(), api_key) request = endpoint + nav_request print(request) response = urllib.request.urlopen(request).read() directions = json.loads(response) keys = directions.keys() # print(keys) # print(directions['error_message'], directions['routes']) routes = directions['routes'] legs = routes[0]['legs'] line = routes[0]['overview_polyline'] # print(routes) points = polyline.decode(line['points']) self.route_layer = QgsVectorLayer( "Point?crs=EPSG:4326&field=route_id:String(100)&field=distance:String(100)&field=time:String(100)&field=ascending/descending:String(100)&field=departure_time:String(100)&field=roads_to_avoid:String(100)&field=traffic_model:String(100)", "route_points", "memory") provider = self.route_layer.dataProvider() # QgsProject.instance().addMapLayer(self.route_layer) if len(legs[0]['duration']['text'].split(' ')) == 2: duration1 = legs[0]['duration']['text'].split(' ') print(duration1, 'dur') duration = duration1[0] else: duration1 = legs[0]['duration']['text'].split(' ') print(duration1, 'dur1') duration = str((int(duration1[0]) * 60) + int(duration1[2])) self.route_layer.startEditing() route_attrib = [ self.dlg.route_id.text(), legs[0]['distance']['text'].split(' ')[0], duration, self.dlg.direction.currentText(), (self.dlg.timeEdit.dateTime()), self.dlg.avoid.currentText(), self.dlg.model.currentText() ] # print((self.dlg.timeEdit.time())) # print(route_attrib) for i in points: outelem = QgsFeature(self.route_layer.fields()) outelem.setGeometry( QgsGeometry.fromPointXY(QgsPointXY(i[1], i[0]))) outelem.setFields(self.route_layer.fields()) outelem.setAttributes(route_attrib) featurelist.append(outelem) # print(outelem) self.route_layer.dataProvider().addFeatures(featurelist) self.route_layer.commitChanges() result = processing.run( "qgis:pointstopath", { 'INPUT': self.route_layer, 'ORDER_FIELD': 'route_id', 'GROUP_FIELD': None, 'DATE_FORMAT': '', 'OUTPUT': 'memory:' }) if not self.dlg.checkBox.isChecked(): route = QgsVectorLayer( "Linestring?crs=EPSG:4326&field=route_id:String(100)&field=distance(km):String(100)&field=time(min):String(100)&field=ascending/descending:String(100)&field=departure_time:String(100)&field=duration_in_traffic(min):String(100)&field=roads_to_avoid:String(100)&field=traffic_model:String(100)&field=no_of_nodes:String(100)", "route", "memory") else: # print(self.dlg.route_id.text(), route_attrib2) route = self.dlg.layer.currentLayer() fields = route.dataProvider().fields() field_name = [field.name() for field in fields] # line_layer = QgsVectorLayer(result['OUTPUT'], 'route') featurelist2 = [] # if self.dlg.mode.currentText() not in ['walking', 'bicycling', 'transit']: if 'duration_in_traffic' in legs[0].keys(): if len(legs[0]['duration']['text'].split(' ')) == 2: duration1 = legs[0]['duration_in_traffic']['text'].split( ' ') print(duration1, 'dur12') duration_in_traffic = duration1[0] else: duration1 = legs[0]['duration_in_traffic']['text'].split( ' ') print(duration1, 'dur13') duration_in_traffic = str((int(duration1[0]) * 60) + int(duration1[2])) if 'fid' in field_name: route_attrib2 = [ route.featureCount(), self.dlg.route_id.text(), legs[0]['distance']['text'].split(' ')[0], duration, self.dlg.direction.currentText(), (self.dlg.timeEdit.dateTime()), duration_in_traffic, self.dlg.avoid.currentText(), self.dlg.model.currentText(), str(self.route_layer.featureCount()) ] else: route_attrib2 = [ self.dlg.route_id.text(), legs[0]['distance']['text'].split(' ')[0], duration, self.dlg.direction.currentText(), (self.dlg.timeEdit.dateTime()), duration_in_traffic, self.dlg.avoid.currentText(), self.dlg.model.currentText(), str(self.route_layer.featureCount()) ] else: if 'fid' in field_name: route_attrib2 = [ route.featureCount(), self.dlg.route_id.text(), legs[0]['distance']['text'].split(' ')[0], duration, self.dlg.direction.currentText(), (self.dlg.timeEdit.dateTime()), 'None', self.dlg.avoid.currentText(), self.dlg.model.currentText(), str(self.route_layer.featureCount()) ] else: route_attrib2 = [ self.dlg.route_id.text(), legs[0]['distance']['text'].split(' ')[0], duration, self.dlg.direction.currentText(), (self.dlg.timeEdit.dateTime()), duration_in_traffic, self.dlg.avoid.currentText(), self.dlg.model.currentText(), str(self.route_layer.featureCount()) ] # print(field_name) # if 'fid' in field_name: # # route.startEditing() # # print(route.dataProvider().fieldNameIndex('fid')) # # route.dataProvider().deleteAttributes([route.dataProvider().fieldNameIndex('fid')]) # # route.updateFields() # # field_name = [field.name() for field in fields] # # print(field_name) # # route_attrib2 = [route.featureCount(), self.dlg.route_id.text(), legs[0]['distance']['text'].split(' ')[0], duration, self.dlg.direction.currentText(),(self.dlg.timeEdit.dateTime()),'None',self.dlg.avoid.currentText(), self.dlg.model.currentText(), str(self.route_layer.featureCount())] # else: # pass provider = route.dataProvider() route.startEditing() request = QgsFeatureRequest() # set order by field clause = QgsFeatureRequest.OrderByClause('route_id', ascending=False) orderby = QgsFeatureRequest.OrderBy([clause]) request.setOrderBy(orderby) fields = route.dataProvider().fields() field_name = [field.name() for field in fields] for feature in result['OUTPUT'].getFeatures(): outelem = QgsFeature(route.fields()) outelem.setGeometry(feature.geometry()) outelem.setFields(route.fields()) if 'fid' not in field_name: outelem.setAttributes(route_attrib2) else: for index, field in enumerate(field_name): if field != 'fid': print(field, route_attrib2[index]) outelem[field] = route_attrib2[index] featurelist2.append(outelem) route.dataProvider().addFeatures(featurelist2) # route.updateFeature(feature) route.commitChanges() # QgsProject.instance().addMapLayer(route) if route.featureCount() == 1: file_path = os.path.abspath( os.path.join(os.path.dirname(__file__), "route_style.qml")) route.loadNamedStyle(file_path) else: # result_del = processing.run("qgis:deletecolumn", { # 'INPUT': route, # 'COLUMN': ['gid'], 'OUTPUT': 'memory:'}) # QgsProject.instance().addMapLayer(result_del['OUTPUT']) # result = processing.run("native:addautoincrementalfield", # {'INPUT': result_del['OUTPUT'], # 'FIELD_NAME': 'gid', 'START': 1, 'GROUP_FIELDS': [], # 'SORT_EXPRESSION': '', # 'SORT_ASCENDING': False, 'SORT_NULLS_FIRST': False, 'OUTPUT': 'memory:route'}) # # QgsProject.instance().removeMapLayer(route) # route = result['OUTPUT'] QgsProject.instance().addMapLayer(route) # provide file name index and field's unique values # fni = route.dataProvider().fieldNameIndex('route_id') # unique_values = route.uniqueValues(fni) # fni2 = route.dataProvider().fieldNameIndex('route_id') # unique_values2 = route.uniqueValues(fni2) # unique_values2 = sorted(unique_values2) unique_values2 = [] unique_values = [] request = QgsFeatureRequest() # set order by field clause = QgsFeatureRequest.OrderByClause('route_id', ascending=False) orderby = QgsFeatureRequest.OrderBy([clause]) request.setOrderBy(orderby) for feature in route.getFeatures(): attrib = feature.attributes() unique_values2.append(attrib[ route.dataProvider().fieldNameIndex('route_id')]) unique_values.append(attrib[ route.dataProvider().fieldNameIndex('route_id')]) from random import randrange # fill categories categories = [] # print(unique_values) # unique_values = sorted(unique_values) print(unique_values, unique_values2) for index, unique_value in enumerate(unique_values): # initialize the default symbol for this geometry type # symbol = QgsSymbol.defaultSymbol(route.geometryType()) # symbol = QgsSymbol.Symbol().setShape(QgsSimpleMarkerSymbolLayerBase.Star # symbol.appendSymbolLayer(symbol_layer) # configure a symbol layer # sym = route.renderer().symbol() # double headed symbol = QgsSymbol.defaultSymbol(route.geometryType()) # double headed sym_layer = QgsArrowSymbolLayer.create({ "arrow_width": "1", "arrow_start_width": "1", "head_length": "1.5", "head_thickness": "1.5", "head_type": "0", "arrow_type": "0", "is_curved": "0", }) fill_sym = QgsFillSymbol.createSimple({ "color": '%d, %d, %d' % (randrange(0, 256), randrange( 0, 256), randrange(0, 256)) }) sym_layer.setSubSymbol(fill_sym) symbol.changeSymbolLayer(0, sym_layer) # layer_style = {} # layer_style['color'] = '%d, %d, %d' % (randrange(0, 256), randrange(0, 256), randrange(0, 256)) # layer_style['outline'] = '#FF0000' # # layer_style['width'] = '7.6' # symbol_layer = QgsSimpleFillSymbolLayer.create(layer_style) # replace default symbol layer with the configured one # if symbol_layer is not None: # symbol.changeSymbolLayer(0, symbol_layer) # symbol.setWidth(0.66) # create renderer object category = QgsRendererCategory(unique_value, symbol, str(unique_values2[index])) # entry for the list of category items categories.append(category) # create renderer object renderer = QgsCategorizedSymbolRenderer('route_id', categories) # assign the created renderer to the layer if renderer is not None: route.setRenderer(renderer) route.triggerRepaint() ltl = QgsProject.instance().layerTreeRoot().findLayer( route.id()) ltm = iface.layerTreeView() # ltm.sortItems(0, Qt.AscendingOrder) # view = iface.layerTreeView() # ltm.model().AllowNodeReorder() index_newfeat = ltm.model().index(0, 0) node = ltm.model().index2node(index_newfeat) nodes = ltm.model().layerLegendNodes(node) legendNodes = ltm.model().layerLegendNodes(ltl) legend_dict = {} legend_dict[node.name()] = legendNodes # print(legend_dict) ltm.setSortingEnabled(True) ltm.sortByColumn(0, Qt.DescendingOrder) for index, ln in enumerate(legendNodes): if index + 1 != route.featureCount(): ln.setData(Qt.Unchecked, Qt.CheckStateRole) # index_newfeat = ltm.model().index(route.featureCount()-1, 0) # print(index_newfeat) # node = ltm.model().index2node(index_newfeat) # print(node) # nodes = ltm.model().layerLegendNodes(node) # # layer_and_nodes[n.name()] = nodes # # print(layer_and_nodes) # # legend_get = ltm.model().index2legendNode(nodes) # print(nodes) # print(index, ln) # print(index, ltm.model().legendRootIndex(ln), ltm.model().legendNode2index(ln), ln, index_newfeat) # if index+1 != int(self.dlg.route_id.text()): # ln.setData(Qt.Checked, Qt.CheckStateRole) if not self.dlg.checkBox.isChecked(): if self.dlg.output.text() != '': path = self.dlg.output.text() QgsVectorFileWriter.writeAsVectorFormat( route, path, 'UTF-8', route.crs(), 'ESRI Shapefile') # layer = QgsProject.instance().layerTreeRoot().findLayer(route.id()) # print(layer.name()) output = self.dlg.output.text().split('/') route_path = QgsVectorLayer( path, output[len(output) - 1].split('.')[0]) QgsProject.instance().addMapLayer(route_path) else: QgsProject.instance().addMapLayer(route) listselect = [] for index, feature in enumerate(route.getFeatures()): if index + 1 == route.featureCount(): listselect.append(feature.id()) route.select(listselect) iface.actionZoomToSelected().trigger() except Exception as e: alert = QMessageBox() alert.setWindowTitle('Alert') if self.dlg.mode.currentText() in [ 'walking', 'bicycling', 'transit' ]: alert.setText( str(e) + '\nRoute not available for selected mode.') else: alert.setText(str(e)) result = alert.exec_() print(e)
def subRenderer(self, color): lineSymbol = QgsLineSymbolV2() arrowSymbol = QgsArrowSymbolLayer().create() arrowSymbol.setArrowWidth(0.0) arrowSymbol.setArrowStartWidth(0.0) arrowSymbol.setColor(color) arrowSymbol.setIsCurved(False) arrowSymbol.setIsRepeated(False) renderSetting = QgsRenderContext() renderSetting.setFlag(QgsRenderContext.Antialiasing, False) renderSetting.setFlag(QgsRenderContext.DrawSymbolBounds, False) renderSetting.setFlag(QgsRenderContext.ForceVectorOutput, False) renderSetting.setFlag(QgsRenderContext.UseAdvancedEffects, False) renderSetting.setFlag(QgsRenderContext.UseRenderingOptimization, False) arrEffectStack = arrowSymbol.paintEffect() effList = arrEffectStack.effectList() for i in range(0, len(effList)): if type(effList[i]) == QgsDrawSourceEffect: effList[i].setDrawMode(1) arrEffectStack.setEnabled(True) lineSymbol.appendSymbolLayer(arrowSymbol) return lineSymbol
def test_subsymbol(self): """ Test rendering a generator in a subsymbol of another symbol """ sym = QgsLineSymbol() arrow = QgsArrowSymbolLayer() arrow.setIsRepeated(False) arrow.setArrowStartWidth(10) arrow.setArrowWidth(5) arrow.setHeadLength(20) arrow.setHeadThickness(10) sym.changeSymbolLayer(0, arrow) self.lines_layer.renderer().setSymbol(sym) # here "$geometry" must refer to the created ARROW shape, NOT the original feature line geometry! generator_layer = QgsGeometryGeneratorSymbolLayer.create( {'geometryModifier': 'buffer($geometry, 3)'}) generator_layer.setSymbolType(QgsSymbol.Fill) generator_layer.setUnits(QgsUnitTypes.RenderMillimeters) self.assertIsNotNone(generator_layer.subSymbol()) generator_layer.subSymbol().symbolLayer(0).setColor( QColor(255, 255, 255)) generator_layer.subSymbol().symbolLayer(0).setStrokeColor( QColor(0, 0, 0)) generator_layer.subSymbol().symbolLayer(0).setStrokeWidth(2) sub_symbol = QgsFillSymbol() sub_symbol.changeSymbolLayer(0, generator_layer) arrow.setSubSymbol(sub_symbol) rendered_layers = [self.lines_layer] self.mapsettings.setLayers(rendered_layers) renderchecker = QgsMultiRenderChecker() renderchecker.setMapSettings(self.mapsettings) renderchecker.setControlName('expected_geometrygenerator_subsymbol') res = renderchecker.runTest('geometrygenerator_subsymbol') self.report += renderchecker.report() self.assertTrue(res)