コード例 #1
0
def saveLineGeometry(shapePath, geodata, spatialRef, geoFormat):
    """
    :param shapePath: Location of shape file
    :param geodata: x, y and z coordinate of line
    :param spatialRef: current spatial reference of qgis project
    :param geoFormat: Geodata export format
    """
    # Define fields for feature attributes. A QgsFields object is needed
    fields = QgsFields()
    writer = QgsVectorFileWriter(shapePath, 'UTF-8', fields,
                                 QgsWkbTypes.LineStringZ, spatialRef,
                                 geoFormat)

    if writer.hasError() != QgsVectorFileWriter.NoError:
        # TODO
        raise Exception('Vector Writer')

    lineVertices = []
    for coords in geodata:
        lineVertices.append(QgsPoint(coords[0], coords[1], coords[2]))

    feature = QgsFeature()
    feature.setGeometry(QgsGeometry.fromPolyline(lineVertices))
    feature.setId(1)
    writer.addFeatures([feature])
    del feature
    # Delete the writer to flush features to disk
    del writer
コード例 #2
0
	def fileHanddler(self, alayer, alist, filedirectory, name):
		crsSrc = alayer.crs()
		crsDes = QgsCoordinateReferenceSystem(crsSrc.authid())
		fieldz = QgsFields()
		fieldz.append(QgsField("Id", QVariant.Int))
		fieldz.append(QgsField("Ré", QVariant.String))
		fieldz.append(QgsField("Norte", QVariant.Double, "double", 23, 2))
		fieldz.append(QgsField("Este", QVariant.Double, "double", 23, 2))
		fieldz.append(QgsField("Longitude", QVariant.String))
		fieldz.append(QgsField("Latitude", QVariant.String))
		fieldz.append(QgsField("Vante", QVariant.String))
		fieldz.append(QgsField("Azimute", QVariant.String))
		fieldz.append(QgsField("Distancia", QVariant.Double, "double", 23, 2))

		writer = QgsVectorFileWriter(filedirectory+'/'+name, "UTF-8", fieldz, QgsWkbTypes.Point, crsDes,
			driverName="ESRI Shapefile")

		if writer.hasError() != QgsVectorFileWriter.NoError:
			print("Error when creating shapefile:", writer.errorMessage())

		writer.addFeatures(alist)
		del writer
		nwLayer = self.iface.addVectorLayer(filedirectory+'/'+name, "", "ogr")
		if not nwLayer:
			print("Layer failed to load!")
		return
コード例 #3
0
ファイル: vector.py プロジェクト: streamerset/QGIS
class VectorWriter:

    MEMORY_LAYER_PREFIX = 'memory:'

    def __init__(self, fileName, encoding, fields, geometryType,
                 crs, options=None):
        self.fileName = fileName
        self.isMemory = False
        self.memLayer = None
        self.writer = None

        if encoding is None:
            settings = QSettings()
            encoding = settings.value('/Processing/encoding', 'System', type=str)

        if self.fileName.startswith(self.MEMORY_LAYER_PREFIX):
            self.isMemory = True

            uri = GEOM_TYPE_MAP[geometryType] + "?uuid=" + unicode(uuid.uuid4())
            if crs.isValid():
                uri += '&crs=' + crs.authid()
            fieldsdesc = []
            for f in fields:
                qgsfield = _toQgsField(f)
                fieldsdesc.append('field=%s:%s' %(qgsfield.name(),
                                TYPE_MAP_MEMORY_LAYER.get(qgsfield.type(), "string")))
            if fieldsdesc:
                uri += '&' + '&'.join(fieldsdesc)

            self.memLayer = QgsVectorLayer(uri, self.fileName, 'memory')
            self.writer = self.memLayer.dataProvider()
        else:
            formats = QgsVectorFileWriter.supportedFiltersAndFormats()
            OGRCodes = {}
            for (key, value) in formats.items():
                extension = unicode(key)
                extension = extension[extension.find('*.') + 2:]
                extension = extension[:extension.find(' ')]
                OGRCodes[extension] = value

            extension = self.fileName[self.fileName.rfind('.') + 1:]
            if extension not in OGRCodes:
                extension = 'shp'
                self.filename = self.filename + 'shp'

            qgsfields = QgsFields()
            for field in fields:
                qgsfields.append(_toQgsField(field))

            self.writer = QgsVectorFileWriter(
                self.fileName, encoding,
                qgsfields, geometryType, crs, OGRCodes[extension])

    def addFeature(self, feature):
        if self.isMemory:
            self.writer.addFeatures([feature])
        else:
            self.writer.addFeature(feature)
