Ejemplo n.º 1
0
    def close_project(self, project=None):
        """
        Close the current open project
        """
        if not project is None and not project == self.project:
            return

        self.tracking.clear_logging()
        self.dataentrywidget.clear()
        self.canvas_page.cleanup()
        QgsMapLayerRegistry.instance().removeAllMapLayers()
        for panel in self.panels:
            self.removeDockWidget(panel)
            del panel
            # Remove all the old buttons

        self.panels = []
        oldproject = self.project
        self.project = None
        self.set_projectbuttons(False)
        self.hidedataentry()
        self.infodock.close()
        RoamEvents.selectioncleared.emit()
        RoamEvents.projectClosed.emit(oldproject)
        self.projectwidget.set_open_project(None)
    def __init__(self, methodName):
        """Run once on class initialisation."""
        unittest.TestCase.__init__(self, methodName)
        myPath = os.path.join(TEST_DATA_DIR, 'landsat.tif')
        rasterFileInfo = QFileInfo(myPath)
        mRasterLayer = QgsRasterLayer(rasterFileInfo.filePath(),
                                      rasterFileInfo.completeBaseName())
        rasterRenderer = QgsMultiBandColorRenderer(
            mRasterLayer.dataProvider(), 2, 3, 4)
        mRasterLayer.setRenderer(rasterRenderer)
        #pipe = mRasterLayer.pipe()
        #assert pipe.set(rasterRenderer), 'Cannot set pipe renderer'
        QgsMapLayerRegistry.instance().addMapLayers([mRasterLayer])

        # create composition with composer map
        self.mMapRenderer = QgsMapRenderer()
        layerStringList = QStringList()
        layerStringList.append(mRasterLayer.id())
        self.mMapRenderer.setLayerSet(layerStringList)
        self.mMapRenderer.setProjectionsEnabled(False)
        self.mComposition = QgsComposition(self.mMapRenderer)
        self.mComposition.setPaperSize(297, 210)
        self.mComposerMap = QgsComposerMap(self.mComposition, 20, 20, 200, 100)
        self.mComposerMap.setFrameEnabled(True)
        self.mComposition.addComposerMap(self.mComposerMap)
Ejemplo n.º 3
0
    def testStringWithMaxLen(self):
        """ tests that text edit wrappers correctly handle string fields with a maximum length """
        layer = QgsVectorLayer("none?field=fldint:integer", "layer", "memory")
        assert layer.isValid()
        layer.dataProvider().addAttributes([QgsField('max', QVariant.String, 'string', 10),
                                            QgsField('nomax', QVariant.String, 'string', 0)])
        layer.updateFields()
        QgsMapLayerRegistry.instance().addMapLayer(layer)

        reg = QgsEditorWidgetRegistry.instance()
        config = {'IsMultiline': 'True'}

        # first test for field without character limit
        editor = QTextEdit()
        editor.setPlainText('this_is_a_long_string')
        w = reg.create('TextEdit', layer, 2, config, editor, None)
        self.assertEqual(w.value(), 'this_is_a_long_string')

        # next test for field with character limit
        editor = QTextEdit()
        editor.setPlainText('this_is_a_long_string')
        w = reg.create('TextEdit', layer, 1, config, editor, None)

        self.assertEqual(w.value(), 'this_is_a_')

        QgsMapLayerRegistry.instance().removeAllMapLayers()
Ejemplo n.º 4
0
    def create_layer(self, data):
        display_name = 'some-layer'
        uri = 'Point?crs=epsg:4326&index=yes&uuid=%s' % uuid.uuid4()
        vlayer = QgsVectorLayer(uri, display_name, 'memory')
        QgsMapLayerRegistry.instance().addMapLayer(vlayer)

        provider = vlayer.dataProvider()
        vlayer.startEditing()
        provider.addAttributes([
            QgsField('population_density', QtCore.QVariant.Double),
        ])
        features = []
        for x, y, density in data:
            feat = QgsFeature()
            geom = QgsGeometry.fromPoint(QgsPoint(x, y))
            feat.setGeometry(geom)
            feat.setAttributes([density])
            features.append(feat)
        provider.addFeatures(features)
        vlayer.commitChanges()

        vlayer.updateExtents()
        self.canvas.setExtent(vlayer.extent())
        cl = QgsMapCanvasLayer(vlayer)
        self.canvas.setLayerSet([cl])
        vlayer.triggerRepaint()
Ejemplo n.º 5
0
    def test_ValueMap_representValue(self):
        layer = QgsVectorLayer("none?field=number1:integer&field=number2:double&field=text1:string&field=number3:integer&field=number4:double&field=text2:string",
                               "layer", "memory")
        assert layer.isValid()
        QgsMapLayerRegistry.instance().addMapLayer(layer)
        f = QgsFeature()
        f.setAttributes([2, 2.5, 'NULL', None, None, None])
        assert layer.dataProvider().addFeatures([f])
        reg = QgsEditorWidgetRegistry.instance()
        factory = reg.factory("ValueMap")
        self.assertIsNotNone(factory)

        # Tests with different value types occurring in the value map
        config = {'two': '2', 'twoandhalf': '2.5', 'NULL text': 'NULL',
                  'nothing': self.VALUEMAP_NULL_TEXT}
        self.assertEqual(factory.representValue(layer, 0, config, None, 2), 'two')
        self.assertEqual(factory.representValue(layer, 1, config, None, 2.5), 'twoandhalf')
        self.assertEqual(factory.representValue(layer, 2, config, None, 'NULL'), 'NULL text')
        # Tests with null values of different types, if value map contains null
        self.assertEqual(factory.representValue(layer, 3, config, None, None), 'nothing')
        self.assertEqual(factory.representValue(layer, 4, config, None, None), 'nothing')
        self.assertEqual(factory.representValue(layer, 5, config, None, None), 'nothing')
        # Tests with fallback display for different value types
        config = {}
        self.assertEqual(factory.representValue(layer, 0, config, None, 2), '(2)')
        self.assertEqual(factory.representValue(layer, 1, config, None, 2.5), '(2.50000)')
        self.assertEqual(factory.representValue(layer, 2, config, None, 'NULL'), '(NULL)')
        # Tests with fallback display for null in different types of fields
        self.assertEqual(factory.representValue(layer, 3, config, None, None), '(NULL)')
        self.assertEqual(factory.representValue(layer, 4, config, None, None), '(NULL)')
        self.assertEqual(factory.representValue(layer, 5, config, None, None), '(NULL)')

        QgsMapLayerRegistry.instance().removeAllMapLayers()
Ejemplo n.º 6
0
def show_qgis_layer(layer):
    """Show a QGIS layer in the map canvas.

    :param layer: The layer to show.
    :type layer: QgsMapLayer
    """
    QgsMapLayerRegistry.instance().addMapLayer(layer)
Ejemplo n.º 7
0
 def accept(self):
     input_path = str(self.leInputPath.text())
     output_path = str(self.leOutputPath.text())
     if not output_path.endswith('.tif'):
         QMessageBox.warning(
             self.parent, self.tr('InaSAFE'),
             (self.tr('Output file name must be tif file')))
     if not os.path.exists(input_path):
         QMessageBox.warning(
             self.parent, self.tr('InaSAFE'),
             (self.tr('Input file is not exist')))
         return
     my_algorithm = str(self.cboAlgorithm.currentText()).lower()
     fileName = convert_mmi_data(input_path, output_path,
                                 the_algorithm=my_algorithm,
                                 algorithm_name=False)
     if self.cBLoadLayer.isChecked():
         fileInfo = QFileInfo(fileName)
         baseName = fileInfo.baseName()
         my_raster_layer = QgsRasterLayer(fileName, baseName)
         if not my_raster_layer.isValid():
             LOGGER.debug("Failed to load")
         else:
             QgsMapLayerRegistry.instance().addMapLayer(my_raster_layer)
     self.done(self.Accepted)
     if not self.test_mode:
         QMessageBox.warning(
             self.parent, self.tr('InaSAFE'),
             (self.tr('Success to convert %1 to %2').
              arg(input_path).arg(output_path)))
 def _layerRemoved(self, layerId):
     if self._layerId and layerId == self._layerId:
         self._layerId = ''
         self.setEnabled(False)
         QgsProject.instance().snapSettingsChanged.disconnect(self._refresh)
         QgsMapLayerRegistry.instance().layerRemoved.disconnect(self._layerRemoved)
         self.snappingEnabledChanged.disconnect(QgsProject.instance().snapSettingsChanged)
Ejemplo n.º 9
0
 def finishInit(self):
     # connect signal for layers and populate combobox
     QgsMapLayerRegistry.instance().layersAdded.connect(self.__canvasLayersChanged)
     QgsMapLayerRegistry.instance().layersRemoved.connect(self.__canvasLayersChanged)
     if self.options.groupLayers:
         self.options.legendInterface.groupRelationsChanged.connect(self.__canvasLayersChanged)
     self.__canvasLayersChanged()
Ejemplo n.º 10
0
    def testNoSliverPolygons(self):

        # create a layer with some polygons that will be used as a source for "avoid intersections"
        l = QgsVectorLayer('MultiPolygon', 'test_layer', 'memory')
        assert l.isValid()
        QgsMapLayerRegistry.instance().addMapLayer(l)
        QgsProject.instance().writeEntry("Digitizing", "/AvoidIntersectionsList", [l.id()])

        features = []
        for i, wkt in enumerate(feat_wkt):
            f = QgsFeature(i + 1)
            f.setGeometry(QgsGeometry.fromWkt(wkt))
            features.append(f)

        l.dataProvider().addFeatures(features)
        assert l.pendingFeatureCount() == 7

        # create a geometry and remove its intersections with other geometries

        g = QgsGeometry.fromWkt(newg_wkt)
        assert g.avoidIntersections() == 0

        # the resulting multi-polygon must have exactly three parts
        # (in QGIS 2.0 it has one more tiny part that appears at the border between two of the original polygons)
        mpg = g.asMultiPolygon()
        assert len(mpg) == 3
    def __init__(self, snapLayer, parent=None):
        super(LayerSnappingEnabledAction, self).__init__(parent)

        self._layerId = ''
        self._iface = None  # QgisInteface

        if isinstance(snapLayer, QgisInterface):
            self._iface = snapLayer
        elif isinstance(snapLayer, QgsVectorLayer):
            self._layerId = snapLayer.id()
        elif isinstance(snapLayer, str) or isinstance(snapLayer, unicode):
            self._layerId = snapLayer

        self.setCheckable(True)
        self.setText('Toggle Layer Snapping')
        self.setStatusTip('Toggle snapping on this layer')
        self.setIcon(QIcon(':/plugins/ark/snapEnable.png'))

        self._refresh()
        self.triggered.connect(self._triggered)

        # Make sure we catch changes in the main snapping dialog
        QgsProject.instance().snapSettingsChanged.connect(self._refresh)
        # If using current layer, make sure we update when it changes
        if self._iface:
            self._iface.legendInterface().currentLayerChanged.connect(self._refresh)
        # If the layer is removed then disable the button
        QgsMapLayerRegistry.instance().layerRemoved.connect(self._layerRemoved)
        # If we change the settings, make such others are told
        self.snappingEnabledChanged.connect(QgsProject.instance().snapSettingsChanged)
Ejemplo n.º 12
0
    def accept(self):
        """Process the layer and field and generate a new layer.

        .. note:: This is called on ok click.

        """
        myIndex = self.cboFields.currentIndex()
        myFieldName = self.cboFields.itemData(
            myIndex, QtCore.Qt.UserRole).toString()

        myIndex = self.cboPolygonLayers.currentIndex()
        myLayerId = self.cboPolygonLayers.itemData(
            myIndex, QtCore.Qt.UserRole).toString()
        myLayer = QgsMapLayerRegistry.instance().mapLayer(myLayerId)

        myFileName = str(myLayer.source())

        myInputLayer = safe_read_layer(myFileName)

        try:
            myOutputLayer = self.minimum_needs(myInputLayer, str(myFieldName))
        except ValueError:
            return

        myNewFile = myFileName[:-4] + '_perka7' + '.shp'

        myOutputLayer.write_to_file(myNewFile)

        myNewLayer = QgsVectorLayer(myNewFile, 'Minimum Needs', 'ogr')
        QgsMapLayerRegistry.instance().addMapLayers([myNewLayer])
        self.done(QtGui.QDialog.Accepted)
Ejemplo n.º 13
0
def add_qgis_raser_layer(raster_layer, canvas, bands = None):
    index_group = TerreImageConstant().index_group
    logger.debug("index_group: " + str(index_group))

    if bands:
        if raster_layer.rasterType() == 2:
            logger.debug(bands)
            pir = bands['pir']
            red = bands['red']
            green = bands['green']
            logger.debug('pir: ' + str(pir))
            logger.debug("red: " + str(red))
            logger.debug("green: " + str(green))
            if pir and red and green:
                renderer = raster_layer.renderer()
                # raster_layer.setDrawingStyle("MultiBandColor")
                renderer.setRedBand(pir)
                renderer.setGreenBand(red)
                renderer.setBlueBand(green)
                # raster_layer.setRenderer( renderer )
            # contrastForRasters( raster_layer, 0, 0, [pir, red, green] )
            histogram_stretching(raster_layer, canvas)

    QgsMapLayerRegistry.instance().addMapLayer(raster_layer)
    TerreImageConstant().legendInterface.moveLayer(raster_layer, index_group)
Ejemplo n.º 14
0
    def test_cboAggregationToggle(self):
        """Aggregation Combobox toggles on and off as expected."""

        # With aggregation layer
        myResult, myMessage = setup_scenario(
            DOCK,
            hazard='A flood in Jakarta like in 2007',
            exposure='People',
            function='Need evacuation',
            function_id='Flood Evacuation Function',
            aggregation_layer='kabupaten jakarta singlepart',
            aggregation_enabled_flag=True)
        myMessage += ' when an aggregation layer is defined.'
        assert myResult, myMessage

        # With no aggregation layer
        myLayer = DOCK.get_aggregation_layer()
        myId = myLayer.id()
        QgsMapLayerRegistry.instance().removeMapLayer(myId)
        myResult, myMessage = setup_scenario(
            DOCK,
            hazard='A flood in Jakarta like in 2007',
            exposure='People',
            function='Need evacuation',
            function_id='Flood Evacuation Function',
            aggregation_enabled_flag=False)
        myMessage += ' when no aggregation layer is defined.'
        assert myResult, myMessage
