Ejemplo n.º 1
0
 def _gpkgPath(self):
     subfolder = "PRdiff-" + str(uuid.uuid4()).replace("-", "")
     path = os.path.join(os.path.dirname(QgsApplication.qgisUserDatabaseFilePath()),
                         "geogig", self.user, self.repo, "DIFF", subfolder)
     if not os.path.exists(path):
         os.makedirs(path)
     return os.path.join(path, "PR_DIFF_" + str(self.prid) + ".gpkg")
Ejemplo n.º 2
0
    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface

        # initialize plugin directory
        self.plugin_dir = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()
                                    ).path() + "/python/plugins/" + __package__

        # initialize locale. Default to Danish
        self.config = QSettings()
        localePath = ""
        try:
            locale = self.config.value("locale/userLocale")[0:2]
        except:
            locale = 'da'

        if QFileInfo(self.plugin_dir).exists():
            localePath = self.plugin_dir + "/i18n/" + locale + ".qt.qm"

        if QFileInfo(localePath).exists():
            self.translator = QTranslator()
            self.translator.load(localePath)

            if qVersion() > '4.3.3':
                QgsApplication.installTranslator(self.translator)

        # new config method
        self.settings = Settings()
        self.options_factory = OptionsFactory(self.settings)
        self.options_factory.setTitle('Geosearch DK')
        iface.registerOptionsWidgetFactory(self.options_factory)
Ejemplo n.º 3
0
def _quad_orders_file():
    folder = os.path.join(
        os.path.dirname(QgsApplication.qgisUserDatabaseFilePath()),
        "planetexplorer")
    os.makedirs(folder, exist_ok=True)
    file = os.path.join(folder, "quadorders.json")
    return file
    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface

        # docked or dialog, defaults to dialog
        # 2018 may: RD: deprecating Docked window, as the content is getting to big anyway
        # if isinstance(QSettings().value("/pdokservicesplugin/docked"), QVariant):
        #     self.docked = QSettings().value("/pdokservicesplugin/docked", QVariant(False))
        # else:
        #     self.docked = QSettings().value("/pdokservicesplugin/docked", False)
        #
        # # Create the dialog and keep reference
        # if "True" == self.docked or "true" == self.docked or True is self.docked:
        #     self.dlg = PdokServicesPluginDockWidget()
        #     self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dlg)
        # else:
        #     self.dlg = PdokServicesPluginDialog(parent=self.iface.mainWindow())

        self.dlg = PdokServicesPluginDialog(parent=self.iface.mainWindow())
        # initialize plugin directory
        self.plugin_dir = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/python/plugins/pdokservicesplugin"
        self.currentLayer = None
        self.SETTINGS_SECTION = '/pdokservicesplugin/'
        self.pointer = None
        self.pdokgeocoder = PDOKGeoLocator(self.iface)
        self.geocoderSourceModel = None
Ejemplo n.º 5
0
    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface

        # initialize plugin directory
        self.plugin_dir = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/python/plugins/" + __package__

        # initialize locale. Default to Danish
        self.config = QSettings()
        localePath = ""
        try:
            locale = self.config.value("locale/userLocale")[0:2]
        except:
            locale = 'da'

        if QFileInfo(self.plugin_dir).exists():
            localePath = self.plugin_dir + "/i18n/" + locale + ".qt.qm"

        if QFileInfo(localePath).exists():
            self.translator = QTranslator()
            self.translator.load(localePath)

            if qVersion() > '4.3.3':
                QgsApplication.installTranslator(self.translator)
        
        # new config method
        self.settings = Settings()
        self.options_factory = OptionsFactory(self.settings)
        self.options_factory.setTitle('Geosearch DK')
        iface.registerOptionsWidgetFactory(self.options_factory)
Ejemplo n.º 6
0
Archivo: plugin.py Proyecto: stdm2/stdm
    def __init__(self, iface):
        """Constructor

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface

        """
        # Save reference to the QGIS interface
        self.iface = iface
        # noinspection PyArgumentList
        self.user_plugin_dir = (
            QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path()
            + "/python/plugins"
        )
        self.plugin_builder_path = os.path.dirname(__file__)

        # class members
        self.action = None
        self.dialog = None
        self.plugin_path = None
        self.template = None
        self.shared_dir = None
        self.template_dir = None
Ejemplo n.º 7
0
def getTranslate(namePlugin, nameDir=None):
    if nameDir is None:
      nameDir = namePlugin

    pluginPath = os.path.join('python', 'plugins', nameDir)

    userPath = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path()
    userPluginPath = os.path.join(userPath, pluginPath)
    
    systemPath = QgsApplication.prefixPath()
    systemPluginPath = os.path.join(systemPath, pluginPath)

    overrideLocale = QSettings().value('locale/overrideFlag', False, type=bool)
    localeFullName = QLocale.system().name() if not overrideLocale else QSettings().value('locale/userLocale', '')

    qmPathFile = os.path.join('i18n', '{0}_{1}.qm'.format(namePlugin, localeFullName))
    pp = userPluginPath if QFileInfo(userPluginPath).exists() else systemPluginPath
    translationFile = os.path.join(pp, qmPathFile)

    if QFileInfo(translationFile).exists():
        translator = QTranslator()
        translator.load(translationFile)
        QCoreApplication.installTranslator(translator)
        QgsApplication.messageLog().logMessage(('Installed translation file {}'.format(translationFile)), 'Midvatten',
                                               level=Qgis.Info)
        return translator
    else:
        QgsApplication.messageLog().logMessage(
            ("translationFile {} didn't exist, no translation file installed!".format(translationFile)), 'Midvatten',
                                               level=Qgis.Info)
Ejemplo n.º 8
0
    def installTranslator(self):  # TODO check this installation
        userPluginPath = os.path.join(
            os.path.dirname(str(QgsApplication.qgisUserDatabaseFilePath())),
            "python/plugins/loadthemall")
        systemPluginPath = os.path.join(str(QgsApplication.prefixPath()),
                                        "python/plugins/loadthemall")
        translationPath = ''

        try:
            # Errors here could happen if the value cannot be converted to string or
            # if it is not subscriptable (see https://github.com/gacarrillor/loadthemall/issues/11)
            locale = QSettings().value("locale/userLocale", type=str)
            myLocale = str(locale[0:2])
        except TypeError as e:
            myLocale = 'en'

        if os.path.exists(userPluginPath):
            translationPath = os.path.join(userPluginPath,
                                           "loadthemall_" + myLocale + ".qm")
        else:
            translationPath = os.path.join(systemPluginPath,
                                           "loadthemall_" + myLocale + ".qm")

        if QFileInfo(translationPath).exists():
            self.translator = QTranslator()
            self.translator.load(translationPath)
            QCoreApplication.installTranslator(self.translator)