コード例 #4
0
    def createGeopkgLayer(self, filepath, featureIterator):
        fields, geomAtt = self._fields()
        qgsfields = QgsFields()
        for f in fields:
            qgsfields.append(f)
        writer = QgsVectorFileWriter(
            filepath,
            "UTF-8",
            qgsfields,
            FeatureTypeHelper.typeNameConverter[geomAtt.type.lower()],
            QgsCoordinateReferenceSystem(geomAtt.SRS),
            driverName="GPKG")

        BATCHSIZE = 500

        def _batch(iterable, size):
            sourceiter = iter(iterable)
            while True:
                batchiter = islice(sourceiter, size)
                try:
                    yield chain([next(batchiter)], batchiter)
                except StopIteration:
                    return

        for batch in _batch(featureIterator, BATCHSIZE):
            success = writer.addFeatures(batch)
            if not success:
                error = writer.errorMessage()
                del writer
                raise Exception("geopkg save: " + error)
        writer.flushBuffer()
        # the only way to close the writer is to call the C++ destructor -- we use sip to do this
        sip.delete(writer)
        del writer  # remove from python
        addAuditTables(filepath)
コード例 #5
0
def savePointGeometry(path, geodata, label, spatialRef, geoFormat):
    """
    :param label: Name of poles
    :param path: Location of shape file
    :param geodata: x, y and z coordinate of poles
    :param spatialRef: current spatial reference of qgis project
    :param geoFormat: Geodata export format
    """

    # Define fields for feature attributes. A QgsFields object is needed
    stueNrName = tr('bezeichnung')
    fields = QgsFields()
    fields.append(QgsField(stueNrName, QVariant.String, 'text', 254))
    fields.append(QgsField('x', QVariant.Double))
    fields.append(QgsField('y', QVariant.Double))
    fields.append(QgsField('z', QVariant.Double))
    fields.append(QgsField('h', QVariant.Double))
    writer = QgsVectorFileWriter(path, 'UTF-8', fields, QgsWkbTypes.PointZ,
                                 spatialRef, geoFormat)

    if writer.hasError() != QgsVectorFileWriter.NoError:
        # TODO
        raise Exception('Vector Writer')

    features = []
    for idx, coords in enumerate(geodata):
        feature = QgsFeature()
        feature.setFields(fields)
        feature.setGeometry(QgsPoint(coords[0], coords[1], coords[2]))
        feature.setId(idx)
        feature.setAttribute(stueNrName, label[idx])
        feature.setAttribute('x', float(coords[0]))
        feature.setAttribute('y', float(coords[1]))
        feature.setAttribute('z', float(coords[2]))
        feature.setAttribute('h', float(coords[3]))
        features.append(feature)

    writer.addFeatures(features)
    # Delete the writer to flush features to disk
    del writer