Ejemplo n.º 15
0
def loadLayers(theLayerList, theClearFlag=True, DIR=TESTDATA):
    """Helper function to load layers as defined in a python list."""
    # First unload any layers that may already be loaded
    if theClearFlag:
        for myLayer in QgsMapLayerRegistry.instance().mapLayers():
            QgsMapLayerRegistry.instance().removeMapLayer(myLayer)

    # Now go ahead and load our layers
    myExposureLayerCount = 0
    myHazardLayerCount = 0
    myCanvasLayers = []

    # Now create our new layers
    for myFile in theLayerList:

        myLayer, myType = loadLayer(myFile, DIR)
        if myType == 'hazard':
            myHazardLayerCount += 1
        elif myType == 'exposure':
            myExposureLayerCount += 1
        # Add layer to the registry (that QGis knows about)
        QgsMapLayerRegistry.instance().addMapLayer(myLayer)

        # Create Map Canvas Layer Instance and add to list
        myCanvasLayers.append(QgsMapCanvasLayer(myLayer))

    # Quickly add any existing CANVAS layers to our list first
    for myLayer in CANVAS.layers():
        myCanvasLayers.append(QgsMapCanvasLayer(myLayer))
    # now load all these layers in the CANVAS
    CANVAS.setLayerSet(myCanvasLayers)
    DOCK.getLayers()

    # Add MCL's to the CANVAS
    return myHazardLayerCount, myExposureLayerCount
Ejemplo n.º 16
0
def load_table_layers(config_collection):
    """
    In order to be able to use attribute tables in the composition, the
    corresponding vector layers need to be added to the layer
    registry. This method creates vector layers from the linked tables
    in the configuration items. This is required prior to creating the
    composition from file.
    :param config_collection: Table configuration collection built from
    the template file.
    :type config_collection: TableConfigurationCollection
    :returns: Valid layers that have been successfully added to the
    registry.
    :rtype: list
    """
    table_configs = config_collection.items().values()

    v_layers = []

    for conf in table_configs:
        layer_name = conf.linked_table()
        v_layer = vector_layer(layer_name)

        if v_layer is None:
            return

        if not v_layer.isValid():
            return

        v_layers.append(v_layer)

    QgsMapLayerRegistry.instance().addMapLayers(v_layers, False)

    return v_layers
Ejemplo n.º 17
0
    def test_geometryTypes(self):

        geo = [(1, "POINT", "(0 0)"),
               (2, "LINESTRING", "(0 0,1 0)"),
               (3, "POLYGON", "((0 0,1 0,1 1,0 0))"),
               (4, "MULTIPOINT", "((1 1))"),
               (5, "MULTILINESTRING", "((0 0,1 0),(0 1,1 1))"),
               (6, "MULTIPOLYGON", "(((0 0,1 0,1 1,0 0)),((2 2,3 0,3 3,2 2)))")]
        for wkb_type, wkt_type, wkt in geo:
            l = QgsVectorLayer("%s?crs=epsg:4326" % wkt_type, "m1", "memory", False)
            self.assertEqual(l.isValid(), True)
            QgsMapLayerRegistry.instance().addMapLayer(l)

            f1 = QgsFeature(1)
            g = QgsGeometry.fromWkt(wkt_type + wkt)
            self.assertEqual(g is None, False)
            f1.setGeometry(g)
            l.dataProvider().addFeatures([f1])

            l2 = QgsVectorLayer("?layer_ref=%s" % l.id(), "vtab", "virtual", False)
            self.assertEqual(l2.isValid(), True)
            self.assertEqual(l2.dataProvider().featureCount(), 1)
            self.assertEqual(l2.dataProvider().wkbType(), wkb_type)

            QgsMapLayerRegistry.instance().removeMapLayer(l.id())
Ejemplo n.º 18
0
    def accept(self):
        """Process the layer and field and generate a new layer.

        .. note:: This is called on OK click.

        """
        index = self.cboFields.currentIndex()
        field_name = self.cboFields.itemData(
            index, QtCore.Qt.UserRole)

        index = self.cboPolygonLayers.currentIndex()
        layer_id = self.cboPolygonLayers.itemData(
            index, QtCore.Qt.UserRole)
        # noinspection PyArgumentList
        layer = QgsMapLayerRegistry.instance().mapLayer(layer_id)

        file_name = layer.source()

        input_layer = safe_read_layer(file_name)

        try:
            output_layer = self.minimum_needs(input_layer, field_name)
        except ValueError:
            return

        new_file = file_name[:-4] + '_perka7' + '.shp'

        output_layer.write_to_file(new_file)

        new_layer = QgsVectorLayer(new_file, 'Minimum Needs', 'ogr')
        # noinspection PyArgumentList
        QgsMapLayerRegistry.instance().addMapLayers([new_layer])
        self.done(QtGui.QDialog.Accepted)
Ejemplo n.º 19
0
    def __init__(self, iface, parent = None):
        """Constructor."""
        super(CalcContour, self).__init__(parent)
        # Set up the user interface from Designer.
        # After setupUI you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect
        self.setupUi(self)
        
        self.iface = iface

        #insert layers into the combobox
        self.populateLayers()

        #instance of the QgsMapTool derived class (line tool)
        self.tool = DsgLineTool(self.iface.mapCanvas())
        self.tool.lineCreated.connect(self.updateLayer)

        #instance of the class responsible to update layer features
        self.contourTool = ContourTool()

        #Connecting slot to deal with adition/removal of layers
        QgsMapLayerRegistry.instance().layersAdded.connect(self.addLayers)
        QgsMapLayerRegistry.instance().layersRemoved.connect(self.populateLayers)
Ejemplo n.º 20
0
    def __init__(self, parent=None, iface=None):
        QTabWidget.__init__(self, parent)
        self.setupUi(self)

        self._notif_bar = None
        self._ol_loaded = False
        self._overlay_layer = None
        self.sel_highlight = None
        self.memory_layer = None
        self._db_session = STDMDb.instance().session

        self.set_iface(iface)

        #Web config
        self._web_spatial_loader = WebSpatialLoader(self.spatial_web_view, self)

        #Connect signals
        self._web_spatial_loader.loadError.connect(self.on_spatial_browser_error)
        self._web_spatial_loader.loadProgress.connect(self.on_spatial_browser_loading)
        self._web_spatial_loader.loadFinished.connect(self.on_spatial_browser_finished)
        self._web_spatial_loader.zoomChanged.connect(self.on_map_zoom_level_changed)
        self.rbGMaps.toggled.connect(self.on_load_GMaps)
        self.rbOSM.toggled.connect(self.on_load_OSM)
        self.zoomSlider.sliderReleased.connect(self.on_zoom_changed)
        self.btnResetMap.clicked.connect(self.on_reset_web_map)
        self.btnSync.clicked.connect(self.on_sync_extents)
        QgsMapLayerRegistry.instance().layersWillBeRemoved.connect(self._on_overlay_to_be_removed)
Ejemplo n.º 21
0
def add_layer_to_canvas(layer, name, impact_function):
    """Helper method to add layer to QGIS.

    :param layer: The layer.
    :type layer: QgsMapLayer

    :param name: Layer name.
    :type name: str

    :param impact_function: The impact function used.
    :type impact_function: ImpactFunction

    :param iface: QGIS QGisAppInterface instance.
    :type iface: QGisAppInterface
    """
    group_name = impact_function.name

    # noinspection PyArgumentList
    root = QgsProject.instance().layerTreeRoot()
    group_analysis = root.findGroup(group_name)
    group_analysis.setVisible(Qt.Checked)

    layer.setLayerName(name)

    QgsMapLayerRegistry.instance().addMapLayer(layer, False)
    layer_node = group_analysis.addLayer(layer)

    layer_node.setVisible(Qt.Checked)
 def tearDown(self):
     """Destroy the dialog after each test."""
     # Clear all the loaded layers in Map Registry
     # noinspection PyArgumentList,PyUnresolvedReferences
     for layer in QgsMapLayerRegistry.instance().mapLayers():
         # noinspection PyArgumentList,PyUnresolvedReferences
         QgsMapLayerRegistry.instance().removeMapLayer(layer)
Ejemplo n.º 23
0
    def prepare_ordered_marker(self, coords, idx):
        """
        Try to display nice marker on a point layer, showing the order of
        the path computed by OSRM.
        """
        self.tsp_marker_lr = QgsVectorLayer(
            "Point?crs=epsg:4326&field=id:integer"
            "&field=TSP_nb:integer(20)&field=Origin_nb:integer(20)",
            "tsp_markers_osrm{}".format(self.nb_route), "memory")
        symbol = QgsSymbolV2.defaultSymbol(self.tsp_marker_lr.geometryType())
        symbol.setSize(4.5)
        symbol.setColor(QtGui.QColor("yellow"))

        ordered_pts = \
            [coords[i["waypoint_index"]] for i in self.parsed['waypoints']]
        print("ordered_pts : ", ordered_pts)

        features = []
        for nb, pt in enumerate(ordered_pts):
            ft = QgsFeature()
            ft.setGeometry(QgsGeometry.fromPoint(QgsPoint(pt)))
            ft.setAttributes([nb, nb + 1, coords.index(pt)])
            features.append(ft)
        self.tsp_marker_lr.dataProvider().addFeatures(features)

        pal_lyr = QgsPalLayerSettings()
        pal_lyr.readFromLayer(self.tsp_marker_lr)
        pal_lyr.enabled = True
        pal_lyr.fieldName = 'TSP_nb'
        pal_lyr.placement= QgsPalLayerSettings.OverPoint
        pal_lyr.setDataDefinedProperty(QgsPalLayerSettings.Size,True,True,'12','')
        pal_lyr.writeToLayer(self.tsp_marker_lr)

        self.tsp_marker_lr.setRendererV2(QgsSingleSymbolRendererV2(symbol))
        QgsMapLayerRegistry.instance().addMapLayer(self.tsp_marker_lr)
Ejemplo n.º 24
0
    def Xtest_print_impact_table(self):
        """Test print impact table to pdf."""
        impact_layer_path = test_data_path(
            'impact', 'population_affected_entire_area.shp')
        layer, _ = load_layer(impact_layer_path)
        # noinspection PyUnresolvedReferences,PyArgumentList
        QgsMapLayerRegistry.instance().addMapLayer(layer)
        # noinspection PyCallingNonCallable
        rect = QgsRectangle(106.8194, -6.2108, 106.8201, -6.1964)
        CANVAS.setExtent(rect)
        CANVAS.refresh()

        template = resources_path(
            'qgis-composer-templates', 'a4-portrait-blue.qpt')
        report = ImpactReport(IFACE, template, layer)
        report.template = template  # just to cover set template
        out_path = unique_filename(
            prefix='test_print_impact_table',
            suffix='.pdf',
            dir=temp_dir('test'))
        report.print_impact_table(out_path)

        # Check the file exists
        message = 'Rendered output does not exist: %s' % out_path
        self.assertTrue(os.path.exists(out_path), message)

        # Check the file is not corrupt
        message = 'The output file %s is corrupt' % out_path
        out_size = os.stat(out_path).st_size
        self.assertTrue(out_size > 0, message)
Ejemplo n.º 25
0
 def return_batch_route(self, features):
     """Save and/or display the routes retrieved"""
     osrm_batch_route_layer = QgsVectorLayer(
         "Linestring?crs=epsg:4326&field=id:integer"
         "&field=total_time:integer(20)&field=distance:integer(20)",
         "routes_osrm{}".format(self.nb_done), "memory")
     provider = osrm_batch_route_layer.dataProvider()
     provider.addFeatures(features)
     QgsMapLayerRegistry.instance().addMapLayer(osrm_batch_route_layer)
     if self.filename:
         error = QgsVectorFileWriter.writeAsVectorFormat(
             osrm_batch_route_layer, self.filename,
             self.encoding, None, "ESRI Shapefile")
         if error != QgsVectorFileWriter.NoError:
             self.iface.messageBar().pushMessage(
                 "Error",
                 "Can't save the result into {} - Output have been "
                 "added to the canvas (see QGis log for error trace"
                 "back)".format(self.filename), duration=10)
             QgsMessageLog.logMessage(
                 'OSRM-plugin error report :\n {}'.format(error),
                 level=QgsMessageLog.WARNING)
             self.iface.setActiveLayer(osrm_batch_route_layer)
             return -1
         else:
             QtGui.QMessageBox.information(
                 self.iface.mainWindow(), 'Info',
                 "Result saved in {}".format(self.filename))
     if self.check_add_layer.isChecked():
         self.iface.setActiveLayer(osrm_batch_route_layer)
     else:
         QgsMapLayerRegistry.instance().removeMapLayer(
             osrm_batch_route_layer.id())
     self.iface.messageBar().clearWidgets()
