Exemplo n.º 1
0
    def fieldName2key(fieldName):
        from settings_dlg import Settings

        if not Settings.longitudeField().isEmpty() and \
          fieldName.startsWith( Settings.longitudeField(), Qt.CaseInsensitive ):
            return 'longitude'
        if not Settings.latitudeField().isEmpty() and \
          fieldName.startsWith( Settings.latitudeField(), Qt.CaseInsensitive ):
            return 'latitude'
        if not Settings.magnitudeField().isEmpty() and \
          fieldName.startsWith( Settings.magnitudeField(), Qt.CaseInsensitive ):
            return 'magnitude'
        if not Settings.depthField().isEmpty() and \
          fieldName.startsWith( Settings.depthField(), Qt.CaseInsensitive ):
            return 'depth'
        if not Settings.dateField().isEmpty() and \
          fieldName.startsWith( Settings.dateField(), Qt.CaseInsensitive ):
            return 'date'

        return None
Exemplo n.º 2
0
	def fieldName2key( fieldName ):
		from settings_dlg import Settings

		if not Settings.longitudeField().isEmpty() and \
				fieldName.startsWith( Settings.longitudeField(), Qt.CaseInsensitive ):
			return 'longitude'
		if not Settings.latitudeField().isEmpty() and \
				fieldName.startsWith( Settings.latitudeField(), Qt.CaseInsensitive ):
			return 'latitude'
		if not Settings.magnitudeField().isEmpty() and \
				fieldName.startsWith( Settings.magnitudeField(), Qt.CaseInsensitive ):
			return 'magnitude'
		if not Settings.depthField().isEmpty() and \
				fieldName.startsWith( Settings.depthField(), Qt.CaseInsensitive ):
			return 'depth'
		if not Settings.dateField().isEmpty() and \
				fieldName.startsWith( Settings.dateField(), Qt.CaseInsensitive ):
			return 'date'

		return None
Exemplo n.º 3
0
	def run(self):
		outPath = unicode(self.outUri.database())
		inPath = unicode(self.inLayer.source())

		tempVrt = None
		if self.inLayer.providerType() == 'delimitedtext':
			# create the VRT which wraps the csv
			tempVrt = QTemporaryFile( u"%s/gem_mt_XXXXXX.vrt" % QDir.tempPath() )
			tempVrt.setAutoRemove(False)
			if not tempVrt.open( QIODevice.WriteOnly ):
				return False

			inPath = QUrl(inPath).toLocalFile()
			layerName = QFileInfo(inPath).baseName()
			vrtData = u"""<OGRVRTDataSource>
    <OGRVRTLayer name="%s">
        <SrcDataSource>%s</SrcDataSource>
        <GeometryType>wkbPoint</GeometryType>
        <LayerSRS>WGS84</LayerSRS>""" % (layerName, inPath)
			tempVrt.write( vrtData )

			from settings_dlg import Settings
			longField = Settings.longitudeField()
			latField = Settings.latitudeField()
			vrtData = u"""
        <GeometryField encoding="PointFromColumns" x="%s" y="%s"/>""" % (longField, latField)
			tempVrt.write( vrtData )

			def ogrTypeName(fld):
				if fld.type() == QVariant.Int:
					return "Integer"
				elif fld.type() == QVariant.Double:
					return  "Real"
				return "String"

			# add fields definition
			for index, fld in self.inLayer.dataProvider().fields().iteritems():
				vrtData = u"""
        <Field name="%s" type="%s"/>""" % (fld.name(), ogrTypeName(fld))
				tempVrt.write( vrtData )

			vrtData = u"""
    </OGRVRTLayer>
</OGRVRTDataSource>"""
			tempVrt.write( vrtData )

			tempVrt.close()

			inPath = unicode(tempVrt.fileName())
		
		self.process = QProcess()
		QObject.connect( self.process, SIGNAL("finished(int, QProcess::ExitStatus)"),  self._processFinished )

		self.process.start("ogr2ogr", ["-f","SQLite", "-dsco","SPATIALITE=YES", "-gt","65535", "-overwrite", outPath, inPath])
		#print "ogr2ogr", " ".join(["-f","SQLite", "-dsco","SPATIALITE=YES", "-gt","65535", "-overwrite", outPath, inPath])
		self.eventLoop.exec_()

		# cleanup
		self._cancelProcess()

		if tempVrt:
			tempVrt.remove()
			tempVrt.deleteLater()
		tempVrt = None

		return self._retCode == 0