Ejemplo n.º 9
0
    def _populate_bookmarks_list(self):
        """Read the sqlite database and populate the bookmarks list.

        If no bookmarks are found, the bookmarks radio button will be disabled
        and the label will be shown indicating that the user should add
        bookmarks in QGIS first.

        Every bookmark are reprojected to mapcanvas crs.
        """
        # Connect to the QGIS sqlite database and check if the table exists.
        # noinspection PyArgumentList
        db_file_path = QgsApplication.qgisUserDatabaseFilePath()
        db = sqlite3.connect(db_file_path)
        cursor = db.cursor()
        cursor.execute(
            'SELECT COUNT(*) '
            'FROM sqlite_master '
            'WHERE type=\'table\' '
            'AND name=\'tbl_bookmarks\';')

        number_of_rows = cursor.fetchone()[0]
        if number_of_rows > 0:
            cursor.execute(
                'SELECT * '
                'FROM tbl_bookmarks;')
            bookmarks = cursor.fetchall()

            canvas_crs = self.canvas.mapSettings().destinationCrs()

            for bookmark in bookmarks:
                name = bookmark[1]
                srid = bookmark[7]
                rectangle = QgsRectangle(
                    bookmark[3], bookmark[4], bookmark[5], bookmark[6])

                if srid != canvas_crs.srsid():
                    transform = QgsCoordinateTransform(
                        QgsCoordinateReferenceSystem(srid),
                        canvas_crs,
                        QgsProject.instance()
                    )
                    try:
                        rectangle = transform.transform(rectangle)
                    except QgsCsException:
                        rectangle = QgsRectangle()

                if rectangle.isEmpty():
                    pass

                self.bookmarks_list.addItem(name, rectangle)
        if self.bookmarks_list.currentIndex() >= 0:
            self.create_bookmarks_label.hide()
        else:
            self.create_bookmarks_label.show()
            self.hazard_exposure_bookmark.setDisabled(True)
            self.bookmarks_list.hide()
Ejemplo n.º 10
0
    def _populate_bookmarks_list(self):
        """Read the sqlite database and populate the bookmarks list.

        If no bookmarks are found, the bookmarks radio button will be disabled
        and the label will be shown indicating that the user should add
        bookmarks in QGIS first.

        Every bookmark are reprojected to mapcanvas crs.
        """
        # Connect to the QGIS sqlite database and check if the table exists.
        # noinspection PyArgumentList
        db_file_path = QgsApplication.qgisUserDatabaseFilePath()
        db = sqlite3.connect(db_file_path)
        cursor = db.cursor()
        cursor.execute(
            'SELECT COUNT(*) '
            'FROM sqlite_master '
            'WHERE type=\'table\' '
            'AND name=\'tbl_bookmarks\';')

        number_of_rows = cursor.fetchone()[0]
        if number_of_rows > 0:
            cursor.execute(
                'SELECT * '
                'FROM tbl_bookmarks;')
            bookmarks = cursor.fetchall()

            canvas_crs = self.canvas.mapSettings().destinationCrs()

            for bookmark in bookmarks:
                name = bookmark[1]
                srid = bookmark[7]
                rectangle = QgsRectangle(
                    bookmark[3], bookmark[4], bookmark[5], bookmark[6])

                if srid != canvas_crs.srsid():
                    transform = QgsCoordinateTransform(
                        QgsCoordinateReferenceSystem(srid),
                        canvas_crs,
                        QgsProject.instance()
                    )
                    try:
                        rectangle = transform.transform(rectangle)
                    except QgsCsException:
                        rectangle = QgsRectangle()

                if rectangle.isEmpty():
                    pass

                self.bookmarks_list.addItem(name, rectangle)
        if self.bookmarks_list.currentIndex() >= 0:
            self.create_bookmarks_label.hide()
        else:
            self.create_bookmarks_label.show()
            self.hazard_exposure_bookmark.setDisabled(True)
            self.bookmarks_list.hide()
Ejemplo n.º 11
0
def getTranslate(namePlugin, nameDir=None):
    if nameDir is None:
      nameDir = namePlugin

    pluginPath = os.path.join('python', 'plugins', nameDir)

    userPath = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path()
    userPluginPath = os.path.join(userPath, pluginPath)
    
    systemPath = QgsApplication.prefixPath()
    systemPluginPath = os.path.join(systemPath, pluginPath)

    pp = userPluginPath if QFileInfo(userPluginPath).exists() else systemPluginPath

    overrideLocale = QSettings().value('locale/overrideFlag', False, type=bool)
    if overrideLocale:
        qmPathFilepattern = os.path.join('i18n', '{0}_{1}_*.qm'.format(namePlugin, QSettings().value('locale/userLocale', '')))

        qmfiles = glob.glob(os.path.join(pp, qmPathFilepattern))
        if qmfiles:
            translationFile = sorted(qmfiles)[0]
            QgsApplication.messageLog().logMessage(
                ("QGIS location overried is activated. Using the first found translationfile for pattern {}.".format(qmPathFilepattern)),
                'Midvatten',
                level=Qgis.Info)
        else:
            QgsApplication.messageLog().logMessage(
                ("QGIS location overried is activated. No translation file found using pattern {}, no translation file installed!".format(qmPathFilepattern)),
                'Midvatten',
                level=Qgis.Info)
            return
    else:
        localeFullName = QLocale.system().name()
        qmPathFile = os.path.join('i18n', '{0}_{1}.qm'.format(namePlugin, localeFullName))
        translationFile = os.path.join(pp, qmPathFile)

    if QFileInfo(translationFile).exists():
        translator = QTranslator()
        translator.load(translationFile)
        QCoreApplication.installTranslator(translator)
        QgsApplication.messageLog().logMessage(('Installed translation file {}'.format(translationFile)), 'Midvatten',
                                               level=Qgis.Info)
        return translator
    else:
        QgsApplication.messageLog().logMessage(
            ("translationFile {} didn't exist, no translation file installed!".format(translationFile)), 'Midvatten',
                                               level=Qgis.Info)