Ejemplo n.º 26
0
    def testRenderMarkerLayerDataDefined(self):
        """ test that rendering a marker symbol with data defined enabled layer works"""

        points_shp = os.path.join(TEST_DATA_DIR, 'points.shp')
        points_layer = QgsVectorLayer(points_shp, 'Points', 'ogr')
        QgsMapLayerRegistry.instance().addMapLayer(points_layer)

        layer = QgsSimpleMarkerSymbolLayer()
        layer.setDataDefinedProperty("enabled", QgsDataDefined("Class='Biplane'"))
        layer.setColor(QColor(100, 150, 150))
        layer.setSize(5)
        layer.setOutlineStyle(Qt.NoPen)

        symbol = QgsMarkerSymbol()
        symbol.changeSymbolLayer(0, layer)
        points_layer.setRenderer(QgsSingleSymbolRenderer(symbol))

        ms = QgsMapSettings()
        ms.setOutputSize(QSize(400, 400))
        ms.setOutputDpi(96)
        ms.setExtent(QgsRectangle(-133, 22, -70, 52))
        ms.setLayers([points_layer.id()])

        renderchecker = QgsMultiRenderChecker()
        renderchecker.setMapSettings(ms)
        renderchecker.setControlPathPrefix('symbol_layer')
        renderchecker.setControlName('expected_markerlayer_ddenabled')
        self.assertTrue(renderchecker.runTest('markerlayer_ddenabled'))
        QgsMapLayerRegistry.instance().removeMapLayer(points_layer)
 def createLayers(self):
     types = [("Point", ptOursStyle, ptTheirsStyle),
               ("LineString", lineOursStyle, lineTheirsStyle),
               ("Polygon", polygonOursStyle, polygonTheirsStyle)]
     if self.oursgeom is not None:
         geomtype = types[int(self.oursgeom.type())][0]
         style = types[int(self.oursgeom.type())][1]
         self.oursLayer = loadLayerNoCrsDialog(geomtype + "?crs=EPSG:4326", "ours", "memory")
         pr = self.oursLayer.dataProvider()
         feat = QgsFeature()
         feat.setGeometry(self.oursgeom)
         pr.addFeatures([feat])
         self.oursLayer.loadNamedStyle(style)
         self.oursLayer.updateExtents()
         QgsMapLayerRegistry.instance().addMapLayer(self.oursLayer, False)
     else:
         self.oursLayer = None
     if self.theirsgeom is not None:
         geomtype = types[int(self.theirsgeom.type())][0]
         style = types[int(self.theirsgeom.type())][2]
         self.theirsLayer = loadLayerNoCrsDialog(geomtype + "?crs=EPSG:4326", "theirs", "memory")
         pr = self.theirsLayer.dataProvider()
         feat = QgsFeature()
         feat.setGeometry(self.theirsgeom)
         pr.addFeatures([feat])
         self.theirsLayer.loadNamedStyle(style)
         self.theirsLayer.updateExtents()
         QgsMapLayerRegistry.instance().addMapLayer(self.theirsLayer, False)
     else:
         self.theirsLayer = None
Ejemplo n.º 28
0
    def test_add_layer_to_registry(self):
        layer_name = layer_interaction.biuniquify_layer_name('this_layer_was_added_for_testing_purpose')

        layer = QgsVectorLayer('Polygon?crs=EPSG:3857', layer_name, 'memory', False)

        number_of_layers = len(QgsMapLayerRegistry.instance().mapLayers())
        layer_interaction.add_layer_to_registry(layer)
        self.layer_list.append(layer.name())

        map_layers = QgsMapLayerRegistry.instance().mapLayers()
        actual = len(map_layers)
        expected = number_of_layers + 1
        message = 'An error occured when adding a layer to the MapLayerRegistry. {} is not {}!'.format(actual, expected)
        self.assertEqual(actual, expected, message)

        layer_added = False
        for layer_key in map_layers:

            if map_layers[layer_key].name() == layer_name:
                layer_added = True
                break

        self.assertTrue(layer_added, 'An error occured when adding a layer to the MapLayerRegistry.')
        number_of_layers = len(map_layers)
        layer_interaction.add_layer_to_registry(None)
        self.assertEqual(len(QgsMapLayerRegistry.instance().mapLayers()), number_of_layers, 'An error occured when trying to add a none-type-layer to the MapLayerRegistry. The number of layers should not increase.')
Ejemplo n.º 29
0
    def testRenderLineLayerDataDefined(self):
        """ test that rendering a line symbol with data defined enabled layer works"""

        lines_shp = os.path.join(TEST_DATA_DIR, 'lines.shp')
        lines_layer = QgsVectorLayer(lines_shp, 'Lines', 'ogr')
        QgsMapLayerRegistry.instance().addMapLayer(lines_layer)

        layer = QgsSimpleLineSymbolLayer()
        layer.setDataDefinedProperty("enabled", QgsDataDefined("Name='Highway'"))
        layer.setColor(QColor(100, 150, 150))
        layer.setWidth(5)

        symbol = QgsLineSymbol()
        symbol.changeSymbolLayer(0, layer)
        lines_layer.setRenderer(QgsSingleSymbolRenderer(symbol))

        ms = QgsMapSettings()
        ms.setOutputSize(QSize(400, 400))
        ms.setOutputDpi(96)
        ms.setExtent(QgsRectangle(-133, 22, -70, 52))
        ms.setLayers([lines_layer.id()])

        renderchecker = QgsMultiRenderChecker()
        renderchecker.setMapSettings(ms)
        renderchecker.setControlPathPrefix('symbol_layer')
        renderchecker.setControlName('expected_linelayer_ddenabled')
        self.assertTrue(renderchecker.runTest('linelayer_ddenabled'))
        QgsMapLayerRegistry.instance().removeMapLayer(lines_layer)
Ejemplo n.º 30
0
    def build_index(self, project):
        self.searchbox.setEnabled(False)
        self.resultsView.setEnabled(False)
        self.resultsView.addItem("building search index...")

        validformat, settings = valid_search_settings(project.settings)
        if not validformat:
            RoamEvents.raisemessage("Searching", "Invalid search config.", level=1)
            self.searchbox.hide()
            self.resultsView.clear()
            self.resultsView.addItem("Invalid search config found")
            return

        self.indexthread = QThread()
        path = os.path.join(os.environ['APPDATA'], "roam", project.name)

        roam.utils.info("Search index path: {0}".format(path))

        if not os.path.exists(path):
            os.makedirs(path)

        self.indexbuilder = IndexBuilder(path, settings)
        self.indexbuilder.moveToThread(self.indexthread)

        QgsMapLayerRegistry.instance().removeAll.connect(self.indexthread.quit)

        self.indexbuilder.indexBuilt.connect(self.index_built)
        self.indexbuilder.finished.connect(self.indexthread.quit)
        self.indexthread.started.connect(self.indexbuilder.build_index)
        self.indexthread.finished.connect(self.indexbuilder.quit)

        self.indexthread.start()
Ejemplo n.º 31
0
 def tearDown(self):
     QgsMapLayerRegistry.instance().removeAllMapLayers()
Ejemplo n.º 32
0
    def on_add_to_canvas_button_clicked(self):
        """
        Add STDM layer to map canvas.
        """
        if self.stdm_layers_combo.count() == 0:
            return

        sp_col_info = self.stdm_layers_combo.itemData(
            self.stdm_layers_combo.currentIndex())
        if sp_col_info is None:
            title = QApplication.translate('SpatialUnitManagerDockWidget',
                                           'Spatial Unit Manager')
            msg = QApplication.translate(
                'SpatialUnitManagerDockWidget',
                'Spatial Column Layer Could not be found')
            # Message: Spatial column information
            # could not be found
            QMessageBox.warning(self.iface.mainWindow(), title, msg)

        table_name, spatial_column = sp_col_info["table_name"], \
                                     sp_col_info["column_name"]

        # Check if the layer has already been
        layer_item = sp_col_info.get('item', None)

        layer_name = self.geom_col_layer_name(table_name, layer_item)

        if layer_name in self._map_registry_layer_names():
            layer = QgsMapLayerRegistry.instance().mapLayersByName(
                layer_name)[0]
            self.iface.setActiveLayer(layer)
            return

        self.curr_lyr_table = table_name
        self.curr_lyr_sp_col = spatial_column

        if not layer_item is None:
            if isinstance(layer_item, str) or isinstance(layer_item, unicode):
                layer_name = layer_item
            else:
                layer_name = layer_item.layer_display()

            entity = self._curr_profile.entity_by_name(table_name)
            if entity is not None:
                geom_col_obj = entity.columns[spatial_column]

                srid = None
                if geom_col_obj.srid >= 100000:
                    srid = geom_col_obj.srid

                curr_layer = vector_layer(table_name,
                                          geom_column=spatial_column,
                                          layer_name=layer_name,
                                          proj_wkt=srid)
            else:

                curr_layer = vector_layer(table_name,
                                          geom_column=spatial_column,
                                          layer_name=layer_name,
                                          proj_wkt=None)
        # for lookup layer.
        else:
            curr_layer = vector_layer(table_name, geom_column=spatial_column)

        if curr_layer.isValid():
            if curr_layer.name() in self._map_registry_layer_names():
                return

            QgsMapLayerRegistry.instance().addMapLayer(curr_layer)
            self.zoom_to_layer()

            self.onLayerAdded.emit(spatial_column, curr_layer)

            self.toggle_entity_multi_layers(curr_layer)

            self.set_canvas_crs(curr_layer)
            # Required in order for the layer name to be set
            if layer_name is not None:
                QTimer.singleShot(
                    100, lambda: self._set_layer_display_name(
                        curr_layer, layer_name))

            entity = self._curr_profile.entity_by_name(self.curr_lyr_table)
            fk_fields = self.join_fk_layer(curr_layer, entity)
            if entity is not None:
                self.sort_joined_columns(curr_layer, fk_fields)
                self.set_field_alias(curr_layer, entity, fk_fields)

        else:
            msg = QApplication.translate(
                "Spatial Unit Manager",
                "'{0}.{1}' layer is invalid, it cannot "
                "be added to the map view.".format(table_name, spatial_column))
            QMessageBox.critical(self.iface.mainWindow(),
                                 'Spatial Unit Manager', msg)
Ejemplo n.º 33
0
    def responseComplete(self):
        """Create a QGIS Project.

        Example :
        SERVICE=MAPCOMPOSITION&
        PROJECT=/destination/project.qgs&
        FILES=/path/1.shp;/path/2.shp;/path/3.asc&
        NAMES=Layer 1;Layer 2;Layer 3&
        REMOVEQML=true&
        OVERWRITE=true
        """
        request = self.serverInterface().requestHandler()
        params = request.parameterMap()

        if params.get('SERVICE', '').upper() == 'MAPCOMPOSITION':
            request.clearHeaders()
            request.setHeader('Content-type', 'text/plain')
            request.clearBody()

            project_path = params.get('PROJECT')
            if not project_path:
                request.appendBody('PROJECT parameter is missing.\n')
                return

            overwrite = params.get('OVERWRITE')
            if overwrite:
                if overwrite.upper() in ['1', 'YES', 'TRUE']:
                    overwrite = True
                else:
                    overwrite = False
            else:
                overwrite = False

            remove_qml = params.get('REMOVEQML')
            if remove_qml:
                if remove_qml.upper() in ['1', 'YES', 'TRUE']:
                    remove_qml = True
                else:
                    remove_qml = False
            else:
                remove_qml = False

            if exists(project_path):
                if not overwrite:
                    msg = 'PROJECT is already existing : %s \n' % project_path
                    request.appendBody(msg)
                    return
                else:
                    remove(project_path)

            files_parameters = params.get('FILES')
            if not files_parameters:
                request.appendBody('FILES parameter is missing.\n')
                return

            files = files_parameters.split(';')
            for layer_file in files:
                if not exists(layer_file):
                    request.appendBody('file not found : %s.\n' % layer_file)
                    return

            names_parameters = params.get('NAMES', None)
            if names_parameters:
                names = names_parameters.split(';')
                if len(names) != len(files):
                    request.appendBody(
                        'Not same length between NAMES and FILES')
                    return
            else:
                names = [
                    splitext(basename(layer_file))[0] for layer_file in files]

            QgsMessageLog.logMessage('Setting up project to %s' % project_path)
            project = QgsProject.instance()
            project.setFileName(project_path)

            qml_files = []
            qgis_layers = []
            vector_layers = []
            raster_layer = []

            for layer_name, layer_file in zip(names, files):
                if layer_file.endswith(('shp', 'geojson')):
                    qgis_layer = QgsVectorLayer(layer_file, layer_name, 'ogr')
                    vector_layers.append(qgis_layer.id())

                elif layer_file.endswith(('asc', 'tiff', 'tif')):
                    qgis_layer = QgsRasterLayer(layer_file, layer_name)
                    raster_layer.append(qgis_layer.id())
                else:
                    request.appendBody('Invalid format : %s' % layer_file)
                    return

                if not qgis_layer.isValid():
                    request.appendBody('Layer is not valid : %s' % layer_file)
                    return

                qgis_layers.append(qgis_layer)

                qml_file = splitext(layer_file)[0] + '.qml'
                if exists(qml_file):
                    # Check if there is a QML
                    qml_files.append(qml_file)

                style_manager = qgis_layer.styleManager()
                style_manager.renameStyle('', 'default')

                # Add layer to the registry
                QgsMapLayerRegistry.instance().addMapLayer(qgis_layer)

            if len(vector_layers):
                for layer_file in vector_layers:
                    project.writeEntry(
                        'WFSLayersPrecision', '/%s' % layer_file, 8)
                project.writeEntry('WFSLayers', '/', vector_layers)

            if len(raster_layer):
                project.writeEntry('WCSLayers', '/', raster_layer)

            project.write()
            project.clear()

            if not exists(project_path) and not isfile(project_path):
                request.appendBody(project.error())
                return

            generate_legend(qgis_layers, project_path)

            if remove_qml:
                for qml in qml_files:
                    QgsMessageLog.logMessage(
                        'Removing QML {path}'.format(path=qml))
                    remove(qml)

            request.appendBody('OK')