Exemplo n.º 4
0
	def run(self):
		# layer base name and dir path
		base_name = QFileInfo(self._fn).baseName()
		dir_path = QFileInfo(self._fn).absoluteDir()

		# create the uri for the delimitedtext provider
		from .settings_dlg import Settings
		csvUrl = QUrl.fromLocalFile( self._fn )
		csvUrl.setQueryItems( [
			( "delimiter", Settings.delimiter() ),
			( "delimiterType", "plain"),
			( "xField", Settings.longitudeField() ),
			( "yField", Settings.latitudeField() )
		] )

		# load the layer
		from qgis.core import QgsVectorLayer
		csvVl = QgsVectorLayer(csvUrl.toString(), base_name, "delimitedtext")
		if not csvVl.isValid():	# invalid layer
			csvVl.deleteLater()
			QMessageBox.warning( self.parent(), "Invalid layer", 
								u"Unable to load the layer %s" % self._fn )
			return (self.INVALID_INPUT, None)

		# check the layer geometry type
		from qgis.core import QGis
		if csvVl.geometryType() != QGis.Point:
			csvVl.deleteLater()
			QMessageBox.warning( self.parent(), "Invalid layer", 
								u"Unable to get data from the selected file. \nSetup Lat/Long field names and delimiter from the Settings dialog, \nthen try again." )
			return (self.INVALID_LATLON, None)

		# check whether the CSV file has to be imported to SL db
		if not Settings.importCsvToSl():
			return (self.OK, csvVl)

		# uri pointing to the new SL database
		from qgis.core import QgsDataSourceURI
		sqlite_path = dir_path.absoluteFilePath( u"%s.sqlite" % base_name )
		slUri = QgsDataSourceURI()
		slUri.setDatabase( sqlite_path )
		slUri.setDataSource( "", base_name, "GEOMETRY" )

		importer = Ogr2ogrImporter(csvVl, slUri, self.parent())
		#importer = QGisLayerImporter(csvVl, slUri, self.parent())
		ret = importer.start()

		# get the importer exit code
		if not ret:
			if importer.wasCanceled():
				ret = self.CANCELED
			else:
				ret = self.ERROR
				QMessageBox.warning( self.parent(), "Error", importer.errorMessage() )
		else:
			ret = self.OK

		# cleanup
		importer.deleteLater()
		importer = None

		csvVl.deleteLater()
		csvVl = None

		if ret != self.OK:
			return (ret, None)

		# load the layer from the SL database
		slVl = QgsVectorLayer(slUri.uri(), slUri.table(), "spatialite")
		if not slVl.isValid():	# invalid layer
			slVl.deleteLater()
			QMessageBox.warning( self.parent(),	"Invalid layer",
								u"Unable to load the layer %s" % slUri.database() )
			return (self.ERROR, None)

		# check the layer geometry type
		if slVl.geometryType() != QGis.Point:
			slVl.deleteLater()
			return (self.ERROR, None)

		return (self.OK, slVl)