コード例 #6
0
ファイル: vector.py プロジェクト: a11656358/QGIS
class VectorWriter:

    MEMORY_LAYER_PREFIX = 'memory:'
    POSTGIS_LAYER_PREFIX = 'postgis:'
    SPATIALITE_LAYER_PREFIX = 'spatialite:'

    nogeometry_extensions = [
        u'csv',
        u'dbf',
        u'ods',
        u'xlsx',
    ]

    def __init__(self, destination, encoding, fields, geometryType,
                 crs, options=None):
        self.destination = destination
        self.isNotFileBased = False
        self.layer = None
        self.writer = None

        if encoding is None:
            settings = QSettings()
            encoding = settings.value('/Processing/encoding', 'System', type=str)

        if self.destination.startswith(self.MEMORY_LAYER_PREFIX):
            self.isNotFileBased = True

            uri = GEOM_TYPE_MAP[geometryType] + "?uuid=" + unicode(uuid.uuid4())
            if crs.isValid():
                uri += '&crs=' + crs.authid()
            fieldsdesc = []
            for f in fields:
                qgsfield = _toQgsField(f)
                fieldsdesc.append('field=%s:%s' % (qgsfield.name(),
                                                   TYPE_MAP_MEMORY_LAYER.get(qgsfield.type(), "string")))
            if fieldsdesc:
                uri += '&' + '&'.join(fieldsdesc)

            self.layer = QgsVectorLayer(uri, self.destination, 'memory')
            self.writer = self.layer.dataProvider()
        elif self.destination.startswith(self.POSTGIS_LAYER_PREFIX):
            self.isNotFileBased = True
            uri = QgsDataSourceURI(self.destination[len(self.POSTGIS_LAYER_PREFIX):])
            connInfo = uri.connectionInfo()
            (success, user, passwd) = QgsCredentials.instance().get(connInfo, None, None)
            if success:
                QgsCredentials.instance().put(connInfo, user, passwd)
            else:
                raise GeoAlgorithmExecutionException("Couldn't connect to database")
            print uri.uri()
            try:
                db = postgis_utils.GeoDB(host=uri.host(), port=int(uri.port()),
                                         dbname=uri.database(), user=user, passwd=passwd)
            except postgis_utils.DbError as e:
                raise GeoAlgorithmExecutionException(
                    "Couldn't connect to database:\n%s" % e.message)

            def _runSQL(sql):
                try:
                    db._exec_sql_and_commit(unicode(sql))
                except postgis_utils.DbError as e:
                    raise GeoAlgorithmExecutionException(
                        'Error creating output PostGIS table:\n%s' % e.message)

            fields = [_toQgsField(f) for f in fields]
            fieldsdesc = ",".join('%s %s' % (f.name(),
                                             TYPE_MAP_POSTGIS_LAYER.get(f.type(), "VARCHAR"))
                                  for f in fields)

            _runSQL("CREATE TABLE %s.%s (%s)" % (uri.schema(), uri.table().lower(), fieldsdesc))
            if geometryType != QGis.WKBNoGeometry:
                _runSQL("SELECT AddGeometryColumn('{schema}', '{table}', 'the_geom', {srid}, '{typmod}', 2)".format(
                    table=uri.table().lower(), schema=uri.schema(), srid=crs.authid().split(":")[-1],
                    typmod=GEOM_TYPE_MAP[geometryType].upper()))

            self.layer = QgsVectorLayer(uri.uri(), uri.table(), "postgres")
            self.writer = self.layer.dataProvider()
        elif self.destination.startswith(self.SPATIALITE_LAYER_PREFIX):
            self.isNotFileBased = True
            uri = QgsDataSourceURI(self.destination[len(self.SPATIALITE_LAYER_PREFIX):])
            print uri.uri()
            try:
                db = spatialite_utils.GeoDB(uri=uri)
            except spatialite_utils.DbError as e:
                raise GeoAlgorithmExecutionException(
                    "Couldn't connect to database:\n%s" % e.message)

            def _runSQL(sql):
                try:
                    db._exec_sql_and_commit(unicode(sql))
                except spatialite_utils.DbError as e:
                    raise GeoAlgorithmExecutionException(
                        'Error creating output Spatialite table:\n%s' % unicode(e))

            fields = [_toQgsField(f) for f in fields]
            fieldsdesc = ",".join('%s %s' % (f.name(),
                                             TYPE_MAP_SPATIALITE_LAYER.get(f.type(), "VARCHAR"))
                                  for f in fields)

            _runSQL("DROP TABLE IF EXISTS %s" % uri.table().lower())
            _runSQL("CREATE TABLE %s (%s)" % (uri.table().lower(), fieldsdesc))
            if geometryType != QGis.WKBNoGeometry:
                _runSQL("SELECT AddGeometryColumn('{table}', 'the_geom', {srid}, '{typmod}', 2)".format(
                    table=uri.table().lower(), srid=crs.authid().split(":")[-1],
                    typmod=GEOM_TYPE_MAP[geometryType].upper()))

            self.layer = QgsVectorLayer(uri.uri(), uri.table(), "spatialite")
            self.writer = self.layer.dataProvider()
        else:
            formats = QgsVectorFileWriter.supportedFiltersAndFormats()
            OGRCodes = {}
            for (key, value) in formats.items():
                extension = unicode(key)
                extension = extension[extension.find('*.') + 2:]
                extension = extension[:extension.find(' ')]
                OGRCodes[extension] = value
            OGRCodes['dbf'] = "DBF file"

            extension = self.destination[self.destination.rfind('.') + 1:]

            if extension not in OGRCodes:
                extension = 'shp'
                self.destination = self.destination + '.shp'

            if geometryType == QGis.WKBNoGeometry:
                if extension == 'shp':
                    extension = 'dbf'
                    self.destination = self.destination[:self.destination.rfind('.')] + '.dbf'
                if extension not in self.nogeometry_extensions:
                    raise GeoAlgorithmExecutionException(
                        "Unsupported format for tables with no geometry")

            qgsfields = QgsFields()
            for field in fields:
                qgsfields.append(_toQgsField(field))

            self.writer = QgsVectorFileWriter(self.destination, encoding,
                                              qgsfields, geometryType, crs, OGRCodes[extension])

    def addFeature(self, feature):
        if self.isNotFileBased:
            self.writer.addFeatures([feature])
        else:
            self.writer.addFeature(feature)