Ejemplo n.º 12
0
    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface

        # docked or dialog, defaults to dialog
        # 2018 may: RD: deprecating Docked window, as the content is getting to big anyway
        # if isinstance(QSettings().value("/pdokservicesplugin/docked"), QVariant):
        #     self.docked = QSettings().value("/pdokservicesplugin/docked", QVariant(False))
        # else:
        #     self.docked = QSettings().value("/pdokservicesplugin/docked", False)
        #
        # # Create the dialog and keep reference
        # if "True" == self.docked or "true" == self.docked or True is self.docked:
        #     self.dlg = PdokServicesPluginDockWidget()
        #     self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dlg)
        # else:
        #     self.dlg = PdokServicesPluginDialog(parent=self.iface.mainWindow())

        self.dlg = PdokServicesPluginDialog(parent=self.iface.mainWindow())
        # initialize plugin directory
        self.plugin_dir = QFileInfo(QgsApplication.qgisUserDatabaseFilePath(
        )).path() + "/python/plugins/pdokservicesplugin"
        # initialize locale
        localePath = ""
        if isinstance(QSettings().value("locale/userLocale"), QVariant):
            locale = QSettings().value("locale/userLocale").value()[0:2]
        else:
            locale = QSettings().value("locale/userLocale")[0:2]

        if QFileInfo(self.plugin_dir).exists():
            localePath = self.plugin_dir + "/i18n/pdokservicesplugin_" + locale + ".qm"

        if QFileInfo(localePath).exists():
            self.translator = QTranslator()
            self.translator.load(localePath)
            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)
        self.currentLayer = None
        self.SETTINGS_SECTION = '/pdokservicesplugin/'
        self.pointer = None
        self.pdokgeocoder = PDOKGeoLocator(self.iface)
        self.geocoderSourceModel = None
    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface

        # docked or dialog, defaults to dialog
        # 2018 may: RD: deprecating Docked window, as the content is getting to big anyway
        # if isinstance(QSettings().value("/pdokservicesplugin/docked"), QVariant):
        #     self.docked = QSettings().value("/pdokservicesplugin/docked", QVariant(False))
        # else:
        #     self.docked = QSettings().value("/pdokservicesplugin/docked", False)
        #
        # # Create the dialog and keep reference
        # if "True" == self.docked or "true" == self.docked or True is self.docked:
        #     self.dlg = PdokServicesPluginDockWidget()
        #     self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dlg)
        # else:
        #     self.dlg = PdokServicesPluginDialog(parent=self.iface.mainWindow())

        self.dlg = PdokServicesPluginDialog(parent=self.iface.mainWindow())
        # initialize plugin directory
        self.plugin_dir = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/python/plugins/pdokservicesplugin"
        # initialize locale
        localePath = ""
        if isinstance(QSettings().value("locale/userLocale"), QVariant):
            locale = QSettings().value("locale/userLocale").value()[0:2]
        else:
            locale = QSettings().value("locale/userLocale")[0:2]

        if QFileInfo(self.plugin_dir).exists():
            localePath = self.plugin_dir + "/i18n/pdokservicesplugin_" + locale + ".qm"

        if QFileInfo(localePath).exists():
            self.translator = QTranslator()
            self.translator.load(localePath)
            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)
        self.currentLayer = None
        self.SETTINGS_SECTION = '/pdokservicesplugin/'
        self.pointer = None
        self.pdokgeocoder = PDOKGeoLocator(self.iface)
        self.geocoderSourceModel = None
Ejemplo n.º 14
0
def GDX_Publisher(self):

    #				print ("GDX_Publisher -------------------------------\n")

    tumpdir = unicode(
        QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path()
    ) + "/python/plugins/gearthview3/_WebServer"

    #				print (tumpdir)

    adesso = str(datetime.datetime.now())
    adesso = adesso.replace(" ", "_")
    adesso = adesso.replace(":", "_")
    adesso = adesso.replace(".", "_")

    #				print ("adesso: <%s>\n" %(adesso))

    # HERE IT DELETES THE OLD IMAGE ------------------------------------
    # (if you comment these, images still remain ...  :)
    for filename in glob.glob(str(tumpdir + '/*.png')):
        os.remove(str(filename))
    for filename in glob.glob(str(tumpdir + '/*.pngw')):
        os.remove(str(filename))