Ejemplo n.º 34
0
def open_file(
        dialog=None,
        osm_file=None,
        output_geom_types=None,
        white_list_column=None,
        output_format=None,
        layer_name="OsmFile",
        config_outputs=None,
        output_dir=None,
        prefix_file=None):
    """
    open an osm file
    """
    outputs = get_outputs(output_dir, output_format, prefix_file, layer_name)

    # Parsing the file
    osm_parser = OsmParser(
        osm_file=osm_file,
        layers=output_geom_types,
        white_list_column=white_list_column)

    osm_parser.signalText.connect(dialog.set_progress_text)
    osm_parser.signalPercentage.connect(dialog.set_progress_percentage)
    layers = osm_parser.parse()

    # Finishing the process with geojson or shapefile
    num_layers = 0
    if output_format == "shape":
        dialog.set_progress_text(tr("QuickOSM", u"From GeoJSON to Shapefile"))

    for i, (layer, item) in enumerate(layers.iteritems()):
        dialog.set_progress_percentage(i / len(layers) * 100)
        QApplication.processEvents()
        if item['featureCount'] and layer in output_geom_types:

            final_layer_name = layer_name
            # If configOutputs is not None (from My Queries)
            if config_outputs:
                if config_outputs[layer]['namelayer']:
                    final_layer_name = config_outputs[layer]['namelayer']

            # Transforming the vector file
            osm_geometries = {
                'points': QGis.WKBPoint,
                'lines': QGis.WKBLineString,
                'multilinestrings': QGis.WKBMultiLineString,
                'multipolygons': QGis.WKBMultiPolygon}
            geojson_layer = QgsVectorLayer(item['geojsonFile'], "temp", "ogr")

            encoding = get_default_encoding()
            if output_format == "shape":
                writer = QgsVectorFileWriter(
                    outputs[layer],
                    encoding,
                    geojson_layer.pendingFields(),
                    osm_geometries[layer],
                    geojson_layer.crs(),
                    "ESRI Shapefile")
            else:
                writer = QgsVectorFileWriter(
                    outputs[layer],
                    encoding,
                    geojson_layer.pendingFields(),
                    osm_geometries[layer],
                    geojson_layer.crs(),
                    "GeoJSON")

            for f in geojson_layer.getFeatures():
                writer.addFeature(f)

            del writer

            # Loading the final vector file
            new_layer = QgsVectorLayer(outputs[layer], final_layer_name, "ogr")

            # Try to set styling if defined
            if config_outputs and config_outputs[layer]['style']:
                new_layer.loadNamedStyle(config_outputs[layer]['style'])
            else:
                # Loading default styles
                if layer == "multilinestrings" or layer == "lines":
                    if "colour" in item['tags']:
                        new_layer.loadNamedStyle(
                            join(dirname(dirname(abspath(__file__))),
                                 "styles",
                                 layer + "_colour.qml"))

            # Add action about OpenStreetMap
            actions = new_layer.actions()
            actions.addAction(
                QgsAction.OpenUrl,
                "OpenStreetMap Browser",
                'http://www.openstreetmap.org/browse/'
                '[% "osm_type" %]/[% "osm_id" %]',
                False)
            actions.addAction(
                QgsAction.GenericPython,
                'JOSM',
                'from QuickOSM.CoreQuickOSM.Actions import Actions;'
                'Actions.run("josm","[% "full_id" %]")',
                False)
            actions.addAction(
                QgsAction.OpenUrl,
                "User default editor",
                'http://www.openstreetmap.org/edit?'
                '[% "osm_type" %]=[% "osm_id" %]',
                False)

            for link in ['url', 'website', 'wikipedia', 'ref:UAI']:
                if link in item['tags']:
                    link = link.replace(":", "_")
                    actions.addAction(
                        QgsAction.GenericPython,
                        link,
                        'from QuickOSM.core.actions import Actions;'
                        'Actions.run("' + link + '","[% "' + link + '" %]")',
                        False)

            if 'network' in item['tags'] and 'ref' in item['tags']:
                actions.addAction(
                    QgsAction.GenericPython,
                    "Sketchline",
                    'from QuickOSM.core.actions import Actions;'
                    'Actions.run_sketch_line("[% "network" %]","[% "ref" %]")',
                    False)

            # Add index if possible
            if output_format == "shape":
                new_layer.dataProvider().createSpatialIndex()

            QgsMapLayerRegistry.instance().addMapLayer(new_layer)
            num_layers += 1

    return num_layers
Ejemplo n.º 35
0
# Start qGIS, then copy and paste ALL lines of this script into the Python Console (Ctrl+Alt+P)
# Note: You will need to change the value of `directoryContainingWktFiles` to the correct folder

from qgis.core import QgsVectorLayer, QgsMapLayerRegistry
import os, PyQt4

# Remember, no backslashes '\' in paths, only forward slashes '/'
directoryContainingWktFiles = 'D:/Dropbox/VATSIM/ZDC/vSTARSZDC/vSTARS Facility - Potomac TRACON (PCT)/Video Map WKTs'

for root, dirs, files in os.walk(directoryContainingWktFiles):
    for file in files:
        fullname = os.path.join(root, file).replace('\\', '/')
        filename = os.path.splitext(os.path.basename(fullname))[0]
        uri = PyQt4.QtCore.QUrl.fromLocalFile(fullname)
        uri.addQueryItem('delimiter', '|')
        uri.addQueryItem('useHeader', 'yes')
        uri.addQueryItem('wktField', 'wkt')
        uri.addQueryItem('crs', 'ESPG:4326')
        layer = QgsVectorLayer(str(uri.toEncoded()), filename, 'delimitedtext')
        if layer.isValid():
            QgsMapLayerRegistry.instance().addMapLayer(layer)
        else:
            print('file invalid')
Ejemplo n.º 36
0
    def run(self, fid = 0):

    ##################################
    ###### PEGA A LAYER ATIVA ########
    ##################################

        parametros = self.layer.source().split(" ") # recebe todos os parametros em uma lista ( senha, porta, password etc..)

    ####################################
    ###### INICIANDO CONEXÃO DB ########
    ####################################

        # Outra opção para isso, seria usar ex: self.dbname.. self.host.. etc.. direto dentro do laço for.
        dbname = "" 
        host = ""
        port = 0
        user = ""
        password = ""

        for i in parametros:
            part = i.split("=")
            
        # Recebe os parametros guardados na própria Layer

            if "dbname" in part[0]:
                dbname = part[1].replace("'", "")

            elif "host" in part[0]:
                host = part[1].replace("'", "")

            elif "port" in part[0]:
                port = int(part[1].replace("'", ""))

            elif "user" in part[0]:
                user = part[1].replace("'", "")

            elif "password" in part[0]:
                password = part[1].split("|")[0].replace("'", "")

        print dbname, host, port, user, password

        # Testa se os parametros receberam os valores pretendidos, caso não, apresenta a mensagem informando..
        if len(dbname) == 0 or len(host) == 0 or port == 0 or len(user) == 0 or len(password) == 0:
            self.iface.messageBar().pushMessage("Erro", u'Um dos parametros não foram devidamente recebidos!', level=QgsMessageBar.CRITICAL, duration=4)
            return

    ####################################
    #### SETA VALORES DE CONEXÃO DB ####
    ####################################

        connection = QSqlDatabase.addDatabase('QPSQL')
        connection.setHostName(host)
        connection.setPort(port)
        connection.setUserName(user)
        connection.setPassword(password)
        connection.setDatabaseName(dbname)

        if not connection.isOpen(): # Testa se a conexão esta recebendo os parametros adequadamente.
            if not connection.open():
                print 'Error connecting to database!'
                self.iface.messageBar().pushMessage("Erro", u'Error connecting to database!', level=QgsMessageBar.CRITICAL, duration=4)
                print connection.lastError().text()
                return

    ####################################
    ###### CRIAÇÃO DE MEMORY LAYER #####
    ####################################
        

        layerCrs = self.layer.crs().authid() # Passa o formato (epsg: numeros)

        flagsLayerName = self.layer.name() + "_flags"
        flagsLayerExists = False

        for l in QgsMapLayerRegistry.instance().mapLayers().values(): # Recebe todas as camadas que estão abertas
            if l.name() == flagsLayerName: # ao encontrar o nome pretendido..
                self.flagsLayer = l # flagslayer vai receber o nome..
                self.flagsLayerProvider = l.dataProvider()
                flagsLayerExists = True # se encontrado os parametros buscados, recebe True.
                break
        
        if flagsLayerExists == False: # se não encontrado os parametros buscados, recebe False.
            tempString = "Point?crs="
            tempString += str(layerCrs)

            self.flagsLayer = QgsVectorLayer(tempString, flagsLayerName, "memory")
            self.flagsLayerProvider = self.flagsLayer.dataProvider()
            self.flagsLayerProvider.addAttributes([QgsField("flagId", QVariant.String), QgsField("geomId", QVariant.String), QgsField("motivo", QVariant.String)])
            self.flagsLayer.updateFields()

        if fid == 0: # Se for 0 então está iniciando e limpa, caso contrário não.
            self.flagsLayer.startEditing()
            ids = [feat.id() for feat in self.flagsLayer.getFeatures()]
            self.flagsLayer.deleteFeatures(ids)
            self.flagsLayer.commitChanges()
        
        lista_fid = [] # Iniciando lista
        for f in self.layer.getFeatures():
            lista_fid.append(str(f.id())) # Guarda na lista. A lista de Feature ids passa tipo "int", foi convertido e guardado como "str".

        source = self.layer.source().split(" ")
        self.tableName = " " # Inicia vazio
        layerExistsInDB = False
        
        for i in source:
                
            if "table=" in i or "layername=" in i: # Se encontrar os atributos pretendidos dentre todos do for
                self.tableName = source[source.index(i)].split(".")[1] # Faz split em ponto e pega a segunda parte.
                self.tableName = self.tableName.replace('"', '')
                layerExistsInDB = True
                break
             
        if layerExistsInDB == False:
            self.iface.messageBar().pushMessage("Erro", u"Provedor da camada corrente não provem do banco de dados!", level=QgsMessageBar.CRITICAL, duration=4)
            return

        ##############################
        #### Busca através do SQL ####
        ##############################


        sql = """select foo."{3}" as "{3}", ST_AsText(ST_MULTI(st_startpoint(foo."{2}"))) as "{2}" from (
        select "{3}" as "{3}", (ST_Dump(ST_Node(ST_SetSRID(ST_MakeValid("{2}"),ST_SRID("{2}"))))).geom as "{2}" from "{0}"."{1}"  
        where ST_IsSimple("{2}") = 'f' and {3} in ({4})) as foo where st_equals(st_startpoint(foo."{2}"),st_endpoint(foo."{2}"))""".format(self.tableSchema, self.tableName, self.geometryColumn, self.keyColumn, ",".join(lista_fid))
            
        query = QSqlQuery(sql)

        self.flagsLayer.startEditing()
        flagCount = fid # iniciando contador que será referência para os IDs da camada de memória.

        listaFeatures = []
        while query.next():
            id = query.value(0) # recebendo valores buscados no sql.
            local = query.value(1) # recebendo valores buscados no sql.
            motivo = query.value(2)
           
            flagId = str(flagCount)

            flagFeat = QgsFeature()
            flagFeat.setFields(self.flagsLayer.fields()) # passa quais atributos serão usados.
            flagGeom = QgsGeometry.fromWkt(local) # passa o local onde foi localizado o erro.
            flagFeat.setGeometry(flagGeom)
            flagFeat.setAttribute(0, flagId) # insere o id definido para a coluna 0 da layer de memória.
            flagFeat.setAttribute(1, id) # insere o id da geometria para a coluna 1 da layer de memória.
            flagFeat.setAttribute(2,  u"NotSimple-Geom.")
            listaFeatures.append(flagFeat)    

            flagCount += 1 # incrementando o contador a cada iteração.

        self.flagsLayerProvider.addFeatures(listaFeatures)
        self.flagsLayer.commitChanges() # Aplica as alterações à camada.

        QgsMapLayerRegistry.instance().addMapLayer(self.flagsLayer) # Adicione a camada no mapa.

        return flagCount
        
    def accept(self):
        layer = self.inputPolyComboBox.currentLayer()
        if not layer:
            self.iface.messageBar().pushMessage("",
                                                "No Valid Layer",
                                                level=QgsMessageBar.WARNING,
                                                duration=4)
        layercrs = layer.crs()
        wkbtype = layer.wkbType()
        polyname = self.geodesicPolyNameLineEdit.text()

        # Get the field names for the input layer. The will be copied to the output layers
        fields = layer.pendingFields()

        # Create the points and polygon output layers
        if wkbtype == QGis.WKBPolygon:
            polyLayer = QgsVectorLayer(
                "Polygon?crs={}".format(layercrs.authid()), polyname, "memory")
        else:
            polyLayer = QgsVectorLayer(
                "MultiPolygon?crs={}".format(layercrs.authid()), polyname,
                "memory")
        ppoly = polyLayer.dataProvider()
        ppoly.addAttributes(fields)
        polyLayer.updateFields()

        if layercrs != epsg4326:
            transto4326 = QgsCoordinateTransform(layercrs, epsg4326)
            transfrom4326 = QgsCoordinateTransform(epsg4326, layercrs)

        iter = layer.getFeatures()
        num_features = 0
        num_bad = 0
        maxseglen = settings.maxSegLength * 1000.0
        maxSegments = settings.maxSegments
        for feature in iter:
            num_features += 1
            try:
                if wkbtype == QGis.WKBPolygon:
                    poly = feature.geometry().asPolygon()
                    numpolygons = len(poly)
                    if numpolygons < 1:
                        continue

                    ptset = []
                    for points in poly:
                        numpoints = len(points)
                        if numpoints < 2:
                            continue
                        # If the input is not 4326 we need to convert it to that and then back to the output CRS
                        ptStart = QgsPoint(points[0][0], points[0][1])
                        if layercrs != epsg4326:  # Convert to 4326
                            ptStart = transto4326.transform(ptStart)
                        pts = [ptStart]
                        for x in range(1, numpoints):
                            ptEnd = QgsPoint(points[x][0], points[x][1])
                            if layercrs != epsg4326:  # Convert to 4326
                                ptEnd = transto4326.transform(ptEnd)
                            l = self.geod.InverseLine(ptStart.y(), ptStart.x(),
                                                      ptEnd.y(), ptEnd.x())
                            n = int(math.ceil(l.s13 / maxseglen))
                            if n > maxSegments:
                                n = maxSegments

                            seglen = l.s13 / n
                            for i in range(1, n):
                                s = seglen * i
                                g = l.Position(
                                    s, Geodesic.LATITUDE | Geodesic.LONGITUDE
                                    | Geodesic.LONG_UNROLL)
                                pts.append(QgsPoint(g['lon2'], g['lat2']))
                            pts.append(ptEnd)
                            ptStart = ptEnd

                            if layercrs != epsg4326:  # Convert each point to the output CRS
                                for x, pt in enumerate(pts):
                                    pts[x] = transfrom4326.transform(pt)
                        ptset.append(pts)

                    if len(ptset) > 0:
                        featureout = QgsFeature()
                        featureout.setGeometry(QgsGeometry.fromPolygon(ptset))

                        featureout.setAttributes(feature.attributes())
                        ppoly.addFeatures([featureout])
                else:
                    multipoly = feature.geometry().asMultiPolygon()
                    multiset = []
                    for poly in multipoly:
                        ptset = []
                        for points in poly:
                            numpoints = len(points)
                            if numpoints < 2:
                                continue
                            # If the input is not 4326 we need to convert it to that and then back to the output CRS
                            ptStart = QgsPoint(points[0][0], points[0][1])
                            if layercrs != epsg4326:  # Convert to 4326
                                ptStart = transto4326.transform(ptStart)
                            pts = [ptStart]
                            for x in range(1, numpoints):
                                ptEnd = QgsPoint(points[x][0], points[x][1])
                                if layercrs != epsg4326:  # Convert to 4326
                                    ptEnd = transto4326.transform(ptEnd)
                                l = self.geod.InverseLine(
                                    ptStart.y(), ptStart.x(), ptEnd.y(),
                                    ptEnd.x())
                                n = int(math.ceil(l.s13 / maxseglen))
                                if n > maxSegments:
                                    n = maxSegments

                                seglen = l.s13 / n
                                for i in range(1, n):
                                    s = seglen * i
                                    g = l.Position(
                                        s,
                                        Geodesic.LATITUDE | Geodesic.LONGITUDE
                                        | Geodesic.LONG_UNROLL)
                                    pts.append(QgsPoint(g['lon2'], g['lat2']))
                                pts.append(ptEnd)
                                ptStart = ptEnd

                                if layercrs != epsg4326:  # Convert each point to the output CRS
                                    for x, pt in enumerate(pts):
                                        pts[x] = transfrom4326.transform(pt)
                            ptset.append(pts)
                        multiset.append(ptset)

                    if len(multiset) > 0:
                        featureout = QgsFeature()
                        featureout.setGeometry(
                            QgsGeometry.fromMultiPolygon(multiset))

                        featureout.setAttributes(feature.attributes())
                        ppoly.addFeatures([featureout])
            except:
                num_bad += 1
                pass

        polyLayer.updateExtents()
        QgsMapLayerRegistry.instance().addMapLayer(polyLayer)
        if num_bad != 0:
            self.iface.messageBar().pushMessage(
                "",
                "{} out of {} features failed".format(num_bad, num_features),
                level=QgsMessageBar.WARNING,
                duration=3)

        self.close()