コード例 #7
0
ファイル: vector.py プロジェクト: rui88/QGIS
class VectorWriter(object):

    MEMORY_LAYER_PREFIX = 'memory:'
    POSTGIS_LAYER_PREFIX = 'postgis:'
    SPATIALITE_LAYER_PREFIX = 'spatialite:'

    nogeometry_extensions = [
        u'csv',
        u'dbf',
        u'ods',
        u'xlsx',
    ]

    def __init__(self,
                 destination,
                 encoding,
                 fields,
                 geometryType,
                 crs,
                 options=None):
        self.destination = destination
        self.isNotFileBased = False
        self.layer = None
        self.writer = None

        if encoding is None:
            settings = QSettings()
            encoding = settings.value('/Processing/encoding',
                                      'System',
                                      type=str)

        if self.destination.startswith(self.MEMORY_LAYER_PREFIX):
            self.isNotFileBased = True

            uri = QgsWkbTypes.displayString(geometryType) + "?uuid=" + str(
                uuid.uuid4())
            if crs.isValid():
                uri += '&crs=' + crs.authid()
            fieldsdesc = []
            for f in fields:
                qgsfield = _toQgsField(f)
                fieldsdesc.append(
                    'field=%s:%s' %
                    (qgsfield.name(),
                     TYPE_MAP_MEMORY_LAYER.get(qgsfield.type(), "string")))
            if fieldsdesc:
                uri += '&' + '&'.join(fieldsdesc)

            self.layer = QgsVectorLayer(uri, self.destination, 'memory')
            self.writer = self.layer.dataProvider()
        elif self.destination.startswith(self.POSTGIS_LAYER_PREFIX):
            self.isNotFileBased = True
            uri = QgsDataSourceUri(
                self.destination[len(self.POSTGIS_LAYER_PREFIX):])
            connInfo = uri.connectionInfo()
            (success, user,
             passwd) = QgsCredentials.instance().get(connInfo, None, None)
            if success:
                QgsCredentials.instance().put(connInfo, user, passwd)
            else:
                raise GeoAlgorithmExecutionException(
                    "Couldn't connect to database")
            # fix_print_with_import
            print(uri.uri())
            try:
                db = postgis.GeoDB(host=uri.host(),
                                   port=int(uri.port()),
                                   dbname=uri.database(),
                                   user=user,
                                   passwd=passwd)
            except postgis.DbError as e:
                raise GeoAlgorithmExecutionException(
                    "Couldn't connect to database:\n%s" % e.message)

            def _runSQL(sql):
                try:
                    db._exec_sql_and_commit(str(sql))
                except postgis.DbError as e:
                    raise GeoAlgorithmExecutionException(
                        'Error creating output PostGIS table:\n%s' % e.message)

            fields = [_toQgsField(f) for f in fields]
            fieldsdesc = ",".join(
                '%s %s' %
                (f.name(), TYPE_MAP_POSTGIS_LAYER.get(f.type(), "VARCHAR"))
                for f in fields)

            _runSQL("CREATE TABLE %s.%s (%s)" %
                    (uri.schema(), uri.table().lower(), fieldsdesc))
            if geometryType != QgsWkbTypes.NullGeometry:
                _runSQL(
                    "SELECT AddGeometryColumn('{schema}', '{table}', 'the_geom', {srid}, '{typmod}', 2)"
                    .format(table=uri.table().lower(),
                            schema=uri.schema(),
                            srid=crs.authid().split(":")[-1],
                            typmod=QgsWkbTypes.displayString(
                                geometryType).upper()))

            self.layer = QgsVectorLayer(uri.uri(), uri.table(), "postgres")
            self.writer = self.layer.dataProvider()
        elif self.destination.startswith(self.SPATIALITE_LAYER_PREFIX):
            self.isNotFileBased = True
            uri = QgsDataSourceUri(
                self.destination[len(self.SPATIALITE_LAYER_PREFIX):])
            # fix_print_with_import
            print(uri.uri())
            try:
                db = spatialite.GeoDB(uri=uri)
            except spatialite.DbError as e:
                raise GeoAlgorithmExecutionException(
                    "Couldn't connect to database:\n%s" % e.message)

            def _runSQL(sql):
                try:
                    db._exec_sql_and_commit(str(sql))
                except spatialite.DbError as e:
                    raise GeoAlgorithmExecutionException(
                        'Error creating output Spatialite table:\n%s' % str(e))

            fields = [_toQgsField(f) for f in fields]
            fieldsdesc = ",".join(
                '%s %s' %
                (f.name(), TYPE_MAP_SPATIALITE_LAYER.get(f.type(), "VARCHAR"))
                for f in fields)

            _runSQL("DROP TABLE IF EXISTS %s" % uri.table().lower())
            _runSQL("CREATE TABLE %s (%s)" % (uri.table().lower(), fieldsdesc))
            if geometryType != QgsWkbTypes.NullGeometry:
                _runSQL(
                    "SELECT AddGeometryColumn('{table}', 'the_geom', {srid}, '{typmod}', 2)"
                    .format(table=uri.table().lower(),
                            srid=crs.authid().split(":")[-1],
                            typmod=QgsWkbTypes.displayString(
                                geometryType).upper()))

            self.layer = QgsVectorLayer(uri.uri(), uri.table(), "spatialite")
            self.writer = self.layer.dataProvider()
        else:
            formats = QgsVectorFileWriter.supportedFiltersAndFormats()
            OGRCodes = {}
            for (key, value) in list(formats.items()):
                extension = str(key)
                extension = extension[extension.find('*.') + 2:]
                extension = extension[:extension.find(' ')]
                OGRCodes[extension] = value
            OGRCodes['dbf'] = "DBF file"

            extension = self.destination[self.destination.rfind('.') + 1:]

            if extension not in OGRCodes:
                extension = 'shp'
                self.destination = self.destination + '.shp'

            if geometryType == QgsWkbTypes.NoGeometry:
                if extension == 'shp':
                    extension = 'dbf'
                    self.destination = self.destination[:self.destination.
                                                        rfind('.')] + '.dbf'
                if extension not in self.nogeometry_extensions:
                    raise GeoAlgorithmExecutionException(
                        "Unsupported format for tables with no geometry")

            qgsfields = QgsFields()
            for field in fields:
                qgsfields.append(_toQgsField(field))

            # use default dataset/layer options
            dataset_options = QgsVectorFileWriter.defaultDatasetOptions(
                OGRCodes[extension])
            layer_options = QgsVectorFileWriter.defaultLayerOptions(
                OGRCodes[extension])

            self.writer = QgsVectorFileWriter(self.destination, encoding,
                                              qgsfields, geometryType, crs,
                                              OGRCodes[extension],
                                              dataset_options, layer_options)

    def addFeature(self, feature):
        if self.isNotFileBased:
            self.writer.addFeatures([feature])
        else:
            self.writer.addFeature(feature)