# ------------------------------------------------------------------

    mapCanvas = self.iface.mapCanvas()

    text = mapCanvas.extent().toString()
    text1 = text.replace(",", " ")
    text2 = text1.replace(" : ", ",")

    #				print ("extent: <%s>\n" %(text2))

    layer = mapCanvas.currentLayer()

    #				print ("Layer: <%s>\n" %(layer.name() ))

    extent = mapCanvas.extent()
    crsSrc = mapCanvas.mapSettings().destinationCrs()
    crsDest = QgsCoordinateReferenceSystem(4326)

    try:
        transform = QgsCoordinateTransform(crsSrc, crsDest,
                                           QgsProject.instance())
    except:
        transform = QgsCoordinateTransform(crsSrc, crsDest)

    projectedExtent = transform.transformBoundingBox(extent)

    x1 = projectedExtent.xMinimum()
    y1 = projectedExtent.yMinimum()

    x2 = projectedExtent.xMaximum()
    y2 = projectedExtent.yMinimum()

    x3 = projectedExtent.xMaximum()
    y3 = projectedExtent.yMaximum()

    x4 = projectedExtent.xMinimum()
    y4 = projectedExtent.yMaximum()

    xc = (x1 + x3) / 2.
    yc = (y1 + y3) / 2.

    out_folder = tumpdir

    # create output image and initialize it

    mapRect = mapCanvas.extent()
    width = mapCanvas.width()
    height = mapCanvas.height()
    srs = mapCanvas.mapSettings().destinationCrs()

    #				print (width, height)

    # MINORU
    #				canvas = mapCanvas
    ##				image = QImage(size.width(), size.height(), QImage.Format_ARGB32_Premultiplied)
    #				image = QImage(QSize(math.ceil(width), math.ceil(height)), QImage.Format_ARGB32)
    #				image.fill(Qt.transparent)
    ##				image.fill(QColor(0))
    #				painter = QPainter()
    #				painter.setRenderHint(QPainter.Antialiasing, True)
    #				painter.setRenderHint(QPainter.TextAntialiasing, True)
    #				painter.setRenderHint(QPainter.SmoothPixmapTransform, True)
    ##				painter.setRenderHint(QPainter.transparent, True)
    #
    ##				brush = QtGui.QBrush()
    ##				brush.setColor(QtGui.QColor(0))
    ##				painter.setBackground(self, 0)
    #
    #				painter.begin(image)
    #				canvas.render(painter)
    #				painter.end()
    # MINORU

    # MINORU2

    #				settings = self.exportSettings.mapSettings

    settings = QgsMapSettings()
    #				extent = settings.extent()
    extent = mapCanvas.extent()

    # store old map settings
    #				old_outputSize = settings.outputSize()
    #				old_extent = settings.extent()
    #				old_rotation = settings.rotation()
    #				old_layers = settings.layers()
    #				old_backgroundColor = settings.backgroundColor()

    # map settings
    settings.setOutputSize(QSize(width, height))
    #				settings.setExtent(extent.unrotatedRect())
    #				settings.setRotation(extent.rotation())

    #				if layerids:
    #				   settings.setLayers(tools.getLayersByLayerIds(layerids))

    #				if transp_background:
    settings.setBackgroundColor(QColor(Qt.transparent))

    has_pluginlayer = False
    for layer in settings.layers():
        if layer and layer.type() == QgsMapLayer.PluginLayer:
            has_pluginlayer = True
            break

    # create an image
    image = QImage(width, height, QImage.Format_ARGB32_Premultiplied)
    painter = QPainter()
    painter.begin(image)
    #				if antialias:
    #				   painter.setRenderHint(QPainter.Antialiasing)

    # rendering
    job = QgsMapRendererCustomPainterJob(settings, painter)
    if has_pluginlayer:
        job.renderSynchronously(
        )  # use this method so that TileLayerPlugin layer is rendered correctly
    else:
        job.start()
        job.waitForFinished()
    painter.end()

    # restore map settings
    #				settings.setOutputSize(old_outputSize)
    #				settings.setExtent(old_extent)
    #				settings.setRotation(old_rotation)
    #				settings.setLayers(old_layers)
    #				settings.setBackgroundColor(old_backgroundColor)

    # MINORU2

    kml = codecs.open(out_folder + '/doc.kml', 'w', encoding='utf-8')

    kml.write('<?xml version="1.0" encoding="UTF-8"?>\n')
    kml.write(
        '<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">\n'
    )
    kml.write('    <Document>\n')
    kml.write('    	 <name>QGisView</name>\n')
    kml.write('    	 <Snippet maxLines="0"></Snippet>\n')

    #				loc = ("    	 <description><![CDATA[https://map.what3words.com/%.7lf,%.7lf]]></description>\n") %(yc, xc)

    #				kml.write(loc)

    kml.write('	     <open>1</open>\n')

    kml.write('	<Style id="sh_style">\n')
    kml.write('		<PolyStyle>\n')
    kml.write('			<color>7fff8080</color>\n')
    kml.write('		</PolyStyle>\n')
    kml.write('	</Style>\n')
    kml.write('	<StyleMap id="msn_style">\n')
    kml.write('		<Pair>\n')
    kml.write('			<key>normal</key>\n')
    kml.write('			<styleUrl>#sn_style</styleUrl>\n')
    kml.write('		</Pair>\n')
    kml.write('		<Pair>\n')
    kml.write('			<key>highlight</key>\n')
    kml.write('			<styleUrl>#sh_style</styleUrl>\n')
    kml.write('		</Pair>\n')
    kml.write('	</StyleMap>\n')
    kml.write('	<Style id="sn_style">\n')
    kml.write('		<PolyStyle>\n')
    kml.write('			<color>00ff8080</color>\n')
    kml.write('			<fill>0</fill>\n')
    kml.write('		</PolyStyle>\n')
    kml.write('	</Style>\n')

    kml.write('	     <Style id="sh_ylw-pushpin">\n')
    kml.write('	     	<IconStyle>\n')
    kml.write('	     		<scale>1.2</scale>\n')
    kml.write('	     	</IconStyle>\n')
    kml.write('	     	<PolyStyle>\n')
    kml.write('	     		<fill>0</fill>\n')
    kml.write('	     	</PolyStyle>\n')
    kml.write('	     </Style>\n')
    kml.write('	     <Style id="sn_ylw-pushpin">\n')
    kml.write('	     	<PolyStyle>\n')
    kml.write('	     		<fill>0</fill>\n')
    kml.write('	     	</PolyStyle>\n')
    kml.write('	     </Style>\n')
    kml.write('	     <StyleMap id="msn_ylw-pushpin">\n')
    kml.write('	     	<Pair>\n')
    kml.write('	     		<key>normal</key>\n')
    kml.write('	     		<styleUrl>#sn_ylw-pushpin</styleUrl>\n')
    kml.write('	     	</Pair>\n')
    kml.write('	     	<Pair>\n')
    kml.write('	     		<key>highlight</key>\n')
    kml.write('	     		<styleUrl>#sh_ylw-pushpin</styleUrl>\n')
    kml.write('	     	</Pair>\n')
    kml.write('	     </StyleMap>\n')

    kml.write('    <StyleMap id="msn_style">\n')
    kml.write('        <Pair>\n')
    kml.write('            <key>normal</key>\n')
    kml.write('            <styleUrl>#sn_style</styleUrl>\n')
    kml.write('        </Pair>\n')
    kml.write('        <Pair>\n')
    kml.write('            <key>highlight</key>\n')
    kml.write('            <styleUrl>#sh_style</styleUrl>\n')
    kml.write('        </Pair>\n')
    kml.write('    </StyleMap>\n')

    kml.write('	     	<Style id="hl">\n')
    kml.write('	     		<IconStyle>\n')
    kml.write('	     			<scale>0.7</scale>\n')
    kml.write('	     			<Icon>\n')
    kml.write(
        '	     				<href>http://maps.google.com/mapfiles/kml/shapes/placemark_circle_highlight.png</href>\n'
    )
    kml.write('	     			</Icon>\n')
    kml.write('	     		</IconStyle>\n')
    kml.write('	     		<LabelStyle>\n')
    kml.write('	     			<scale>0.7</scale>\n')
    kml.write('	     		</LabelStyle>\n')
    kml.write('	     		<ListStyle>\n')
    kml.write('	     		</ListStyle>\n')
    kml.write('	     	</Style>\n')
    kml.write('	     	<Style id="default">\n')
    kml.write('	     		<IconStyle>\n')
    kml.write('	     			<scale>0.7</scale>\n')
    kml.write('	     			<Icon>\n')
    kml.write(
        '	     				<href>http://maps.google.com/mapfiles/kml/shapes/placemark_circle.png</href>\n'
    )
    kml.write('	     			</Icon>\n')
    kml.write('	     		</IconStyle>\n')
    kml.write('	     		<LabelStyle>\n')
    kml.write('	     			<scale>0.7</scale>\n')
    kml.write('	     		</LabelStyle>\n')
    kml.write('	     		<ListStyle>\n')
    kml.write('	     		</ListStyle>\n')
    kml.write('	     	</Style>\n')
    kml.write('	     	<StyleMap id="default0">\n')
    kml.write('	     		<Pair>\n')
    kml.write('	     			<key>normal</key>\n')
    kml.write('	     			<styleUrl>#default</styleUrl>\n')
    kml.write('	     		</Pair>\n')
    kml.write('	     		<Pair>\n')
    kml.write('	     			<key>highlight</key>\n')
    kml.write('	     			<styleUrl>#hl</styleUrl>\n')
    kml.write('	     		</Pair>\n')
    kml.write('	     	</StyleMap>\n')

    rotazio = 0.0

    rotazio = -(mapCanvas.rotation())

    kml.write('      <Folder>\n')

    xc = (x1 + x3) / 2.
    yc = (y1 + y3) / 2.
    dx = (x3 - x1) * 75000.  #100000.

    kml.write('    		<open>1</open>\n')
    kml.write('    		<NetworkLink>\n')
    kml.write('    		   <name>QGIS_link</name>\n')
    kml.write('    		   <visibility>1</visibility>\n')
    kml.write('    		   <open>1</open>\n')
    kml.write('    		   <Link>\n')
    kml.write('    		      <href>QGIS_link.kmz</href>\n')
    kml.write('    		   </Link>\n')
    kml.write('    		</NetworkLink>\n')

    kml.write('    		<LookAt>\n')
    stringazza = ("    		   <longitude>%lf</longitude>\n") % (xc)
    kml.write(stringazza)
    stringazza = ("    		   <latitude>%lf</latitude>\n") % (yc)
    kml.write(stringazza)
    kml.write('    		   <altitude>0</altitude>\n')

    stringazza = ("    		   <heading>%lf</heading>\n") % (rotazio)
    kml.write(stringazza)

    kml.write('    		   <tilt>0</tilt>\n')
    stringazza = ("    		   <range>%lf</range>\n") % (dx)
    kml.write(stringazza)
    kml.write('    		   <gx:altitudeMode>relativeToGround</gx:altitudeMode>\n')
    kml.write('    		</LookAt>\n')

    kml.write('      <GroundOverlay>\n')
    kml.write('    	 <name>QGisView</name>\n')

    kml.write('    	<Icon>\n')

    xN = projectedExtent.xMinimum()
    yN = projectedExtent.yMinimum()

    nomePNG = ("QGisView_%lf_%lf_%s") % (xN, yN, adesso)
    stringazza = ("    	<href>%s.png</href>\n") % (nomePNG)
    kml.write(stringazza)
    kml.write('    		<viewBoundScale>1.0</viewBoundScale>\n')
    kml.write('    	</Icon>\n')
    kml.write('    	<gx:LatLonQuad>\n')
    kml.write('    		<coordinates>\n')

    stringazza = ("%.7lf,%.7lf,0 %.7lf,%.7lf,0 %.7lf,%.7lf,0 %.7lf,%.7lf,0\n"
                  ) % (x1, y1, x2, y2, x3, y3, x4, y4)
    kml.write(stringazza)

    kml.write('    		</coordinates>\n')
    kml.write('    	</gx:LatLonQuad>\n')
    kml.write('    </GroundOverlay>\n')

    #Export tfw-file
    xScale = (projectedExtent.xMaximum() -
              projectedExtent.xMinimum()) / image.width()
    yScale = (projectedExtent.yMaximum() -
              projectedExtent.yMinimum()) / image.height()

    f = open(out_folder + "/" + nomePNG + ".pngw", 'w')
    f.write(str(xScale) + '\n')
    f.write(str(0) + '\n')
    f.write(str(0) + '\n')
    f.write('-' + str(yScale) + '\n')
    f.write(str(projectedExtent.xMinimum()) + '\n')
    f.write(str(projectedExtent.yMaximum()) + '\n')
    f.write(str(projectedExtent.xMaximum()) + '\n')
    f.write(str(projectedExtent.yMinimum()))
    f.close()

    input_file = out_folder + "/" + nomePNG + ".png"

    #Save the image
    image.save(input_file, "png")

    nomeLay = "gearthview"  # foo default name

    #  Adesso scrivo il vettoriale
    #  Prendo il sistema di riferimento del Layer selezionato ------------------

    curLayer = mapCanvas.currentLayer()

    iface = qgis.utils.iface

    selectedLayers = iface.layerTreeView().selectedLayers()

    if (not selectedLayers):
        #				   print ("selectedLayers is Empty")
        selectedLayers = []
        selectedLayers.append(curLayer)

    for layer in selectedLayers:

        if layer:

            if layer.type() == layer.VectorLayer:

                name = layer.source()
                nomeLayer = layer.name()
                nomeLay = nomeLayer.replace(" ", "_")

                #				    print(layer.name())

                kml.write('    <Folder>\n')
                stringazza = ('			<name>%s</name>\n') % (nomeLay)
                kml.write(stringazza)

                crsSrc = layer.crs()

                crsDest = QgsCoordinateReferenceSystem(4326)  # Wgs84LLH
                xform = QgsCoordinateTransform(crsSrc, crsDest,
                                               QgsProject.instance())

                #----------------------------------------------------------------------------
                #  Trasformo la finestra video in coordinate layer,
                #     per estrarre solo gli elementi visibili
                #----------------------------------------------------------------------------
                #				    mapCanvas = iface.mapCanvas()
                boundBox = mapCanvas.extent()

                xMin = float(boundBox.xMinimum())
                yMin = float(boundBox.yMinimum())

                xMax = float(boundBox.xMaximum())
                yMax = float(boundBox.yMaximum())

                crs2 = mapCanvas.mapSettings().destinationCrs()
                crsSrc2 = QgsCoordinateReferenceSystem(crs2.authid())
                crsDest2 = QgsCoordinateReferenceSystem(layer.crs())
                xform2 = QgsCoordinateTransform(crsSrc2, crsDest2,
                                                QgsProject.instance())

                pt0 = xform2.transform(QgsPointXY(xMin, yMin))
                pt1 = xform2.transform(QgsPointXY(xMax, yMax))

                rect = QgsRectangle(pt0, pt1)

                #				    print ("pt0x: <%s>" %(str(pt0.x())) )
                #				    print ("pt0y: <%s>" %(str(pt0.y())) )
                #				    print ("pt1x: <%s>" %(str(pt1.x())) )
                #				    print ("pt1y: <%s>" %(str(pt1.y())) )

                rq = QgsFeatureRequest(rect)

                iter = layer.getFeatures(rq)

                for feat in iter:

                    nele = feat.id()

                    # fetch geometry
                    geom = feat.geometry()
                    # show some information about the feature

                    #				      print (("GeomType: %d") %(geom.type()))

                    if geom.type() == 0:

                        elem = geom.asPoint()
                        x1 = elem.x()
                        y1 = elem.y()

                        #				        pt1 = xform.transform(QgsPoint(x1, y1))

                        kml.write('	<Placemark>\n')

                        stringazza = ('		<name>%s</name>\n') % (nele)
                        kml.write(stringazza)

                        kml.write('	<styleUrl>#default0</styleUrl>\n')

                        # DESCRIPTION DATA-----------
                        kml.write('	<Snippet maxLines="0"></Snippet>\n')
                        kml.write('	<description><![CDATA[\n')
                        kml.write('<html><body><table border="1">\n')
                        kml.write(
                            '<tr><th>Field Name</th><th>Field Value</th></tr>\n'
                        )

                        # Prendo il contenuto dei campi -------------
                        fff = feat.fields()
                        num = fff.count()
                        iii = -1
                        for f in layer.fields():
                            iii = iii + 1

                            stringazza = ('<tr><td>%s</td><td>%s</td></tr>\n'
                                          ) % (f.name(), feat[iii])

                            kml.write(stringazza)

                        kml.write('</table></body></html>\n')
                        kml.write(']]></description>\n')

                        # EXTENDED DATA -------------
                        stringazza = (
                            '		<ExtendedData><SchemaData schemaUrl="#%s">\n'
                        ) % (nomeLay)
                        kml.write(stringazza)

                        ## Prendo il contenuto dei campi -------------
                        fff = feat.fields()
                        num = fff.count()
                        iii = -1
                        for f in layer.fields():
                            iii = iii + 1

                            stringazza = (
                                '				<SimpleData name="%s">%s</SimpleData>\n'
                            ) % (f.name(), feat[iii])

                            if (stringazza.find('<SimpleData name="descrip') ==
                                    -1):
                                kml.write(stringazza)

                        kml.write('		</SchemaData></ExtendedData>\n')
                        # EXTENDED DATA -------------

                        wkt = layer.crs().toWkt()
                        source = osr.SpatialReference()
                        source.ImportFromWkt(wkt)

                        target = osr.SpatialReference()
                        target.ImportFromEPSG(4326)

                        transform = osr.CoordinateTransformation(
                            source, target)

                        testo = geom.asWkt()
                        #				        print (testo)

                        testo = testo.replace("PointZ (", "Point (")
                        testo = testo.replace("PointZM (", "Point (")
                        testo = testo.replace(" 0,", ",")
                        testo = testo.replace(" 0)", ")")

                        geometra = ogr.CreateGeometryFromWkt(testo)
                        geometra.Transform(transform)
                        testoKML = geometra.ExportToKML()
                        kml.write(testoKML)

                        kml.write('	</Placemark>\n')

                    elif geom.type() == 1:

                        elem = geom.asPolyline()

                        kml.write('	<Placemark>\n')

                        stringazza = ('		<name>%s</name>\n') % (nele)
                        kml.write(stringazza)

                        kml.write('	<styleUrl>#default0</styleUrl>\n')

                        # DESCRIPTION DATA-----------
                        kml.write('	<Snippet maxLines="0"></Snippet>\n')
                        kml.write('	<description><![CDATA[\n')
                        kml.write('<html><body><table border="1">\n')
                        kml.write(
                            '<tr><th>Field Name</th><th>Field Value</th></tr>\n'
                        )

                        # Prendo il contenuto dei campi -------------
                        fff = feat.fields()
                        num = fff.count()
                        iii = -1
                        for f in layer.fields():
                            iii = iii + 1

                            stringazza = ('<tr><td>%s</td><td>%s</td></tr>\n'
                                          ) % (f.name(), feat[iii])

                            kml.write(stringazza)

                        kml.write('</table></body></html>\n')
                        kml.write(']]></description>\n')

                        # EXTENDED DATA -------------
                        stringazza = (
                            '		<ExtendedData><SchemaData schemaUrl="#%s">\n'
                        ) % (nomeLay)
                        kml.write(stringazza)

                        ## Prendo il contenuto dei campi -------------
                        fff = feat.fields()
                        num = fff.count()
                        iii = -1
                        for f in layer.fields():
                            iii = iii + 1

                            stringazza = (
                                '				<SimpleData name="%s">%s</SimpleData>\n'
                            ) % (f.name(), feat[iii])

                            if (stringazza.find('<SimpleData name="descrip') ==
                                    -1):
                                kml.write(stringazza)

                        kml.write('		</SchemaData></ExtendedData>\n')
                        # EXTENDED DATA -------------

                        wkt = layer.crs().toWkt()
                        source = osr.SpatialReference()
                        source.ImportFromWkt(wkt)

                        target = osr.SpatialReference()
                        target.ImportFromEPSG(4326)

                        transform = osr.CoordinateTransformation(
                            source, target)

                        testo = geom.asWkt()
                        #				        print (testo)

                        testo = testo.replace("LineStringZ (", "LineString (")
                        testo = testo.replace("LineStringZM (", "LineString (")
                        testo = testo.replace(" 0,", ",")
                        testo = testo.replace(" 0)", ")")

                        geometra = ogr.CreateGeometryFromWkt(testo)
                        geometra.Transform(transform)
                        testoKML = geometra.ExportToKML()
                        kml.write(testoKML)

                        kml.write('	</Placemark>\n')

                    elif geom.type() == 2:

                        kml.write('	<Placemark>\n')

                        stringazza = ('		<name>%s</name>\n') % (nele)
                        kml.write(stringazza)
                        kml.write('		<styleUrl>#msn_style</styleUrl>\n')

                        # DESCRIPTION DATA-----------
                        kml.write('	<Snippet maxLines="0"></Snippet>\n')
                        kml.write('	<description><![CDATA[\n')
                        kml.write('<html><body><table border="1">\n')
                        kml.write(
                            '<tr><th>Field Name</th><th>Field Value</th></tr>\n'
                        )

                        # Prendo il contenuto dei campi -------------
                        fff = feat.fields()
                        num = fff.count()
                        iii = -1
                        for f in layer.fields():
                            iii = iii + 1

                            stringazza = ('<tr><td>%s</td><td>%s</td></tr>\n'
                                          ) % (f.name(), feat[iii])

                            kml.write(stringazza)

                        kml.write('</table></body></html>\n')
                        kml.write(']]></description>\n')

                        # EXTENDED DATA -------------
                        stringazza = (
                            '		<ExtendedData><SchemaData schemaUrl="#%s">\n'
                        ) % (nomeLay)
                        kml.write(stringazza)

                        ## Prendo il contenuto dei campi -------------
                        fff = feat.fields()
                        num = fff.count()
                        iii = -1
                        for f in layer.fields():
                            iii = iii + 1

                            stringazza = (
                                '				<SimpleData name="%s">%s</SimpleData>\n'
                            ) % (f.name(), feat[iii])

                            if (stringazza.find('<SimpleData name="descrip') ==
                                    -1):
                                kml.write(stringazza)

                        kml.write('		</SchemaData></ExtendedData>\n')
                        # EXTENDED DATA -------------

                        testo = geom.asWkt()
                        #				        print (testo)

                        wkt = layer.crs().toWkt()
                        source = osr.SpatialReference()
                        source.ImportFromWkt(wkt)

                        target = osr.SpatialReference()
                        target.ImportFromEPSG(4326)

                        transform = osr.CoordinateTransformation(
                            source, target)

                        testo = testo.replace("PolygonZ (", "Polygon (")
                        testo = testo.replace("PolygonZM (", "Polygon (")
                        testo = testo.replace(" 0,", ",")
                        testo = testo.replace(" 0)", ")")
                        geometra = ogr.CreateGeometryFromWkt(testo)
                        geometra.Transform(transform)
                        testoKML = geometra.ExportToKML()

                        testoKML = testoKML.replace(
                            "<Polygon>",
                            "<Polygon><altitudeMode>relativeToGround</altitudeMode>"
                        )

                        kml.write(testoKML)

                        kml.write('	</Placemark>\n')

                kml.write('  </Folder>\n')

    kml.write('</Folder>\n')

    kml.write('</Document>\n')
    kml.write('</kml>\n')
    kml.close()

    if platform.system() == "Windows":
        os.startfile(out_folder + '/doc.kml')

    if platform.system() == "Darwin":
        os.system("open " + str(out_folder + '/doc.kml'))

    if platform.system() == "Linux":
        os.system("xdg-open " + str(out_folder + '/doc.kml'))