Ejemplo n.º 38
0
    def load_knmi(self):
        # KNMI
        # http://geoservices.knmi.nl/cgi-bin/RADNL_OPER_R___25PCPRR_L3.cgi?SERVICE=WMS&&SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&LAYERS=RADNL_OPER_R___25PCPRR_L3_COLOR&WIDTH=886&HEIGHT=603&CRS=EPSG%3A3857&BBOX=-725.7203842048766,6434348.070664023,1220725.7203842048,7265651.929335977&STYLES=default&FORMAT=image/png&TRANSPARENT=TRUE&time=2016-06-15T08%3A30%3A00Z
        # http://geoservices.knmi.nl/cgi-bin/RADNL_OPER_R___25PCPRR_L3.cgi?TIME=2016-06-14T09:25:02Z/2016-06-14T10:25:02Z&&SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&BBOX=41607.58263816371618,373175.3892402839847,308340.3808564461069,650052.614857714274&CRS=EPSG:28992&WIDTH=1451&HEIGHT=1507&LAYERS=RADNL_OPER_R___25PCPRR_L3_COLOR&STYLES=&FORMAT=image/png&DPI=96&MAP_RESOLUTION=96&FORMAT_OPTIONS=dpi:96&TRANSPARENT=TRUE

        # http://geoservices.knmi.nl/cgi-bin/RADNL_OPER_R___25PCPRR_L3.cgi?SERVICE=WMS&&SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&LAYERS=RADNL_OPER_R___25PCPRR_L3_COLOR&WIDTH=886&HEIGHT=603&CRS=EPSG%3A3857&BBOX=-725.7203842048766,6434348.070664023,1220725.7203842048,7265651.929335977&STYLES=default&FORMAT=image/png&TRANSPARENT=TRUE
        # Timestart en end
        # 2016-06-13T18:00:00Z
        # 2016-06-15T18:00:00Z

        if not 'timemanager' in plugins:
            self.iface.messageBar().pushWarning(
                "Warning!!",
                "No TimeManger plugin, we REALLY need that. Please install via Plugin Manager first..."
            )
            return

        # development: remove the knmi layer from mapcanvas
        for l in QgsMapLayerRegistry.instance().mapLayersByName("knmi"):
            QgsMapLayerRegistry.instance().removeMapLayer(l)

        tm = plugins['timemanager']

        # TODO try catch this
        from timemanager.layer_settings import LayerSettings
        from timemanager.raster.wmstlayer import WMSTRasterLayer
        #from timemanager.tmlogging import info

        #TODO click on button if not enabled
        if not tm.getController().getTimeLayerManager().isEnabled():
            tm.getController().getGui().dock.pushButtonToggleTime.click()

        # for testing: just remove all timelayers
        tm.getController().timeLayerManager.clearTimeLayerList()

        # # DEZE WERKT NIET !!!!  (?? zelfde probleem als eerder??)
        # url = "http://geoservices.knmi.nl/cgi-bin/RADNL_OPER_R___25PCPRR_L3.cgi?SERVICE=WMS"
        # # DEZE WERKT WEL !!!!
        # url = "http://geoservices.knmi.nl/cgi-bin/RADNL_OPER_R___25PCPRR_L3.cgi"
        # layers = "RADNL_OPER_R___25PCPRR_L3_COLOR"
        # styles = ""
        # imgformat = "image/png"
        # crs = "EPSG:28992"

        settings = RegenRadarSettings()
        name = settings.value("name")
        url = settings.value("url")
        layers = settings.value("layers")
        styles = settings.value("styles")
        imgformat = settings.value("imgformat")
        crs = settings.value("crs")

        # IgnoreGetMapUrl=1&contextualWMSLegend=0&crs=EPSG:28992&dpiMode=7&featureCount=10&format=image/png&layers=RADNL_OPER_R___25PCPRR_L3_COLOR&styles=&url=http://geoservices.knmi.nl/cgi-bin/RADNL_OPER_R___25PCPRR_L3.cgi?

        uri = "crs=" + crs + "&layers=" + layers + "&styles=" + styles + "&format=" + imgformat + "&url=" + url
        layer = self.iface.addRasterLayer(uri, name, "wms")

        tlayer_settings = LayerSettings()

        # endTimeAttribute !!! NOT toTimeAttribute
        #settings.startTimeAttribute = unicode("2016-06-13T18:00:00Z")
        #settings.endTimeAttribute = unicode("2016-06-15T18:00:00Z")
        DEFAULT_DATE_FORMAT = 'yyyy-MM-ddTHH:mm:ssZ'
        end = QDateTime.currentDateTime().toUTC()  # now in UTC
        time = end.time()
        minute = time.minute()
        # prefer times which are %5=0 (that is 0, 5, 15 ... minutes)
        time.setHMS(time.hour(), minute - minute % 5, 0, 0)
        end.setTime(time)
        tlayer_settings.endTimeAttribute = end.toString(DEFAULT_DATE_FORMAT)
        hours = settings.value("hours")
        start = end.addSecs(-hours * 60 * 60).toString(DEFAULT_DATE_FORMAT)
        tlayer_settings.startTimeAttribute = start
        # NOK
        # http://geoservices.knmi.nl/cgi-bin/RADNL_OPER_R___25PCPRR_L3.cgi?TIME=2016-07-05T13:45:00Z/2016-07-05T13:50:00Z&&SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&BBOX=-145108.7003207547241,299063.8299999999581,436757.3003207547008,626788.5699999999488&CRS=EPSG:28992&WIDTH=941&HEIGHT=530&LAYERS=RADNL_OPER_R___25PCPRR_L3_COLOR&STYLES=&FORMAT=image/png&DPI=96&MAP_RESOLUTION=96&FORMAT_OPTIONS=dpi:96&TRANSPARENT=TRUE

        # OK
        # http://geoservices.knmi.nl/cgi-bin/RADNL_OPER_R___25PCPRR_L3.cgi?TIME=2016-06-13T18:05:00Z/2016-06-13T18:10:00Z&&SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&BBOX=-145108.7003207547241,299063.8299999999581,436757.3003207547008,626788.5699999999488&CRS=EPSG:28992&WIDTH=941&HEIGHT=530&LAYERS=RADNL_OPER_R___25PCPRR_L3_COLOR&STYLES=&FORMAT=image/png&DPI=96&MAP_RESOLUTION=96&FORMAT_OPTIONS=dpi:96&TRANSPARENT=TRUE
        #settings.startTimeAttribute = unicode("2016-06-13T18:00:00Z")
        #settings.endTimeAttribute = unicode("2016-06-15T18:00:00Z")

        tlayer_settings.layer = layer

        timelayer = WMSTRasterLayer(tlayer_settings, self.iface)

        # ??
        # iface.mapCanvas().mapCanvasRefreshed.disconnect(tm.getController().waitAfterRenderComplete)
        # iface.mapCanvas().mapCanvasRefreshed.connect(tm.getController().waitAfterRenderComplete)

        # print timelayer
        # print timelayer.getTimeExtents()

        # tm.getController().refreshGuiTimeExtents([
        #    QtCore.QDateTime.fromString("2016-06-13T18:00:00Z", 'yyyy-MM-ddTHH:mm:ssZ'),
        #    QtCore.QDateTime.fromString("2016-06-15T18:00:00Z", 'yyyy-MM-ddTHH:mm:ssZ')])

        animationFrameLength = 2000
        frame_type = 'minutes'
        frame_size = 5  # TODO: make this a parameter?
        tm.getController().setPropagateGuiChanges(False)
        tm.getController().setAnimationOptions(animationFrameLength, False,
                                               False)

        tm.getController().timeLayerManager.registerTimeLayer(timelayer)

        tm.getController().getGui().setTimeFrameType(frame_type)
        tm.getController().getGui().setTimeFrameSize(frame_size)

        # set layer to zero
        tm.getController().getGui().dock.horizontalTimeSlider.setValue(0)

        # tm.getController().timeLayerManager.refreshTimeRestrictions()

        # tm.getController().getGui().dock.pushButtonPlay.click()

        # plugins['timemanager'].getController().getGui().dock.pushButtonPlay.click()

        QTimer.singleShot(
            5000,
            tm.getController().getGui().dock.pushButtonPlay.click)
Ejemplo n.º 39
0
 def getAllLayers(self):
     if LayerRegistry._iface and hasattr(LayerRegistry._iface, 'legendInterface'):
         return LayerRegistry._iface.legendInterface().layers()
     return list(QgsMapLayerRegistry.instance().mapLayers().values())
Ejemplo n.º 40
0
    def read_islh(self):

        os.chdir(self.plugin_dir)  #musim do plugin diru, abysem nacet svg

        if not self.dockwidget.input_file.text():
            QMessageBox.critical(QDialog(), u"Missing file",
                                 u"Není vybrán žádný soubor")
        else:
            self.f = open(self.dockwidget.input_file.text())
            try:
                #nachroustam xml
                self.dockwidget.output_working_on.setText(u"načítám XML")
                self.load_xml()

            except:
                QMessageBox.critical(QDialog(), u"vadný soubor",
                                     u"soubor se nepodařilo načíst")

            self.dockwidget.output_working_on.setText(
                u"Začínám tvořit grafiku")

            self.add_layers()

            self.dockwidget.output_working_on.setText(
                u"přidávám vrstvy do mapové kompozice")

            self.dockwidget.progressBar.setRange(0, 8)
            self.dockwidget.progressBar.setValue(0)

            self.layerTreeRoot = QgsProject.instance().layerTreeRoot()
            self.por_mapa_group = self.layerTreeRoot.insertGroup(
                0, u'Porostní mapa')
            self.bzl_jp_op_mapa_group = self.layerTreeRoot.insertGroup(
                1, u'BZL, JP, OP')

            #self.iface.mapCanvas().setRenderFlag(False)

            if hasattr(self, 'psk_layer'):
                QgsMapLayerRegistry.instance().addMapLayer(
                    self.psk_layer, False)
                self.psk_layer.loadNamedStyle('styles/por_mapa.qml')
                self.por_mapa_group.insertLayer(0, self.psk_layer)

            self.dockwidget.progressBar.setValue(1)

            if hasattr(self, 'bzl_layer'):
                QgsMapLayerRegistry.instance().addMapLayer(
                    self.bzl_layer, False)
                self.bzl_jp_op_mapa_group.insertLayer(0, self.bzl_layer)

            self.dockwidget.progressBar.setValue(2)

            if hasattr(self, 'jp_layer'):
                QgsMapLayerRegistry.instance().addMapLayer(
                    self.jp_layer, False)
                self.bzl_jp_op_mapa_group.insertLayer(0, self.jp_layer)

            self.dockwidget.progressBar.setValue(3)

            if hasattr(self, 'op_layer'):
                QgsMapLayerRegistry.instance().addMapLayer(
                    self.op_layer, False)
                self.bzl_jp_op_mapa_group.insertLayer(0, self.op_layer)

            self.dockwidget.progressBar.setValue(4)

            if hasattr(self, 'kpo_layer'):
                QgsMapLayerRegistry.instance().addMapLayer(
                    self.kpo_layer, False)
                self.kpo_layer.loadNamedStyle('styles/por_mapa_kpo.qml')
                self.por_mapa_group.insertLayer(0, self.kpo_layer)

            self.dockwidget.progressBar.setValue(5)

            if hasattr(self, 'klo_layer'):
                QgsMapLayerRegistry.instance().addMapLayer(
                    self.klo_layer, False)
                self.klo_layer.loadNamedStyle('styles/porostni_mapa_linie.qml')
                self.por_mapa_group.insertLayer(0, self.klo_layer)

            self.dockwidget.progressBar.setValue(6)

            if hasattr(self, 'kbo_layer'):
                QgsMapLayerRegistry.instance().addMapLayer(
                    self.kbo_layer, False)
                self.kbo_layer.loadNamedStyle('styles/styly_body.qml')
                self.por_mapa_group.insertLayer(0, self.kbo_layer)

            self.dockwidget.progressBar.setValue(7)

            if hasattr(self, 'kto_layer'):
                QgsMapLayerRegistry.instance().addMapLayer(
                    self.kto_layer, False)
                self.kto_layer.loadNamedStyle('styles/styly_txt.qml')
                self.por_mapa_group.insertLayer(0, self.kto_layer)

            self.dockwidget.progressBar.setValue(8)

            self.bzl_jp_op_mapa_group.setVisible(Qt.Unchecked)
            #self.por_mapa_group.setVisible(Qt.Unchecked)

            lhc_list = [self.lhc.get('LHC_KOD')]
            self.dockwidget.input_lhc.clear()
            self.dockwidget.input_lhc.addItems(lhc_list)

            #nastavit komba na zacatek
            self.select_lhc()
            self.select_odd()
            self.select_dil()
            self.select_por()
            self.select_psk()
            self.iface.setActiveLayer(self.psk_layer)
