示例#1
0
def spaceBarPressed():
    global myIt, activeLayerId
    aLayer = iface.activeLayer()
    if not aLayer or not aLayer.type() == QgsMapLayer.VectorLayer:
        iface.messageBar().pushInfo(
            "Feature iterator",
            "First select a vector layer in the layers panel.")
        return
    if activeLayerId != aLayer.id():
        activeLayerId = aLayer.id()
        myIt = None
    if not myIt:
        request = QgsFeatureRequest().setFlags(
            QgsFeatureRequest.NoGeometry).setNoAttributes()
        myIt = aLayer.getFeatures(request)

    feat = next(myIt, None)
    if feat:
        aLayer.selectByIds([feat.id()])
        if aLayer.geometryType() == QgsWkbTypes.PointGeometry:
            iface.actionPanToSelected().trigger()  # Pan to points
        else:
            iface.actionZoomToSelected().trigger()  # Zoom to the rest
    else:
        iface.messageBar().pushInfo("Feature iterator",
            "We reached the last feature of this layer already.\n" + \
            "If you want to restart press the Escape key.")
示例#2
0
    def zoomtosel( self ): 
        codcom =""  
        fpath =os.getenv("HOME")+'/.qgis2/python/plugins/Cxf_in/CTCOMCAT.txt'
        in_file = open(fpath,"r")        
        testo= in_file.readlines()
        comune=""   
        if (self.ui.cat_com.currentText()) !=comune:   
           for ctcom in testo:
                line=ctcom.split(",")
                
                if line[3].strip()==self.ui.cat_com.currentText():
                      print line[0].strip()
                      codcom=line[0].strip() 
        layer = QgsMapLayerRegistry.instance().mapLayersByName("Particelle") [0] 
        iface.setActiveLayer(layer) 
        iter= layer.getFeatures()
        nfile = layer.fieldNameIndex('Nomefile')
        map = layer.fieldNameIndex('Mappale')
        layer.removeSelection ()
        foglio=codcom+"_"+self.ui.cat_fg.currentText().replace ('_','')
 
  
        for feature in iter:

         if feature.attributes()[nfile]==codcom+"_"+self.ui.cat_fg.currentText().replace ('_','') and feature.attributes()[map]==self.ui.cat_mapp.currentText() :
           

           layer.select( feature.id())
           iface.actionZoomToSelected().trigger() 
 def zoomin(self):
     print('wykonano zoom')
     filtr = ("\"id\" ={}").format(self.r1[0])
     print(filtr)
     self.layer = iface.activeLayer()
     print(self.layer.name())
     self.layer.selectByExpression(filtr)
     iface.actionZoomToSelected().trigger()
示例#4
0
 def zoomToFeature(self, layerId, layerSchema, layerName):
     loadedLayers = core.QgsProject.instance().mapLayers().values()
     for layer in loadedLayers:
         if not (layer.dataProvider().uri().schema() == layerSchema
                 and layer.dataProvider().uri().table() == layerName):
             continue
         layer.select(int(layerId))
         iface.actionZoomToSelected().trigger()
         break
    def siguiente(self):
        global contenidoleidob
        global orden
        global layer
        print("entro en la funcion")
            

        elem=contenidoleidob[orden]
        elem=elem.replace('[','')
        elem=elem.replace(']','')
        elem=elem.replace("'","")
        print(elem)
        elem=elem.split(',')
       
        
        print(elem)
        elm=elem[0]
        print(elm)
        codigovia=elem[1]
        

        
        



        """from PyQt5.QtWidgets import QInputDialog
        def getTextInput(title, message):
            answer = QInputDialog.getText(None, title, message)
            if answer[1]:
                print(answer[0])
                return answer[0]
            else:
                return None
        sigo=getTextInput("COntinuamos", " escribe un '1'")"""
        #si ya existe lo va mirando secuancialmente esperando a que el usuario toque una tecla determinada
       

        miexpresion="\"ANEXO_JV\" = '{}' ".format(elm)+" AND \"CLASIFICAC\" = 'SI' AND \"TIPO\" = 'EJE' AND \"COD_VIA\" = '{}'".format(codigovia)

        layer.selectByExpression(miexpresion,QgsVectorLayer.SetSelection)
        #selection = layer.selectByExpression("\"C_POLIGONO\" = {} ".format(pol)+" AND \"C_PARCELA\" = {}".format(par),QgsVectorLayer.SetSelection)
            
        print(miexpresion)
        selection = layer.selectedFeatures()
        
        self.dlg.labelSelecionados.setText(str(len(selection)))
        iface.actionZoomToSelected().trigger()
        
        orden=int(orden) + 1
        print (orden)
示例#6
0
def spaceBarPressed():
    global myIt, activeLayerId
    aLayer = iface.activeLayer()
    if not aLayer or not aLayer.type() == 0:
        print("Please first select a vector layer in the ToC.")
        return
    if activeLayerId != aLayer.id():
        activeLayerId = aLayer.id()
        myIt = None
    if not myIt:
        myIt = aLayer.getFeatures()

    feat = next(myIt, None)
    if feat:
        aLayer.removeSelection()
        aLayer.select(feat.id())
        iface.actionZoomToSelected().trigger()
        print("Selected feature:", str(feat.id()))
    else:
        print ("We reached the last feature of this layer already.\n" + \
            "If you want to restart press the Escape key.")
示例#7
0
 def select_and_zoom_on_section_of_count(self, count_id):
     sections = self.get_sections_of_count(count_id)
     layer = self.layers['section']
     layer.selectByIds([x.id() for x in sections])
     iface.setActiveLayer(layer)
     iface.actionZoomToSelected().trigger()
示例#8
0
    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)
示例#9
0
def zoom_to_selected(layer):
    a = iface.activeLayer()
    iface.setActiveLayer(layer)
    iface.actionZoomToSelected().trigger()
    iface.setActiveLayer(a)