Ejemplo n.º 15
0
def P3dPoints_Write(self, adesso):

    iface = qgis.utils.iface

    layer = iface.mapCanvas().currentLayer()

    if (layer == None):
        return (-1)

    crs = layer.crs()

    nomeLayer = str(layer.name())
    filePath = str(layer.source())
    direct = os.path.dirname(filePath)
    out_folder = direct + '/_3dPointsExport'

    if not os.path.exists(out_folder):
        os.mkdir(out_folder)

    nomeGML = ("/GEKml_3dPoints.csv")

    #  Apro il file WKT in scrittura

    kml = open(out_folder + nomeGML, 'w')

    kml.write("X,Y,Z,ID,Name,Istr\n")
    # kml.write ("X,Y,Z,ID\n")

    layer = self.iface.mapCanvas().currentLayer()

    if layer:
        if layer.type() == layer.VectorLayer:

            name = layer.source()
            nomeLayer = layer.name()
            nomeLay = nomeLayer.replace(" ", "_")

            #--------------------------------------------------------
            if (adesso == "GEKml_Polygons"):

                #				      print "CREO UN MEMORY LAYER DI POLIGONI"

                geomType = ("Polygon" + '?crs=%s') % (crs.authid())
                DronePlan = "GEKml_Extrusions"
                memLay_Tin = QgsVectorLayer(geomType, DronePlan, 'memory')
                memprovider_Tin = memLay_Tin.dataProvider()

                memLay_Tin.updateExtents()
                memLay_Tin.commitChanges()
                #				      QgsMapLayerRegistry.instance().addMapLayer(memLay_Tin)
                QgsProject.instance().addMapLayer(memLay_Tin)
                res = memprovider_Tin.addAttributes([
                    QgsField("ID", QVariant.Int),
                    QgsField("height", QVariant.Double),
                    QgsField("baseZ", QVariant.Double),
                    QgsField("Name", QVariant.String)
                ])

            idx = layer.fields().indexFromName('Name')

            height = 0
            baseZ = 0
            num = 0
            iter = layer.getFeatures()
            for feat in iter:

                num = num + 1
                # fetch geometry
                geom = feat.geometry()

                Name = feat.attributes()[idx]

                #				      print Name

                testoWKT = geom.asWkt() + "\n"

                #				      print testoWKT

                istr = testoWKT.split(' ')
                Z = str(istr[3])
                Z = Z.replace(',', '')
                istruz = str(num) + "," + Name + "," + str(istr[0])

                #				      print istruz

                if (str(istr[0]) == "PolygonZ" and adesso == "GEKml_Polygons"):

                    #				         print "---scrivo un elemento poligono"

                    feature = QgsFeature()

                    feature.setGeometry(geom)

                    feature.initAttributes(4)

                    ID = num

                    #  RoofType;	// 0 = flat, 1 = shed, 2 = gable, 3 = hip
                    # h ttp://wiki.openstreetmap.org/wiki/OSM-4D/Roof_table

                    #				         RoofType = Name

                    #				         if (height == 0 and Z > 0):
                    if (float(Z) > 0):
                        #				            print Z
                        height = float(Z)

                    values = [(ID), (height), (baseZ), (Name)]

                    feature.setAttributes(values)

                    memprovider_Tin.addFeatures([feature])

                testoWKT = testoWKT.replace("PointZ (", "")
                testoWKT = testoWKT.replace("LineStringZ (", "")
                testoWKT = testoWKT.replace("PolygonZ ((", "")

                testoWKT = testoWKT.replace("Polygon ((", "")

                testoWKT = testoWKT.replace(", ", ",istruzione\n")

                testoWKT = testoWKT.replace("))", ",istruzione")
                testoWKT = testoWKT.replace(")", ",istruzione")
                testoWKT = testoWKT.replace(" ", ",")

                testoWKT = testoWKT.replace("istruzione", istruz)

                kml.write(testoWKT)

                if (str(istr[0]) == "PointZ" and adesso == "GEKml_Polygons"):
                    splitta = testoWKT.split(',')
                    baseZ = splitta[2]

                if (str(istr[0]) == "LineStringZ"
                        and adesso == "GEKml_Polygons"):
                    splitta = testoWKT.split(',')
                    height = splitta[7]

    kml.close()

    if (adesso == "GEKml_Polygons"):
        memLay_Tin.updateFields()
        #				   tumpdir = unicode(QFileInfo(QgsApplication.qgisUserDbFilePath()).path()) + "/python/plugins/gearthview/_WebServer"
        tumpdir = unicode(
            QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path()
        ) + "/python/plugins/gearthview/_WebServer"
        nomeqml = tumpdir + "/GEKml_Extrusions.qml"
        nomeqml.replace("\\", "/")

        result = memLay_Tin.loadNamedStyle(nomeqml)

    return (0)