Ejemplo n.º 41
0
    def renderer(self):
        qgis = QgsApplication([], False)
        qgis.setPrefixPath(self.settings.get('path'), True)
        qgis.setMaxThreads(1)
        qgis.initQgis()

        while True:
            try:
                fndata, srs, render_size, extended, \
                    target_box, result = self.queue.get()

                layer = QgsVectorLayer(fndata, 'layer', 'ogr')

                crs = QgsCoordinateReferenceSystem(srs.id)
                layer.setCrs(crs)

                settings = QgsMapSettings()
                settings.setLayers([layer.id()])
                settings.setFlag(QgsMapSettings.DrawLabeling)
                settings.setFlag(QgsMapSettings.Antialiasing)

                settings.setCrsTransformEnabled(True)
                settings.setDestinationCrs(crs)
                settings.setMapUnits(crs.mapUnits())
                settings.setOutputSize(QSize(*render_size))
                settings.setExtent(QgsRectangle(*extended))

                settings.setOutputImageFormat(QImage.Format_ARGB32)
                bgcolor = QColor.fromRgba(qRgba(255, 255, 255, 0))
                settings.setBackgroundColor(bgcolor)
                settings.setOutputDpi(96)

                QgsMapLayerRegistry.instance().addMapLayer(layer)
                settings.setLayers([layer.id()])

                # Создаем QImage руками чтобы можно было использовать
                # QgsMapRendererCustomPainterJob. Остальные не позволяют
                # обойти баг с рисованием поверх старого.
                img = QImage(settings.outputSize(), QImage.Format_ARGB32)

                # Эти костыли нужны для того, чтобы корректно рисовались
                # слои на прозрачном фоне, без этого получается каша.
                img.fill(QColor.fromRgba(qRgba(255, 255, 255, 255)))
                img.fill(QColor.fromRgba(qRgba(255, 255, 255, 0)))

                # DPI должно быть таким же как в settings, иначе ошибка. В QImage
                # разрешение указывается в точках на метр по каждой оси.
                dpm = settings.outputDpi() / 25.4 * 1000
                img.setDotsPerMeterX(dpm)
                img.setDotsPerMeterY(dpm)

                painter = QPainter(img)
                job = QgsMapRendererCustomPainterJob(settings, painter)
                job.renderSynchronously()
                painter.end()

                QgsMapLayerRegistry.instance().removeAllMapLayers()

                # Преобразование QImage в PIL
                ba = QByteArray()
                bf = QBuffer(ba)
                bf.open(QIODevice.WriteOnly)
                img.save(bf, 'PNG')
                bf.close()

                buf = StringIO()
                buf.write(bf.data())
                buf.seek(0)

                img = PIL.Image.open(buf)

                # Вырезаем нужный нам кусок изображения
                result.put(img.crop(target_box))

            except Exception as e:
                self.logger.error(e.message)

        qgis.exitQgis()
Ejemplo n.º 42
0
 def refresh(self):
     #import traceback
     #traceback.print_stack(limit=5)
     self.removeall()
     for layer in QgsMapLayerRegistry.instance().mapLayers().values():
         self.addlayer(layer)
Ejemplo n.º 43
0
    def __init__(self, canvas):
        """Constructor
        :param canvas:
        """
        QObject.__init__(self)
        self.canvas = canvas
        # Set up slots so we can mimic the behaviour of QGIS when layers
        # are added.
        LOGGER.debug('Initialising canvas...')
        # noinspection PyArgumentList
        QgsMapLayerRegistry.instance().layersAdded.connect(self.addLayers)
        # noinspection PyArgumentList
        QgsMapLayerRegistry.instance().layerWasAdded.connect(self.addLayer)
        # noinspection PyArgumentList
        QgsMapLayerRegistry.instance().removeAll.connect(self.removeAllLayers)

        # For processing module
        self.destCrs = None
        # For keeping track of which layer is active in the legend.
        self.active_layer = None

        # In the next section of code, we are going to do some monkey patching
        # to make the QGIS processing framework think that this mock QGIS IFACE
        # instance is the actual one. It will also ensure that the processing
        # algorithms are nicely loaded and available for use.

        # Since QGIS > 2.0, the module is moved from QGisLayers to dataobjects
        # pylint: disable=F0401, E0611
        if QGis.QGIS_VERSION_INT > 20001:
            from processing.tools import dataobjects
        else:
            from processing.core import QGisLayers as dataobjects

        import processing
        from processing.core.Processing import Processing
        # pylint: enable=F0401, E0611
        processing.classFactory(self)

        # We create our own getAlgorithm function below which will will monkey
        # patch in to the Processing class in QGIS in order to ensure that the
        # Processing.initialize() call is made before asking for an alg.

        @staticmethod
        def mock_getAlgorithm(name):
            """
            Modified version of the original getAlgorithm function.

            :param name: Name of the algorithm to load.
            :type name: str

            :return: An algorithm concrete class.
            :rtype: QgsAlgorithm  ?
            """
            Processing.initialize()
            for provider in Processing.algs.values():
                if name in provider:
                    return provider[name]
            return None

        # Now we let the monkey loose!
        Processing.getAlgorithm = mock_getAlgorithm
        # We also need to make dataobjects think that this iface is 'the one'
        # Note. the placement here (after the getAlgorithm monkey patch above)
        # is significant, so don't move it!
        dataobjects.iface = self
Ejemplo n.º 44
0
 def activeLayer(self):
     """Get pointer to the active layer (layer selected in the legend)"""
     myLayers = QgsMapLayerRegistry.instance().mapLayers()
     for myItem in myLayers:
         return myLayers[myItem]
Ejemplo n.º 45
0
 def layers(self):
     # It's for processing module
     # simulate iface.legendInterface().layers()
     return QgsMapLayerRegistry.instance().mapLayers().values()
Ejemplo n.º 46
0
def get_vector_layer_by_name(layer_name):
    layer = QgsMapLayerRegistry.instance().mapLayersByName(layer_name)
    if not layer:
        return None
    else:
        return layer[0]
Ejemplo n.º 47
0
    def legend_test(self):
        self.mAtlasMap.setAtlasDriven(True)
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Auto)
        self.mAtlasMap.setAtlasMargin(0.10)

        # add a point layer
        ptLayer = QgsVectorLayer(
            "Point?crs=epsg:4326&field=attr:int(1)&field=label:string(20)",
            "points", "memory")

        pr = ptLayer.dataProvider()
        f1 = QgsFeature(1)
        f1.initAttributes(2)
        f1.setAttribute(0, 1)
        f1.setAttribute(1, "Test label 1")
        f1.setGeometry(QgsGeometry.fromPoint(QgsPoint(-0.638, 48.954)))
        f2 = QgsFeature(2)
        f2.initAttributes(2)
        f2.setAttribute(0, 2)
        f2.setAttribute(1, "Test label 2")
        f2.setGeometry(QgsGeometry.fromPoint(QgsPoint(-1.682, 48.550)))
        pr.addFeatures([f1, f2])

        # categorized symbology
        r = QgsCategorizedSymbolRendererV2("attr", [
            QgsRendererCategoryV2(
                1, QgsMarkerSymbolV2.createSimple({"color": "255,0,0"}),
                "red"),
            QgsRendererCategoryV2(
                2, QgsMarkerSymbolV2.createSimple({"color": "0,0,255"}),
                "blue")
        ])
        ptLayer.setRendererV2(r)

        QgsMapLayerRegistry.instance().addMapLayer(ptLayer)

        # add the point layer to the map settings
        layers = self.mapSettings.layers()
        layers = [ptLayer.id()] + layers
        self.mapSettings.setLayers(layers)

        # add a legend
        legend = QgsComposerLegend(self.mComposition)
        legend.moveBy(200, 100)
        # sets the legend filter parameter
        legend.setComposerMap(self.mAtlasMap)
        legend.setLegendFilterOutAtlas(True)
        self.mComposition.addComposerLegend(legend)

        self.mAtlas.beginRender()

        self.mAtlas.prepareForFeature(0)
        self.mLabel1.adjustSizeToText()

        checker = QgsCompositionChecker('atlas_legend', self.mComposition)
        myTestResult, myMessage = checker.testComposition()
        assert myTestResult

        self.mAtlas.endRender()

        # restore state
        self.mapSettings.setLayers([layers[1]])
        self.mComposition.removeComposerItem(legend)
        QgsMapLayerRegistry.instance().removeMapLayer(ptLayer.id())
Ejemplo n.º 48
0
 def newProject(self):
     """Create new project."""
     # noinspection PyArgumentList
     QgsMapLayerRegistry.instance().removeAllMapLayers()
Ejemplo n.º 49
0
    def run(self):
        """Run method that performs all the real work"""
        #create the dialog
        self.dlg = LeakDetectionDialog()
        self.dlg.comboBox.clear()
        self.dlg.comboBox_2.clear()
        #this is for pipe
        layer_list_pt = QgsMapLayerRegistry.instance().mapLayers().values()
        for layer in layer_list_pt:
            if layer.type() == QgsMapLayer.VectorLayer:
                self.dlg.comboBox.addItem(layer.name(), layer)
#for junction
        layer_list_line = QgsMapLayerRegistry.instance().mapLayers().values()
        print "layer now", layer_list_line
        for layer in layer_list_line:
            if layer.type() == QgsMapLayer.VectorLayer:
                #print "laye name",layer.name()
                self.dlg.comboBox_2.addItem(layer.name(), layer)

        self.dlg.lineEdit.clear()
        self.dlg.pushButton.clicked.connect(self.select_output_file)
        self.dlg.toolButton.clicked.connect(self.select_file_point)
        print "layer list line sabse pehle", layer_list_line, type(
            layer_list_line)
        self.dlg.toolButton_2.clicked.connect(self.select_file_line)
        # show the dialog
        self.dlg.show()

        # Clear the QComboBox before loading layers
        '''
        layers = QgsMapLayerRegistry.instance().mapLayers().values()
        for layer in layers:
            if layer.type() == QgsMapLayer.VectorLayer:
                self.dlg.comboBox.addItem( layer.name(), layer ) 
		
        layers = QgsMapLayerRegistry.instance().mapLayers().values()
        for layer in layers:
            if layer.type() == QgsMapLayer.VectorLayer:
                self.dlg.comboBox_2.addItem( layer.name(), layer ) 		
		
        '''

        #print "lay",lay

        #this is for junction
        #layers = self.iface.legendInterface().layers()
        '''	
        layers = self.iface.activeLayer()
        print "layers for pipe",layers			
        for layer in layers:
            layer_list_line.append(layer.name())
        print "layer check",layer_list_line	
        self.dlg.comboBox_2.addItems(layer_list_line)  
        '''

        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.

            filename = self.dlg.lineEdit.text()
            output_file = open(filename, 'w')
            selectedLayerIndex = self.dlg.comboBox_2.currentIndex(
            )  #this is needed for line data length,dia,fric so call the open_file function
            layer_list_line = QgsMapLayerRegistry.instance().mapLayers(
            ).values()
            #print "YO",selectedLayerIndex,layer_list_line

            selectedLayer = layer_list_line[selectedLayerIndex]
            print " laye rkaun hai", selectedLayer
            fields = selectedLayer.pendingFields()
            fieldnames = [field.name() for field in fields]
            print "names", fieldnames

            if "start_x" not in fieldnames:
                selectedLayer.dataProvider().addAttributes(
                    [QgsField("start_x", QVariant.Double)])
            if "end_x" not in fieldnames:
                selectedLayer.dataProvider().addAttributes(
                    [QgsField("end_x", QVariant.Double)])
            if "start_y" not in fieldnames:
                selectedLayer.dataProvider().addAttributes(
                    [QgsField("start_y", QVariant.Double)])
            if "end_y" not in fieldnames:
                selectedLayer.dataProvider().addAttributes(
                    [QgsField("end_y", QVariant.Double)])