Exemplo n.º 5
0
    def run(self):
        outPath = unicode(self.outUri.database())
        inPath = unicode(self.inLayer.source())

        tempVrt = None
        if self.inLayer.providerType() == 'delimitedtext':
            # create the VRT which wraps the csv
            tempVrt = QTemporaryFile(u"%s/gem_mt_XXXXXX.vrt" % QDir.tempPath())
            tempVrt.setAutoRemove(False)
            if not tempVrt.open(QIODevice.WriteOnly):
                return False

            inPath = QUrl(inPath).toLocalFile()
            layerName = QFileInfo(inPath).baseName()
            vrtData = u"""<OGRVRTDataSource>
    <OGRVRTLayer name="%s">
        <SrcDataSource>%s</SrcDataSource>
        <GeometryType>wkbPoint</GeometryType>
        <LayerSRS>WGS84</LayerSRS>""" % (layerName, inPath)
            tempVrt.write(vrtData)

            from settings_dlg import Settings
            longField = Settings.longitudeField()
            latField = Settings.latitudeField()
            vrtData = u"""
        <GeometryField encoding="PointFromColumns" x="%s" y="%s"/>""" % (
                longField, latField)
            tempVrt.write(vrtData)

            def ogrTypeName(fld):
                if fld.type() == QVariant.Int:
                    return "Integer"
                elif fld.type() == QVariant.Double:
                    return "Real"
                return "String"

            # add fields definition
            for index, fld in self.inLayer.dataProvider().fields().iteritems():
                vrtData = u"""
        <Field name="%s" type="%s"/>""" % (fld.name(), ogrTypeName(fld))
                tempVrt.write(vrtData)

            vrtData = u"""
    </OGRVRTLayer>
</OGRVRTDataSource>"""
            tempVrt.write(vrtData)

            tempVrt.close()

            inPath = unicode(tempVrt.fileName())

        self.process = QProcess()
        QObject.connect(self.process,
                        SIGNAL("finished(int, QProcess::ExitStatus)"),
                        self._processFinished)

        self.process.start("ogr2ogr", [
            "-f", "SQLite", "-dsco", "SPATIALITE=YES", "-gt", "65535",
            "-overwrite", outPath, inPath
        ])
        #print "ogr2ogr", " ".join(["-f","SQLite", "-dsco","SPATIALITE=YES", "-gt","65535", "-overwrite", outPath, inPath])
        self.eventLoop.exec_()

        # cleanup
        self._cancelProcess()

        if tempVrt:
            tempVrt.remove()
            tempVrt.deleteLater()
        tempVrt = None

        return self._retCode == 0
Exemplo n.º 6
0
    def run(self):
        # layer base name and dir path
        base_name = QFileInfo(self._fn).baseName()
        dir_path = QFileInfo(self._fn).absoluteDir()

        # create the uri for the delimitedtext provider
        from .settings_dlg import Settings
        csvUrl = QUrl.fromLocalFile(self._fn)
        csvUrl.setQueryItems([("delimiter", Settings.delimiter()),
                              ("delimiterType", "plain"),
                              ("xField", Settings.longitudeField()),
                              ("yField", Settings.latitudeField())])

        # load the layer
        from qgis.core import QgsVectorLayer
        csvVl = QgsVectorLayer(csvUrl.toString(), base_name, "delimitedtext")
        if not csvVl.isValid():  # invalid layer
            csvVl.deleteLater()
            QMessageBox.warning(self.parent(), "Invalid layer",
                                u"Unable to load the layer %s" % self._fn)
            return (self.INVALID_INPUT, None)

        # check the layer geometry type
        from qgis.core import QGis
        if csvVl.geometryType() != QGis.Point:
            csvVl.deleteLater()
            QMessageBox.warning(
                self.parent(), "Invalid layer",
                u"Unable to get data from the selected file. \nSetup Lat/Long field names and delimiter from the Settings dialog, \nthen try again."
            )
            return (self.INVALID_LATLON, None)

        # check whether the CSV file has to be imported to SL db
        if not Settings.importCsvToSl():
            return (self.OK, csvVl)

        # uri pointing to the new SL database
        from qgis.core import QgsDataSourceURI
        sqlite_path = dir_path.absoluteFilePath(u"%s.sqlite" % base_name)
        slUri = QgsDataSourceURI()
        slUri.setDatabase(sqlite_path)
        slUri.setDataSource("", base_name, "GEOMETRY")

        importer = Ogr2ogrImporter(csvVl, slUri, self.parent())
        #importer = QGisLayerImporter(csvVl, slUri, self.parent())
        ret = importer.start()

        # get the importer exit code
        if not ret:
            if importer.wasCanceled():
                ret = self.CANCELED
            else:
                ret = self.ERROR
                QMessageBox.warning(self.parent(), "Error",
                                    importer.errorMessage())
        else:
            ret = self.OK

        # cleanup
        importer.deleteLater()
        importer = None

        csvVl.deleteLater()
        csvVl = None

        if ret != self.OK:
            return (ret, None)

        # load the layer from the SL database
        slVl = QgsVectorLayer(slUri.uri(), slUri.table(), "spatialite")
        if not slVl.isValid():  # invalid layer
            slVl.deleteLater()
            QMessageBox.warning(
                self.parent(), "Invalid layer",
                u"Unable to load the layer %s" % slUri.database())
            return (self.ERROR, None)

        # check the layer geometry type
        if slVl.geometryType() != QGis.Point:
            slVl.deleteLater()
            return (self.ERROR, None)

        return (self.OK, slVl)