Ejemplo n.º 16
0
    def PasteFromGE(self):

        mapCanvas = self.iface.mapCanvas()

        copyText = QApplication.clipboard().text()

        #---------       Fix bug paste multiholes  -------------------------

        copyText = copyText.replace(
            "\t\t\t\t</LinearRing>\n\t\t\t\t<LinearRing>",
            "\t\t\t\t</LinearRing>\n\t\t\t</innerBoundaryIs>\n\t\t\t<innerBoundaryIs>\n\t\t\t\t<LinearRing>"
        )

        copyText = copyText.replace(
            "\t\t\t\t\t</LinearRing>\n\t\t\t\t\t<LinearRing>",
            "\t\t\t\t</LinearRing>\n\t\t\t</innerBoundaryIs>\n\t\t\t<innerBoundaryIs>\n\t\t\t\t<LinearRing>"
        )

        #---------       Fix bug paste multiholes  -------------------------

        #        print copyText

        tumpdir = unicode(
            QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path()
        ) + "/python/plugins/gearthview3/_WebServer"

        #<Point>         GEKml_Points.kml
        #<LineString>    GEKml_Lines.kml
        #<Polygon>       GEKml_Polygons.kml

        # Tolgo i livelli precedenti
        #        QgsMapLayerRegistry.instance().removeMapLayer("GEKml_Points")
        #        QgsMapLayerRegistry.instance().removeMapLayer("GEKml_Lines")
        #        QgsMapLayerRegistry.instance().removeMapLayer("GEKml_Polygons")

        for iLayer in range(mapCanvas.layerCount()):
            layer = mapCanvas.layer(iLayer)
            if (layer.name() == "GEKml_Points") or (
                    layer.name() == "GEKml_Lines") or (layer.name()
                                                       == "GEKml_Polygons"):
                QgsProject.instance().removeMapLayer(layer.id())

        GEKml_Points = copyText.find("<Point>")
        GEKml_Lines = copyText.find("<LineString>")
        GEKml_Polygons = copyText.find("<Polygon>")

        if (GEKml_Polygons > 0):

            salvalo2 = codecs.open(tumpdir + "/GEKml_Polygons.kml",
                                   'w',
                                   encoding='utf-8')
            salvalo2.write(copyText)

            salvalo2.close()

            vlayer = QgsVectorLayer(tumpdir + "/GEKml_Polygons.kml",
                                    "GEKml_Polygons", "ogr")
            QgsProject.instance().addMapLayer(vlayer)

        if (GEKml_Lines > 0):

            salvalo2 = codecs.open(tumpdir + "/GEKml_Lines.kml",
                                   'w',
                                   encoding='utf-8')
            salvalo2.write(copyText)

            salvalo2.close()

            vlayer = QgsVectorLayer(tumpdir + "/GEKml_Lines.kml",
                                    "GEKml_Lines", "ogr")
            QgsProject.instance().addMapLayer(vlayer)

        if (GEKml_Points > 0):

            salvalo2 = codecs.open(tumpdir + "/GEKml_Points.kml",
                                   'w',
                                   encoding='utf-8')
            salvalo2.write(copyText)

            salvalo2.close()

            vlayer = QgsVectorLayer(tumpdir + "/GEKml_Points.kml",
                                    "GEKml_Points", "ogr")
            QgsProject.instance().addMapLayer(vlayer)

            #  Dalla versione 2.14  QGIS permette di esportare anche la coordinata Z ---

            #        if QGIS_VERSION_INT >= 21400:

            giaFatto = 0
            if (GEKml_Polygons > 0):
                ret = P3dPoints_Write(self, "GEKml_Polygons")
                giaFatto = 1

            if (GEKml_Lines > 0 and giaFatto == 0):
                ret = P3dPoints_Write(self, "GEKml_Lines")
                giaFatto = 1

            if (GEKml_Points > 0 and giaFatto == 0):
                ret = P3dPoints_Write(self, "GEKml_Points")
                giaFatto = 1

            nomecsv = tumpdir + "/_3dPointsExport/GEKml_3dPoints.csv"
            nomecsv.replace("\\", "/")
            uri = """file:///""" + nomecsv + """?"""
            uri += """type=csv&"""
            uri += """trimFields=no&"""
            uri += """xField=X&"""
            uri += """yField=Y&"""
            uri += """spatialIndex=yes&"""
            uri += """subsetIndex=no&"""
            uri += """watchFile=no&"""
            uri += """crs=epsg:4326"""

            for iLayer in range(mapCanvas.layerCount()):
                layer = mapCanvas.layer(iLayer)
                if (layer):
                    if layer.name() == "GEKml_3dPoints":
                        QgsMapLayerRegistry.instance().removeMapLayer(
                            layer.id())
                    if layer.name() == "GEKml_Extrusions":
                        QgsMapLayerRegistry.instance().removeMapLayer(
                            layer.id())

            vlayer = QgsVectorLayer(uri, "GEKml_3dPoints", "delimitedtext")

            #           QgsMapLayerRegistry.instance().addMapLayer(vlayer)
            QgsProject.instance().addMapLayer(vlayer)

            nomeqml = tumpdir + "/_3dPointsExport/GEKml_3dPoints.qml"
            nomeqml.replace("\\", "/")

            result = vlayer.loadNamedStyle(nomeqml)