#this is used to add new fiels i.e x_start,x_end,y_start,y_end from shape file to attribute table using regex
#selectedLayer.dataProvider().addAttributes([QgsField("start_x",QVariant.Double),QgsField("end_x",QVariant.Double),QgsField("start_y",QVariant.Double),QgsField("end_y",QVariant.Double)])
            selectedLayer.updateFields()
            selectedLayer.startEditing()

            idx1 = selectedLayer.fieldNameIndex("start_x")
            e1 = QgsExpression(""" $x_at(0) """)
            e1.prepare(selectedLayer.pendingFields())

            idx2 = selectedLayer.fieldNameIndex("end_x")
            e2 = QgsExpression(""" $x_at(-1) """)
            e2.prepare(selectedLayer.pendingFields())

            idy1 = selectedLayer.fieldNameIndex("start_y")
            e3 = QgsExpression(""" $y_at(0) """)
            e3.prepare(selectedLayer.pendingFields())

            idy2 = selectedLayer.fieldNameIndex("end_y")
            e4 = QgsExpression(""" $y_at(-1) """)
            e4.prepare(selectedLayer.pendingFields())

            for f in selectedLayer.getFeatures():
                f[idx1] = e1.evaluate(f)
                f[idx2] = e2.evaluate(f)
                f[idy1] = e3.evaluate(f)
                f[idy2] = e4.evaluate(f)
                selectedLayer.updateFeature(f)
            selectedLayer.commitChanges()

            #this is used to write teh attribute table to output file specified by user
            output_file.write(','.join(fieldnames) + '\n')
            for f in selectedLayer.getFeatures():
                line = ','.join(unicode(f[x]) for x in fieldnames) + '\n'
                unicode_line = line.encode('utf-8')
                #print "line",unicode_line
                output_file.write(unicode_line)
            output_file.close()
            #del output_file

            #this calls the main function which does all the flow rate calculations
            open_file(filename)
            #add_to_table_flow(data_dict)
            #index = self.dlg.layerCombo.currentIndex()
            #layer = self.dlg.layerCombo.itemData(index)
            #QMessageBox.information(self.iface.mainWindow(),"hello world","%s has %d features." %(layer.name(),layer.featureCount()))
            print "FIANLLL YY ", data_dict

            #this is used to add flow rates from the dictionary to attribute table
            if "flow rates" not in fieldnames:
                selectedLayer.dataProvider().addAttributes(
                    [QgsField("flow rates", QVariant.Double)])
            selectedLayer.updateFields()
            selectedLayer.startEditing()

            #idx1=selectedLayer.fieldNameIndex("flow rates")
            for feature in selectedLayer.getFeatures():
                node_1 = feature["node1"]
                node_2 = feature["node2"]
                #print "nodhfdv",node_1,node_2
                #for i in data_dict:
                ls = data_dict[int(node_1)]
                for m in range(0, len(ls)):
                    lls = ls[m]
                    node2 = lls[0]
                    flow = lls[4]

                    #print "node_1",node_1,node_2,node2,type(int(node_2)),type(node2),(int(node2)==int(node_2))
                    if int(node2) == int(node_2):
                        print "flow final for vector layer", flow
                        feature["flow rates"] = flow
                        selectedLayer.updateFeature(feature)
            selectedLayer.commitChanges()
            # Hello World program in Python
            '''
            selectedLayer.setCustomProperty("labeling/fieldname","flow rates")
            selectedLayer.setCustomProperty("labeling/placement",QgsPalLayerSettings.Line)
            selectedLayer.setCustomProperty("labeling/fontSize","8")
            selectedLayer.setCustomProperty("labeling/enabled","true")
            selectedLayer.triggerRepaint() 			
			'''
            '''
Ejemplo n.º 50
0
    def testCase(self):
        self.TEST_DATA_DIR = unitTestDataPath()
        tmppath = tempfile.mkdtemp()
        for file in glob.glob(
                os.path.join(self.TEST_DATA_DIR, 'france_parts.*')):
            shutil.copy(os.path.join(self.TEST_DATA_DIR, file), tmppath)
        vectorFileInfo = QFileInfo(tmppath + "/france_parts.shp")
        mVectorLayer = QgsVectorLayer(vectorFileInfo.filePath(),
                                      vectorFileInfo.completeBaseName(), "ogr")

        QgsMapLayerRegistry.instance().addMapLayers([mVectorLayer])

        # create composition with composer map
        self.mapSettings = QgsMapSettings()
        layerStringList = []
        layerStringList.append(mVectorLayer.id())
        self.mapSettings.setLayers(layerStringList)
        self.mapSettings.setCrsTransformEnabled(True)
        self.mapSettings.setMapUnits(QGis.Meters)

        # select epsg:2154
        crs = QgsCoordinateReferenceSystem()
        crs.createFromSrid(2154)
        self.mapSettings.setDestinationCrs(crs)

        self.mComposition = QgsComposition(self.mapSettings)
        self.mComposition.setPaperSize(297, 210)

        # fix the renderer, fill with green
        props = {"color": "0,127,0"}
        fillSymbol = QgsFillSymbolV2.createSimple(props)
        renderer = QgsSingleSymbolRendererV2(fillSymbol)
        mVectorLayer.setRendererV2(renderer)

        # the atlas map
        self.mAtlasMap = QgsComposerMap(self.mComposition, 20, 20, 130, 130)
        self.mAtlasMap.setFrameEnabled(True)
        self.mComposition.addComposerMap(self.mAtlasMap)

        # the atlas
        self.mAtlas = self.mComposition.atlasComposition()
        self.mAtlas.setCoverageLayer(mVectorLayer)
        self.mAtlas.setEnabled(True)
        self.mComposition.setAtlasMode(QgsComposition.ExportAtlas)

        # an overview
        mOverview = QgsComposerMap(self.mComposition, 180, 20, 50, 50)
        mOverview.setFrameEnabled(True)
        mOverview.setOverviewFrameMap(self.mAtlasMap.id())
        self.mComposition.addComposerMap(mOverview)
        nextent = QgsRectangle(49670.718, 6415139.086, 699672.519, 7065140.887)
        mOverview.setNewExtent(nextent)

        # set the fill symbol of the overview map
        props2 = {"color": "127,0,0,127"}
        fillSymbol2 = QgsFillSymbolV2.createSimple(props2)
        mOverview.setOverviewFrameMapSymbol(fillSymbol2)

        # header label
        self.mLabel1 = QgsComposerLabel(self.mComposition)
        self.mComposition.addComposerLabel(self.mLabel1)
        self.mLabel1.setText("[% \"NAME_1\" %] area")
        self.mLabel1.setFont(QgsFontUtils.getStandardTestFont())
        self.mLabel1.adjustSizeToText()
        self.mLabel1.setSceneRect(QRectF(150, 5, 60, 15))

        qWarning(
            "header label font: %s exactMatch:%s" %
            (self.mLabel1.font().toString(), self.mLabel1.font().exactMatch()))

        # feature number label
        self.mLabel2 = QgsComposerLabel(self.mComposition)
        self.mComposition.addComposerLabel(self.mLabel2)
        self.mLabel2.setText("# [%$feature || ' / ' || $numfeatures%]")
        self.mLabel2.setFont(QgsFontUtils.getStandardTestFont())
        self.mLabel2.adjustSizeToText()
        self.mLabel2.setSceneRect(QRectF(150, 200, 60, 15))

        qWarning(
            "feature number label font: %s exactMatch:%s" %
            (self.mLabel2.font().toString(), self.mLabel2.font().exactMatch()))

        self.filename_test()
        self.autoscale_render_test()
        self.autoscale_render_test_old_api()
        self.fixedscale_render_test()
        self.predefinedscales_render_test()
        self.hidden_render_test()
        self.legend_test()

        shutil.rmtree(tmppath, True)
Ejemplo n.º 51
0
 def tearDown(self):
     """Fixture run after each test"""
     QgsMapLayerRegistry.instance().removeAllMapLayers()
     DOCK.cboHazard.clear()
     DOCK.cboExposure.clear()
Ejemplo n.º 52
0
    def accept(self):
        """Do PetaBencana download and display it in QGIS.

        .. versionadded: 3.3
        """

        self.save_state()
        try:
            self.require_directory()
        except CanceledImportDialogError:
            return

        QtGui.qApp.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor))

        source = self.define_url()
        # save the file as json first
        name = 'jakarta_flood.json'
        output_directory = self.output_directory.text()
        output_prefix = self.filename_prefix.text()
        overwrite = self.overwrite_flag.isChecked()
        date_stamp_flag = self.include_date_flag.isChecked()
        output_base_file_path = self.get_output_base_path(
            output_directory,
            output_prefix,
            date_stamp_flag,
            name,
            overwrite)

        title = self.tr("Can't access API")

        try:
            self.download(source, output_base_file_path)

            # Open downloaded file as QgsMapLayer
            layer = QgsVectorLayer(
                output_base_file_path, 'flood', 'ogr', False)
        except Exception as e:
            disable_busy_cursor()
            QMessageBox.critical(self, title, str(e))
            return

        self.time_stamp = time.strftime('%d-%b-%Y %H:%M:%S')
        # Now save as shp
        name = 'jakarta_flood.shp'
        output_base_file_path = self.get_output_base_path(
            output_directory,
            output_prefix,
            date_stamp_flag,
            name,
            overwrite)
        QgsVectorFileWriter.writeAsVectorFormat(
            layer, output_base_file_path, 'CP1250', None, 'ESRI Shapefile')
        # Get rid of the GeoJSON layer and rather use local shp
        del layer

        self.copy_style(output_base_file_path)

        self.copy_keywords(output_base_file_path)
        layer = self.add_flooded_field(output_base_file_path)

        # check if the layer has feature or not
        if layer.featureCount() <= 0:
            city = self.city_combo_box.currentText()
            message = self.tr(
                'There are no floods data available on {city} '
                'at this time.').format(city=city)
            display_warning_message_box(
                self,
                self.tr('No data'),
                message)
            disable_busy_cursor()
        else:
            # add the layer to the map
            registry = QgsMapLayerRegistry.instance()
            registry.addMapLayer(layer)
            disable_busy_cursor()
            self.done(QDialog.Accepted)
Ejemplo n.º 53
0
 def layer(self):
     if self.getType() != self.FILE and self.combo.currentIndex() >= 0:
         layerID = self.combo.itemData(self.combo.currentIndex())
         return QgsMapLayerRegistry.instance().mapLayer(layerID)
     return None
Ejemplo n.º 54
0
    def run_error(self):
        print "EROR"
        #create the dialog
        self.dlg = FindErrorDialog()
        self.dlg.lineEdit.clear()

        self.dlg.toolButton.clicked.connect(self.select_sensor_data)
        self.dlg.toolButton_2.clicked.connect(self.select_equilibrium_data)
        self.dlg.checkBox.stateChanged.connect(self.select_canvas)
        layer_list_line = []
        layer_list_line = QgsMapLayerRegistry.instance().mapLayers().values()
        print "layer now FOR ERROR ", layer_list_line
        for layer in layer_list_line:
            if layer.type() == QgsMapLayer.VectorLayer:
                #print "laye name",layer.name()
                self.dlg.comboBox.addItem(layer.name(), layer)
        #show the dialog for form 2 wich is FindErrorDialog class
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            filename = self.dlg.lineEdit.text()
            print "filename", filename
            output_sensor_file = open(filename, "r")
            selectedLayerIndex = self.dlg.comboBox.currentIndex(
            )  #this is needed for line data length,dia,fric so call the open_file function
            layer_list_line = QgsMapLayerRegistry.instance().mapLayers(
            ).values()
            print "YO", selectedLayerIndex, layer_list_line

            selectedLayer = layer_list_line[selectedLayerIndex]
            print " ERROR LAYER", selectedLayer
            fields = selectedLayer.pendingFields()
            fieldnames = [field.name() for field in fields]
            print "names", type(fieldnames[0])

            open_file_sensor(filename)
            #print "dict for sensor",data_dict_sensor
            for feature in selectedLayer.getFeatures():
                node_1 = feature["node1"]
                node_2 = feature["node2"]
                flow_data = feature["flow rates"]
                #print "nodhfdv",node_1,node_2,flow_data,type(node_1)
                ls = []
                if int(node_1) in data_dict_sensor:
                    ls = data_dict_sensor[int(node_1)]
                    #print "lsss",ls,len(ls)
                for m in range(0, len(ls)):
                    lls = ls[m]
                    node2 = lls[0]
                    flow_sensor = lls[1]

                    #print "node_1",node_1,node_2,node2,type(int(node_2)),type(node2),(int(node2)==int(node_2))
                    if int(node2) == int(node_2):
                        if float(flow_data) == float(flow_sensor):
                            print " NO ERROR "

                        else:
                            print "ERROR in FLOW", node2, node_2, flow_sensor, flow_data, type(
                                flow_sensor), type(flow_data)
                            '''
							pay=QgsPalLayerSettings()
                            pay.readFromLayer(selectedLayer)
                            #print "layer",selectedLayer							
                            pay.enabled=True
                            pay.fieldName='flow rates'.encode('utf-8')           		
                            pay.placement=QgsPalLayerSettings.AroundPoint
                            pay.setDataDefinedProperty(QgsPalLayerSettings.Size,True,True,'20','')
                            pay.writeToLayer(selectedLayer)
                            QgsMapLayerRegistry.instance().addMapLayers([selectedLayer]) 
                            '''
                            selectedLayer.setCustomProperty("labelling", "pal")
                            selectedLayer.setCustomProperty(
                                "labeling/enabled", "true")
                            selectedLayer.setCustomProperty(
                                "labeling/fieldname", "flow rates")
                            #selectedLayer.setCustomProperty("labeling/placement",QgsPalLayerSettings.Line)
                            selectedLayer.setCustomProperty(
                                "labeling/fontSize", "8")

                        selectedLayer.triggerRepaint()
Ejemplo n.º 55
0
    def test_addMapLayerAlreadyAdded(self):
        """ test that already added layers can't be readded to registry """
        QgsMapLayerRegistry.instance().removeAllMapLayers()

        l1 = createLayer('test')
        QgsMapLayerRegistry.instance().addMapLayer(l1)
        self.assertEqual(
            len(QgsMapLayerRegistry.instance().mapLayersByName('test')), 1)
        self.assertEqual(QgsMapLayerRegistry.instance().count(), 1)
        self.assertEqual(QgsMapLayerRegistry.instance().addMapLayer(l1), None)
        self.assertEqual(
            len(QgsMapLayerRegistry.instance().mapLayersByName('test')), 1)
        self.assertEqual(QgsMapLayerRegistry.instance().count(), 1)

        QgsMapLayerRegistry.instance().removeAllMapLayers()
Ejemplo n.º 56
0
def addDiffLayers(repo, commit, commit2, layernames):

    styles = [diffStylePoints, diffStyleLines, diffStylePolygons]
    geomTypes = ["Point","LineString","Polygon"]
    beforeFilename = tempFilename("gpkg")
    repo.exportdiff(commit.commitid, commit2.commitid, beforeFilename)
    afterFilename = tempFilename("gpkg")
    repo.exportdiff(commit2.commitid, commit.commitid, afterFilename)
    for layername in layernames:
        styles = [diffStylePoints, diffStyleLines, diffStylePolygons]
        geomTypes = ["Point","LineString","Polygon"]
        beforeLayer = loadLayerNoCrsDialog("%s|layername=%s" % (beforeFilename, layername), layername, "ogr")
        afterLayer = loadLayerNoCrsDialog("%s|layername=%s" % (afterFilename, layername), layername, "ogr")
        beforeCon = sqlite3.connect(beforeFilename)
        beforeCursor = beforeCon.cursor()
        afterCon = sqlite3.connect(afterFilename)
        afterCursor = afterCon.cursor()

        attributes = [v[1] for v in beforeCursor.execute("PRAGMA table_info('%s');" % layername)]
        attrnames = [f.name() for f in beforeLayer.pendingFields()]

        layerFeatures = []

        beforeCursor.execute("SELECT * FROM %s_changes WHERE audit_op=2;" % layername)
        modified = beforeCursor.fetchall()
        for m in modified:
            geogigfid = m[0]
            beforeGpkgfid = gpkgfidFromGeogigfid(beforeCursor, layername, geogigfid)
            beforeCursor.execute("SELECT * FROM %s WHERE fid='%s';" % (layername, beforeGpkgfid))
            featureRow = beforeCursor.fetchone()
            attrs = {attr: featureRow[attributes.index(attr)] for attr in attrnames}
            attrs["changetype"] = MODIFIED_BEFORE
            request = QgsFeatureRequest()
            request.setFilterFid(beforeGpkgfid)
            feature = next(beforeLayer.getFeatures(request))
            layerFeatures.append({"attrs":attrs, "geom": QgsGeometry(feature.geometry())})
            afterGpkgfid = gpkgfidFromGeogigfid(afterCursor, layername, geogigfid)
            afterCursor.execute("SELECT * FROM %s WHERE fid='%s';" % (layername,afterGpkgfid))
            featureRow = afterCursor.fetchone()
            attrs = {attr: featureRow[attributes.index(attr)] for attr in attrnames}
            attrs["changetype"] = MODIFIED_AFTER
            request = QgsFeatureRequest()
            request.setFilterFid(afterGpkgfid)
            feature = next(afterLayer.getFeatures(request))
            layerFeatures.append({"attrs":attrs, "geom": QgsGeometry(feature.geometry())})


        afterCursor.execute("SELECT * FROM %s_changes WHERE audit_op=1;" % layername)
        added = afterCursor.fetchall()
        for a in added:
            geogigfid = a[0]
            afterGpkgfid = gpkgfidFromGeogigfid(afterCursor, layername, geogigfid)
            afterCursor.execute("SELECT * FROM %s WHERE fid='%s';" % (layername, afterGpkgfid))
            featureRow = afterCursor.fetchone()
            attrs = {attr: featureRow[attributes.index(attr)] for attr in attrnames}
            attrs["changetype"] = ADDED
            request = QgsFeatureRequest()
            request.setFilterFid(afterGpkgfid)
            feature = next(afterLayer.getFeatures(request))
            layerFeatures.append({"attrs":attrs, "geom": QgsGeometry(feature.geometry())})

        beforeCursor.execute("SELECT * FROM %s_changes WHERE audit_op=1;" % layername)
        removed = beforeCursor.fetchall()
        for r in removed:
            geogigfid = r[0]
            beforeGpkgfid = gpkgfidFromGeogigfid(beforeCursor, layername, geogigfid)
            beforeCursor.execute("SELECT * FROM %s WHERE fid='%s';" % (layername, beforeGpkgfid))
            featureRow = beforeCursor.fetchone()
            attrs = {attr: featureRow[attributes.index(attr)] for attr in attrnames}
            attrs["changetype"] = REMOVED
            request = QgsFeatureRequest()
            request.setFilterFid(beforeGpkgfid)
            feature = next(beforeLayer.getFeatures(request))
            layerFeatures.append({"attrs":attrs, "geom": QgsGeometry(feature.geometry())})

        if layerFeatures:
            attrnames.append("changetype")
            uriFields = "&".join(["field=%s" % f for f in attrnames])
            uri = "%s?crs=%s&%s" % (geomTypes[beforeLayer.geometryType()], beforeLayer.crs().authid(), uriFields)
            layer = QgsVectorLayer(uri, "%s(diff)" % layername, "memory")
            featuresList = []
            for feature in layerFeatures:
                qgsfeature = QgsFeature()
                qgsfeature.setGeometry(feature["geom"])
                qgsfeature.setAttributes([feature["attrs"][attr] for attr in attrnames])
                featuresList.append(qgsfeature)

            layer.dataProvider().addFeatures(featuresList)
            layer.updateExtents()
            QgsMapLayerRegistry.instance().addMapLayers([layer])
            layer.loadNamedStyle(styles[layer.geometryType()])
Ejemplo n.º 57
0
    def test_addRemoveLayersSignals(self):
        """ test that signals are correctly emitted when removing map layers"""
        QgsMapLayerRegistry.instance().removeAllMapLayers()

        layers_will_be_removed_spy = QSignalSpy(
            QgsMapLayerRegistry.instance().layersWillBeRemoved)
        layer_will_be_removed_spy_str = QSignalSpy(
            QgsMapLayerRegistry.instance().layerWillBeRemoved[str])
        layer_will_be_removed_spy_layer = QSignalSpy(
            QgsMapLayerRegistry.instance().layerWillBeRemoved[QgsMapLayer])
        layers_removed_spy = QSignalSpy(
            QgsMapLayerRegistry.instance().layersRemoved)
        layer_removed_spy = QSignalSpy(
            QgsMapLayerRegistry.instance().layerRemoved)
        remove_all_spy = QSignalSpy(QgsMapLayerRegistry.instance().removeAll)

        l1 = createLayer('l1')
        l2 = createLayer('l2')
        l3 = createLayer('l3')
        l4 = createLayer('l4')
        QgsMapLayerRegistry.instance().addMapLayers([l1, l2, l3, l4])

        # remove 1 layer
        QgsMapLayerRegistry.instance().removeMapLayer(l1)
        # can't seem to actually test the data which was emitted, so best we can do is test
        # the signal count
        self.assertEqual(len(layers_will_be_removed_spy), 1)
        self.assertEqual(len(layer_will_be_removed_spy_str), 1)
        self.assertEqual(len(layer_will_be_removed_spy_layer), 1)
        self.assertEqual(len(layers_removed_spy), 1)
        self.assertEqual(len(layer_removed_spy), 1)
        self.assertEqual(len(remove_all_spy), 0)
        self.assertEqual(QgsMapLayerRegistry.instance().count(), 3)

        # remove 2 layers at once
        QgsMapLayerRegistry.instance().removeMapLayers([l2.id(), l3.id()])
        self.assertEqual(len(layers_will_be_removed_spy), 2)
        self.assertEqual(len(layer_will_be_removed_spy_str), 3)
        self.assertEqual(len(layer_will_be_removed_spy_layer), 3)
        self.assertEqual(len(layers_removed_spy), 2)
        self.assertEqual(len(layer_removed_spy), 3)
        self.assertEqual(len(remove_all_spy), 0)
        self.assertEqual(QgsMapLayerRegistry.instance().count(), 1)

        # remove all
        QgsMapLayerRegistry.instance().removeAllMapLayers()
        self.assertEqual(len(layers_will_be_removed_spy), 3)
        self.assertEqual(len(layer_will_be_removed_spy_str), 4)
        self.assertEqual(len(layer_will_be_removed_spy_layer), 4)
        self.assertEqual(len(layers_removed_spy), 3)
        self.assertEqual(len(layer_removed_spy), 4)
        self.assertEqual(len(remove_all_spy), 1)

        #remove some layers which aren't in the registry
        QgsMapLayerRegistry.instance().removeMapLayers(['asdasd'])
        self.assertEqual(len(layers_will_be_removed_spy), 3)
        self.assertEqual(len(layer_will_be_removed_spy_str), 4)
        self.assertEqual(len(layer_will_be_removed_spy_layer), 4)
        self.assertEqual(len(layers_removed_spy), 3)
        self.assertEqual(len(layer_removed_spy), 4)
        self.assertEqual(len(remove_all_spy), 1)

        l5 = createLayer('test5')
        QgsMapLayerRegistry.instance().removeMapLayer(l5)
        self.assertEqual(len(layers_will_be_removed_spy), 3)
        self.assertEqual(len(layer_will_be_removed_spy_str), 4)
        self.assertEqual(len(layer_will_be_removed_spy_layer), 4)
        self.assertEqual(len(layers_removed_spy), 3)
        self.assertEqual(len(layer_removed_spy), 4)
        self.assertEqual(len(remove_all_spy), 1)
    def openNdviFile(self, file_name):
        """
        Open file with NDVI

        :param file_name: path to file with NDVI
        :type: unicode
        """

        self.LOGGER.info("opening NDVI file: %s", file_name)

        try:
            self.validateInputFilePath(file_name)
        except CalculatorException as e:
            self.LOGGER.info(e.message)
            self.dlg.show_error_message(self.getTranslation(e.title), self.getTranslation(e.message))
            return

        ndvi0_raster_layer = QgsRasterLayer(file_name, "NDVI - <0")

        layer_data_type = ndvi0_raster_layer.dataProvider().dataType(1)
        ndvi_thresholds = NdviThreshold().dataTypes.get(layer_data_type)
        if ndvi_thresholds is None:
            self.LOGGER.info("NDVI file - unknown data type")
            self.dlg.show_error_message(self.getTranslation("NDVI file open error"),
                                        self.getTranslation("Unknown data type"))
            ndvi_raster_layer = QgsRasterLayer(file_name, "NDVI")
            map_layer_registry = QgsMapLayerRegistry.instance()
            map_layer_registry.addMapLayer(ndvi_raster_layer)
            return

        ndvi025_raster_layer = QgsRasterLayer(file_name, "NDVI - 0-0.25")
        ndvi05_raster_layer = QgsRasterLayer(file_name, "NDVI - 0.25-0.5")
        ndvi075_raster_layer = QgsRasterLayer(file_name, "NDVI - 0.5-0.75")
        ndvi1_raster_layer = QgsRasterLayer(file_name, "NDVI - 0.75-1")

        algorithm = QgsContrastEnhancement.StretchToMinimumMaximum
        limits = QgsRaster.ContrastEnhancementMinMax
        ndvi0_raster_layer.setContrastEnhancement(algorithm, limits)
        ndvi025_raster_layer.setContrastEnhancement(algorithm, limits)
        ndvi05_raster_layer.setContrastEnhancement(algorithm, limits)
        ndvi075_raster_layer.setContrastEnhancement(algorithm, limits)
        ndvi1_raster_layer.setContrastEnhancement(algorithm, limits)

        colors_scheme = ColorsForNdviMap().getColorScheme(self.dlg.cbx_color_schemes.currentText())
        ndvi0_raster_layer.setRenderer(
            self.getRenderer(ndvi0_raster_layer.dataProvider(),
                             self.getColorMapForNdvi0(colors_scheme, ndvi_thresholds)))
        ndvi025_raster_layer.setRenderer(
            self.getRenderer(ndvi025_raster_layer.dataProvider(),
                             self.getColorMapForNdvi025(colors_scheme, ndvi_thresholds)))
        ndvi05_raster_layer.setRenderer(
            self.getRenderer(ndvi05_raster_layer.dataProvider(),
                             self.getColorMapForNdvi05(colors_scheme, ndvi_thresholds)))
        ndvi075_raster_layer.setRenderer(
            self.getRenderer(ndvi075_raster_layer.dataProvider(),
                             self.getColorMapForNdvi075(colors_scheme, ndvi_thresholds)))
        ndvi1_raster_layer.setRenderer(
            self.getRenderer(ndvi1_raster_layer.dataProvider(),
                             self.getColorMapForNdvi1(colors_scheme, ndvi_thresholds)))

        map_layer_registry = QgsMapLayerRegistry.instance()
        map_layer_registry.addMapLayer(ndvi0_raster_layer)
        map_layer_registry.addMapLayer(ndvi025_raster_layer)
        map_layer_registry.addMapLayer(ndvi05_raster_layer)
        map_layer_registry.addMapLayer(ndvi075_raster_layer)
        map_layer_registry.addMapLayer(ndvi1_raster_layer)
Ejemplo n.º 59
0
    def test_removeMapLayerByLayer(self):
        """ test removing a map layer by layer """
        QgsMapLayerRegistry.instance().removeAllMapLayers()

        # test no crash with empty registry
        QgsMapLayerRegistry.instance().removeMapLayer('bad')
        QgsMapLayerRegistry.instance().removeMapLayer(None)

        l1 = createLayer('test')
        l2 = createLayer('test2')

        QgsMapLayerRegistry.instance().addMapLayers([l1, l2])
        self.assertEqual(QgsMapLayerRegistry.instance().count(), 2)

        #remove bad layers
        QgsMapLayerRegistry.instance().removeMapLayer(None)
        self.assertEqual(QgsMapLayerRegistry.instance().count(), 2)
        l3 = createLayer('test3')
        QgsMapLayerRegistry.instance().removeMapLayer(l3)
        self.assertEqual(QgsMapLayerRegistry.instance().count(), 2)

        # remove valid layers
        QgsMapLayerRegistry.instance().removeMapLayer(l1)
        self.assertEqual(QgsMapLayerRegistry.instance().count(), 1)

        # test that layer has been deleted
        self.assertTrue(sip.isdeleted(l1))

        # remove second layer
        QgsMapLayerRegistry.instance().removeMapLayer(l2)
        self.assertEqual(QgsMapLayerRegistry.instance().count(), 0)
        self.assertTrue(sip.isdeleted(l2))

        # try removing a layer not in the registry
        l3 = createLayer('test3')
        QgsMapLayerRegistry.instance().removeMapLayer(l3)
        self.assertFalse(sip.isdeleted(l3))
Ejemplo n.º 60
0
    def test_addMapLayer(self):
        """ test adding individual map layers to registry """
        QgsMapLayerRegistry.instance().removeAllMapLayers()

        l1 = createLayer('test')
        self.assertEqual(QgsMapLayerRegistry.instance().addMapLayer(l1), l1)
        self.assertEqual(
            len(QgsMapLayerRegistry.instance().mapLayersByName('test')), 1)
        self.assertEqual(QgsMapLayerRegistry.instance().count(), 1)

        # adding a second layer should leave existing layers intact
        l2 = createLayer('test2')
        self.assertEqual(QgsMapLayerRegistry.instance().addMapLayer(l2), l2)
        self.assertEqual(
            len(QgsMapLayerRegistry.instance().mapLayersByName('test')), 1)
        self.assertEqual(
            len(QgsMapLayerRegistry.instance().mapLayersByName('test2')), 1)
        self.assertEqual(QgsMapLayerRegistry.instance().count(), 2)

        QgsMapLayerRegistry.instance().removeAllMapLayers()