コード例 #8
0
ファイル: vector.py プロジェクト: nyalldawson/QGIS
class VectorWriter(object):

    MEMORY_LAYER_PREFIX = "memory:"
    POSTGIS_LAYER_PREFIX = "postgis:"
    SPATIALITE_LAYER_PREFIX = "spatialite:"

    nogeometry_extensions = [u"csv", u"dbf", u"ods", u"xlsx"]

    def __init__(self, destination, encoding, fields, geometryType, crs, options=None):
        self.destination = destination
        self.isNotFileBased = False
        self.layer = None
        self.writer = None

        if encoding is None:
            settings = QSettings()
            encoding = settings.value("/Processing/encoding", "System", str)

        if self.destination.startswith(self.MEMORY_LAYER_PREFIX):
            self.isNotFileBased = True

            uri = QgsWkbTypes.displayString(geometryType) + "?uuid=" + str(uuid.uuid4())
            if crs.isValid():
                uri += "&crs=" + crs.authid()
            fieldsdesc = []
            for f in fields:
                qgsfield = _toQgsField(f)
                fieldsdesc.append(
                    "field=%s:%s" % (qgsfield.name(), TYPE_MAP_MEMORY_LAYER.get(qgsfield.type(), "string"))
                )
            if fieldsdesc:
                uri += "&" + "&".join(fieldsdesc)

            self.layer = QgsVectorLayer(uri, self.destination, "memory")
            self.writer = self.layer.dataProvider()
        elif self.destination.startswith(self.POSTGIS_LAYER_PREFIX):
            self.isNotFileBased = True
            uri = QgsDataSourceUri(self.destination[len(self.POSTGIS_LAYER_PREFIX) :])
            connInfo = uri.connectionInfo()
            (success, user, passwd) = QgsCredentials.instance().get(connInfo, None, None)
            if success:
                QgsCredentials.instance().put(connInfo, user, passwd)
            else:
                raise GeoAlgorithmExecutionException("Couldn't connect to database")
            try:
                db = postgis.GeoDB(
                    host=uri.host(), port=int(uri.port()), dbname=uri.database(), user=user, passwd=passwd
                )
            except postgis.DbError as e:
                raise GeoAlgorithmExecutionException("Couldn't connect to database:\n%s" % e.message)

            def _runSQL(sql):
                try:
                    db._exec_sql_and_commit(str(sql))
                except postgis.DbError as e:
                    raise GeoAlgorithmExecutionException("Error creating output PostGIS table:\n%s" % e.message)

            fields = [_toQgsField(f) for f in fields]
            fieldsdesc = ",".join("%s %s" % (f.name(), TYPE_MAP_POSTGIS_LAYER.get(f.type(), "VARCHAR")) for f in fields)

            _runSQL("CREATE TABLE %s.%s (%s)" % (uri.schema(), uri.table().lower(), fieldsdesc))
            if geometryType != QgsWkbTypes.NullGeometry:
                _runSQL(
                    "SELECT AddGeometryColumn('{schema}', '{table}', 'the_geom', {srid}, '{typmod}', 2)".format(
                        table=uri.table().lower(),
                        schema=uri.schema(),
                        srid=crs.authid().split(":")[-1],
                        typmod=QgsWkbTypes.displayString(geometryType).upper(),
                    )
                )

            self.layer = QgsVectorLayer(uri.uri(), uri.table(), "postgres")
            self.writer = self.layer.dataProvider()
        elif self.destination.startswith(self.SPATIALITE_LAYER_PREFIX):
            self.isNotFileBased = True
            uri = QgsDataSourceUri(self.destination[len(self.SPATIALITE_LAYER_PREFIX) :])
            try:
                db = spatialite.GeoDB(uri=uri)
            except spatialite.DbError as e:
                raise GeoAlgorithmExecutionException("Couldn't connect to database:\n%s" % e.message)

            def _runSQL(sql):
                try:
                    db._exec_sql_and_commit(str(sql))
                except spatialite.DbError as e:
                    raise GeoAlgorithmExecutionException("Error creating output Spatialite table:\n%s" % str(e))

            fields = [_toQgsField(f) for f in fields]
            fieldsdesc = ",".join(
                "%s %s" % (f.name(), TYPE_MAP_SPATIALITE_LAYER.get(f.type(), "VARCHAR")) for f in fields
            )

            _runSQL("DROP TABLE IF EXISTS %s" % uri.table().lower())
            _runSQL("CREATE TABLE %s (%s)" % (uri.table().lower(), fieldsdesc))
            if geometryType != QgsWkbTypes.NullGeometry:
                _runSQL(
                    "SELECT AddGeometryColumn('{table}', 'the_geom', {srid}, '{typmod}', 2)".format(
                        table=uri.table().lower(),
                        srid=crs.authid().split(":")[-1],
                        typmod=QgsWkbTypes.displayString(geometryType).upper(),
                    )
                )

            self.layer = QgsVectorLayer(uri.uri(), uri.table(), "spatialite")
            self.writer = self.layer.dataProvider()
        else:
            formats = QgsVectorFileWriter.supportedFiltersAndFormats()
            OGRCodes = {}
            for (key, value) in list(formats.items()):
                extension = str(key)
                extension = extension[extension.find("*.") + 2 :]
                extension = extension[: extension.find(" ")]
                OGRCodes[extension] = value
            OGRCodes["dbf"] = "DBF file"

            extension = self.destination[self.destination.rfind(".") + 1 :]

            if extension not in OGRCodes:
                extension = "shp"
                self.destination = self.destination + ".shp"

            if geometryType == QgsWkbTypes.NoGeometry:
                if extension == "shp":
                    extension = "dbf"
                    self.destination = self.destination[: self.destination.rfind(".")] + ".dbf"
                if extension not in self.nogeometry_extensions:
                    raise GeoAlgorithmExecutionException("Unsupported format for tables with no geometry")

            qgsfields = QgsFields()
            for field in fields:
                qgsfields.append(_toQgsField(field))

            # use default dataset/layer options
            dataset_options = QgsVectorFileWriter.defaultDatasetOptions(OGRCodes[extension])
            layer_options = QgsVectorFileWriter.defaultLayerOptions(OGRCodes[extension])

            self.writer = QgsVectorFileWriter(
                self.destination,
                encoding,
                qgsfields,
                geometryType,
                crs,
                OGRCodes[extension],
                dataset_options,
                layer_options,
            )

    def addFeature(self, feature):
        if self.isNotFileBased:
            self.writer.addFeatures([feature])
        else:
            self.writer.addFeature(feature)
コード例 #9
0
    accumulator[str(i)] = set(accumulator[str(i)])
    fields = QgsFields()
    fields.append(QgsField("id", QVariant.String))
    writer = QgsVectorFileWriter(
        os.path.join(projectPath, "data/hexagon_" + str(i) + ".shp"),
        "UTF8", fields, QgsWkbTypes.Polygon,
        QgsCoordinateReferenceSystem('EPSG:4326'), "ESRI Shapefile")
    features = []
    for j in accumulator[str(i)]:
        f = QgsFeature()
        f.setGeometry(
            QgsGeometry.fromPolygonXY(
                [[QgsPointXY(c[0], c[1]) for c in h3.h3_to_geo_boundary(j)]]))
        f.setAttributes([j])
        features.append(f)
    writer.addFeatures(features)

for i in r:
    layer = QgsVectorLayer(
        os.path.join(projectPath, "data/hexagon_" + str(i) + ".shp"),
        "Hexagons " + str(i), "ogr")
    QgsProject.instance().addMapLayer(layer)

for i in r:
    processing.run(
        'qgis:countpointsinpolygon', {
            'CLASSFIELD':
            None,
            'FIELD':
            'numpoints',
            'POLYGONS':