# FINE  QGis.QGIS_VERSION_INT >= 21400 ----------------------

#        vlayer.triggerRepaint()

        mapCanvas.refresh()
Ejemplo n.º 17
0
from .resources import *

# Import the code for the DockWidget
from .point_cloud_3d_dockwidget import PointCloud3DDockWidget
import os.path

import sys
# sys.path.append("C:\Program Files\JetBrains\PyCharm 2018.3.3\debug-eggs\pycharm-debug.egg") # dhl
# sys.path.append("C:\Program Files\JetBrains\PyCharm 2020.3\debug-eggs\pydevd-pycharm.egg") # dhl
# import pydevd

from PyQt5.QtWidgets import QMessageBox, QFileDialog, QTabWidget, QInputDialog, QLineEdit
from PyQt5.QtCore import QSettings, QTranslator, qVersion, QCoreApplication, QFileInfo, QDir, QObject, QFile
from qgis.core import QgsApplication, QgsDataSourceUri

pluginsPath = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path()
pluginPath = os.path.dirname(os.path.realpath(__file__))
pluginPath = os.path.join(pluginsPath, pluginPath)
libCppPath = os.path.join(pluginPath, 'libCpp')
existsPluginPath = QDir(libCppPath).exists()
sys.path.append(pluginPath)
sys.path.append(libCppPath)
os.environ["PATH"] += os.pathsep + libCppPath
from libCpp.libPyPointCloud3D import IPyPC3DProject
from . import PC3DDefinitions


class PointCloud3D:
    """QGIS Plugin Implementation."""
    def __init__(self, iface):
        """Constructor.