Esempio n. 1
0
 def layers_create(self, missing=None):
     """Utworzenie warstw w projekcie. Podanie atrybutu 'missing' spowoduje, że tylko wybrane warstwy będą dodane."""
     # Ustalenie ilości dodawanych warstw:
     i_max = len(missing) if missing else self.lyr_cnt
     # Utworzenie listy ze słownikami warstw do dodania:
     lyrs = []
     if missing:
         for l_dict in self.lyrs:
             if l_dict["name"] in missing:
                 lyrs.append(l_dict)
     else:
         lyrs = self.lyrs
     i = 0
     # Dodanie warstw:
     for l_dict in lyrs:
         i += 1
         raw_uri = l_dict["uri"]
         uri = eval("f'{}'".format(raw_uri))
         if l_dict["source"] == "wms" or l_dict["source"] == "gdal":
             lyr = QgsRasterLayer(uri, l_dict["name"], l_dict["source"])
             lyr_required = False
         else:
             lyr = QgsVectorLayer(uri, l_dict["name"], l_dict["source"])
             lyr_required = True
         if not lyr.isValid() and not lyr_required:
             m_text = f'Nie udało się poprawnie wczytać podkładu mapowego: {l_dict["name"]}. Naciśnięcie Tak spowoduje kontynuowanie uruchamiania wtyczki (podkład mapowy nie będzie wyświetlany), naciśnięcie Nie przerwie proces uruchamiania wtyczki. Jeśli problem będzie się powtarzał, zaleca się powiadomienie administratora systemu.'
             reply = QMessageBox.question(dlg.app, "WellMatch", m_text,
                                          QMessageBox.Yes, QMessageBox.No)
             if reply == QMessageBox.No:
                 return False
         elif not lyr.isValid() and lyr_required:
             m_text = f'Nie udało się poprawnie wczytać warstwy: {l_dict["name"]}. Jeśli problem będzie się powtarzał, proszę o powiadomienie administratora systemu ([email protected]).'
             QMessageBox.critical(dlg.app, "WellMatch", m_text)
             return False
         if l_dict["source"] == "memory":
             lyr.setCustomProperty("skipMemoryLayersCheck", 1)
             pr = lyr.dataProvider()
             pr.addAttributes(l_dict["attrib"])
             lyr.updateFields()
         if "crs" in l_dict:
             lyr.setCrs(CRS_1992)
         dlg.proj.addMapLayer(lyr, False)
         if l_dict["root"]:
             parent_grp = self.root
             parent_grp.insertChildNode(l_dict["pos"],
                                        QgsLayerTreeLayer(lyr))
             parent_grp.findLayer(lyr).setItemVisibilityChecked(
                 l_dict["visible"])
         else:
             if "pos" in l_dict:
                 parent_grp = self.root.findGroup(l_dict["parent"])
                 parent_grp.insertChildNode(l_dict["pos"],
                                            QgsLayerTreeLayer(lyr))
                 parent_grp.findLayer(lyr).setItemVisibilityChecked(False)
             else:
                 parent_grp = self.root.findGroup(l_dict["parent"])
                 node = parent_grp.addLayer(lyr)
                 node.setItemVisibilityChecked(l_dict["visible"])
         lyr.loadNamedStyle(f'{STYLE_PATH}{l_dict["style"]}')
     return True
 def createXYZLayer(self, layerType, name):
     # create XYZ layer with tms url as uri
     provider = 'wms'
     url = "type=xyz&url=" + layerType.xyzUrlConfig()
     layer = QgsRasterLayer(url, name, provider,
                            QgsRasterLayer.LayerOptions())
     layer.setCustomProperty('ol_layer_type', layerType.layerTypeName)
     return layer, layerType.xyzUrlConfig()
 def createXYZLayer(self, layerType, name):
     # create XYZ layer with tms url as uri
     provider = 'wms'
     url = "type=xyz&url=" + layerType.xyzUrlConfig()
     layer = QgsRasterLayer(url, name, provider,
                            QgsRasterLayer.LayerOptions())
     layer.setCustomProperty('ol_layer_type', layerType.layerTypeName)
     return layer, layerType.xyzUrlConfig()
class EsriRasterLayer(object):
    qgsRasterLayer = None
    connection = None
    imageSpec = None
    isUpdating = False

    @staticmethod
    def create(connection, imageSpec, srcPath):
        esriLayer = EsriRasterLayer()
        esriLayer.connection = connection
        esriLayer.imageSpec = imageSpec
        esriLayer.updateQgsRasterLayer(srcPath)
        return esriLayer

    @staticmethod
    def restoreFromQgsLayer(qgsLayer):
        esriLayer = EsriRasterLayer()
        esriLayer.qgsRasterLayer = qgsLayer
        basicUrl = str(qgsLayer.customProperty("arcgiscon_connection_url"))
        name = qgsLayer.name()
        username = str(
            qgsLayer.customProperty("arcgiscon_connection_username"))
        password = str(
            qgsLayer.customProperty("arcgiscon_connection_password"))
        authMethod = int(
            qgsLayer.customProperty("arcgiscon_connection_authmethod"))
        esriLayer.connection = Connection(basicUrl, name, username, password,
                                          authMethod)
        extent = str(qgsLayer.customProperty("arcgiscon_connection_extent"))
        if extent != "":
            esriLayer.connection.updateBoundingBoxByExtent(json.loads(extent))
        return esriLayer

    def updateQgsRasterLayer(self, srcPath):
        if self.imageSpec.name != self.connection.name:
            self.qgsRasterLayer = QgsRasterLayer(
                srcPath, self.connection.name + " " + self.imageSpec.name)
        else:
            self.qgsRasterLayer = QgsRasterLayer(srcPath, self.imageSpec.name)
        self.updateProperties()

    def updateProperties(self):
        self.qgsRasterLayer.setCustomProperty("arcgiscon_connection_url",
                                              self.connection.basicUrl)
        self.qgsRasterLayer.setCustomProperty(
            "arcgiscon_connection_authmethod", self.connection.authMethod)
        self.qgsRasterLayer.setCustomProperty("arcgiscon_connection_username",
                                              self.connection.username)
        self.qgsRasterLayer.setCustomProperty("arcgiscon_connection_password",
                                              self.connection.password)

        #extent = json.dumps(self.connection.bbBox) if self.connection.bbBox is not None else ""
        #extent = self.connection.bbBox if self.connection.bbBox is not None else ""
        #self.qgsRasterLayer.setCustomProperty("arcgiscon_connection_extent", extent)

        self.qgsRasterLayer.setDataUrl(self.connection.basicUrl)
Esempio n. 5
0
        def finished(exception, result=None):
            self.msgBar.clearWidgets()
            if not exception is None:
                msg = f"Error: Exception: {exception}"
                self.msgBar.pushMessage( self.MODULE, msg, Qgis.Critical, 4 )
                return
            layer = QgsRasterLayer( *result )
            if not layer.isValid():
                source = urllib.parse.unquote( layer.source() ).split('&')
                url = [ v for v in source if v.split('=')[0] == 'url' ][0]
                msg = f"!!!Error server: Get {url}"
                self.msgBar.pushCritical( self.MODULE, msg )
                return

            project = QgsProject.instance()
            totalEW = int( layer.customProperty('embeddedWidgets/count', 0) )
            layer.setCustomProperty('embeddedWidgets/count', totalEW + 1 )
            layer.setCustomProperty(f"embeddedWidgets/{totalEW}/id", self.widgetProvider.id() )
            project.addMapLayer( layer )
            root = project.layerTreeRoot()
            ltl = root.findLayer( layer )
            ltl.setExpanded(True)
    def load_pdok(self):
        """load most recent aerial photos of PDOK (Netherlands only) and style with transparency slider"""
        pdok_layer = QgsRasterLayer(
            "tileMatrixSet=EPSG:28992&crs=EPSG:28992&layers=Actueel_ortho25&styles=&format=image/png&url=https://geodata.nationaalgeoregister.nl/luchtfoto/rgb/wmts",
            "PDOK Luchtfoto actueel",
            "wms",
        )

        root = QgsProject.instance().layerTreeRoot()
        if not root.findGroup("background"):
            grp_background = root.insertGroup(-1, "background")
        else:
            grp_background = root.findGroup("background")

        QgsProject.instance().addMapLayer(pdok_layer, False)
        grp_background.insertChildNode(
            len(grp_background.children()), QgsLayerTreeLayer(pdok_layer)
        )
        pdok_layer.renderer().setOpacity(0.5)
        pdok_layer.setCustomProperty("embeddedWidgets/count", 1)
        pdok_layer.setCustomProperty("embeddedWidgets/0/id", "transparency")
        self.iface.layerTreeView().refreshLayerSymbology(pdok_layer.id())
    def load_dem(self, event):
        """lookup DEM raster reference of scenario, load raster and give styling"""
        global_settings_layer = QgsProject.instance().mapLayersByName(
            "v2_global_settings"
        )[0]
        source = Path(
            global_settings_layer.dataProvider()
            .dataSourceUri()
            .split(" ")[0]
            .split("=")[1][1:-1]
        )
        model_directory = source.parents[0]

        root = QgsProject.instance().layerTreeRoot()
        if not root.findGroup("background"):
            grp_background = root.insertGroup(-1, "background")
        else:
            grp_background = root.findGroup("background")

        feature = list(global_settings_layer.getFeatures())[
            self.selected_scenario_index
        ]

        dem_file = model_directory / Path(feature["dem_file"])

        fileInfo = QFileInfo(str(dem_file))
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()

        dem_layer = QgsRasterLayer(str(dem_file), "Digital Elevation Model")
        QgsProject.instance().addMapLayer(dem_layer, False)
        grp_background.insertChildNode(0, QgsLayerTreeLayer(dem_layer))
        dem_layer.loadNamedStyle(
            os.path.join(os.path.dirname(__file__), "styles\DEM.qml")
        )
        dem_layer.renderer().setOpacity(0.5)
        dem_layer.setCustomProperty("embeddedWidgets/count", 1)
        dem_layer.setCustomProperty("embeddedWidgets/0/id", "transparency")
        self.iface.layerTreeView().refreshLayerSymbology(dem_layer.id())
Esempio n. 8
0
def add_mosaics_to_qgis_project(mosaics,
                                name,
                                proc="default",
                                ramp="",
                                zmin=0,
                                zmax=22,
                                add_xyz_server=False):
    mosaic_names = [(mosaic_title(mosaic), mosaic[NAME]) for mosaic in mosaics]
    tile_url = mosaics[0][LINKS][TILES]
    uri = f'type=xyz&url={tile_url}&zmin={zmin}&zmax={zmax}'
    layer = QgsRasterLayer(uri, name, 'wms')
    layer.setCustomProperty(PLANET_CURRENT_MOSAIC, mosaic_title(mosaics[0]))
    layer.setCustomProperty(PLANET_MOSAIC_PROC, proc)
    layer.setCustomProperty(PLANET_MOSAIC_RAMP, ramp)
    layer.setCustomProperty(PLANET_MOSAIC_DATATYPE, mosaics[0][DATATYPE])
    layer.setCustomProperty(PLANET_MOSAICS, json.dumps(mosaic_names))
    QgsProject.instance().addMapLayer(layer)
    layer.setCustomProperty("embeddedWidgets/count", 1)
    layer.setCustomProperty("embeddedWidgets/0/id", WIDGET_PROVIDER_NAME)
    view = iface.layerTreeView()
    view.layerTreeModel().refreshLayerLegend(view.currentNode())
    view.currentNode().setExpanded(True)
    if add_xyz_server:
        s = QSettings()
        s.setValue(f'qgis/connections-xyz/{name}/zmin', zmin)
        s.setValue(f'qgis/connections-xyz/{name}/zmax', zmax)
        s.setValue(f'qgis/connections-xyz/{name}/username', "")
        s.setValue(f'qgis/connections-xyz/{name}/password', "")
        s.setValue(f'qgis/connections-xyz/{name}/authcfg', "")
        procparam = quote(f'&proc={proc}') if proc != "rgb" else ""
        rampparam = quote(f'&color={ramp}') if ramp else ""
        full_uri = f"{tile_url}{procparam}{rampparam}"
        s.setValue(f'qgis/connections-xyz/{name}/url',
                   full_uri.replace(PlanetClient.getInstance().api_key(), ""))
Esempio n. 9
0
def create_preview_group(group_name: str,
                         images: List[dict],
                         footprints_filename=None,
                         catalog_layer_name=None,
                         tile_service: str = 'xyz',
                         search_query: str = None,
                         sort_order: Tuple[str, str] = None) -> None:

    if tile_service.lower() not in ['wmts', 'xyz']:
        log.debug(f'Incorrect tile service passed for preview group: '
                  f'{tile_service} (must be wmts or xyz)')
        return

    item_ids = [f"{img['properties'][ITEM_TYPE]}:{img[ID]}" for img in images]
    uri = tile_service_data_src_uri(item_ids, service=tile_service)

    if uri:
        log.debug(f'Tile datasource URI:\n{uri}')

        rlayer = QgsRasterLayer(uri, 'Image previews', 'wms')
        rlayer.setCustomProperty(PLANET_PREVIEW_ITEM_IDS, json.dumps(item_ids))

        if tile_service == 'xyz' and catalog_layer_name is not None:
            url = uri.split("url=")[-1]
            s = QSettings()
            s.setValue(f'qgis/connections-xyz/{catalog_layer_name}/username',
                       "")
            s.setValue(f'qgis/connections-xyz/{catalog_layer_name}/password',
                       "")
            s.setValue(f'qgis/connections-xyz/{catalog_layer_name}/authcfg',
                       "")
            s.setValue(f'qgis/connections-xyz/{catalog_layer_name}/url',
                       url.replace(PlanetClient.getInstance().api_key(), ""))
    else:
        log.debug('No tile URI for preview group')
        return

    vlayer = None
    if images:
        vlayer = create_preview_vector_layer(images[0])

        vlayer.startEditing()
        dp = vlayer.dataProvider()
        fields: List[QgsField] = vlayer.fields()

        for img in images:
            feat = QgsFeature()
            feat.setFields(fields)
            qgs_geom = qgsgeometry_from_geojson(img['geometry'])
            feat.setGeometry(qgs_geom)

            f_names = [f.name() for f in fields]

            if 'item_id' in f_names:
                feat['item_id'] = img[ID]

            if search_query and 'search_query' in f_names:
                feat['search_query'] = json.dumps(search_query)
            if (sort_order and 'sort_order' in f_names
                    and len(sort_order) > 1):
                feat['sort_order'] = ' '.join(sort_order)

            props: dict = img['properties']
            for k, v in props.items():
                if k in f_names:
                    feat[k] = v

            dp.addFeature(feat)

        vlayer.commitChanges()

        if footprints_filename:
            QgsVectorFileWriter.writeAsVectorFormat(vlayer,
                                                    footprints_filename,
                                                    "UTF-8")
            gpkglayer = QgsVectorLayer(footprints_filename, 'Footprints')
            gpkglayer.setRenderer(vlayer.renderer().clone())
            vlayer = gpkglayer
        QgsProject.instance().addMapLayer(vlayer, False)

    # noinspection PyArgumentList
    QgsProject.instance().addMapLayer(rlayer, False)

    # noinspection PyArgumentList
    root: QgsLayerTree = QgsProject.instance().layerTreeRoot()
    group = root.insertGroup(0, f'{group_name} {tile_service.upper()} preview')
    if vlayer:
        group.addLayer(vlayer)
    group.addLayer(rlayer)
    if vlayer:
        iface.setActiveLayer(vlayer)
Esempio n. 10
0
    def createXYZLayer(self, layerType, name):
        # create XYZ layer with tms url as uri
        provider = "wms"

        # isinstance(P, (list, tuple, np.ndarray))
        xyzUrls = layerType.xyzUrlConfig()
        layerName = name
        tilePixelRatio = layerType.tilePixelRatio

        coordRefSys = layerType.coordRefSys(self.canvasCrs())
        self.setMapCrs(coordRefSys)

        if isinstance(xyzUrls, (list)):
            # create group layer
            root = QgsProject.instance().layerTreeRoot()
            layer = root.addGroup(layerType.groupName)

            i = 0
            for xyzUrl in xyzUrls:
                tmsLayerName = layerName

                # https://github.com/qgis/QGIS/blob/master/src/providers/wms/qgsxyzconnectiondialog.cpp

                uri = "url=" + xyzUrl + "&zmax=18&zmin=0&type=xyz"
                if (tilePixelRatio > 0):
                    uri = uri + "&tilePixelRatio=" + str(tilePixelRatio)

                if i > 0:
                    tmsLayerName = layerName + " Label"

                tmsLayer = QgsRasterLayer(uri, tmsLayerName, provider,
                                          QgsRasterLayer.LayerOptions())
                tmsLayer.setCustomProperty("ol_layer_type", tmsLayerName)

                layer.insertChildNode(0, QgsLayerTreeLayer(tmsLayer))
                i = i + 1

                if tmsLayer.isValid():
                    QgsProject.instance().addMapLayer(tmsLayer, False)
                    self._ol_layers += [tmsLayer]

                    # last added layer is new reference
                    self.setReferenceLayer(tmsLayer)
                    # add to XYT Tiles
                    self.addToXYZTiles(tmsLayerName, xyzUrl, tilePixelRatio)
        else:
            uri = "url=" + xyzUrls + "&zmax=18&zmin=0&type=xyz"
            if (tilePixelRatio > 0):
                uri = uri + "&tilePixelRatio=" + str(tilePixelRatio)

            layer = QgsRasterLayer(uri, layerName, provider,
                                   QgsRasterLayer.LayerOptions())
            layer.setCustomProperty("ol_layer_type", layerName)

            if layer.isValid():
                QgsProject.instance().addMapLayer(layer)
                self._ol_layers += [layer]

                # last added layer is new reference
                self.setReferenceLayer(layer)
                # add to XYT Tiles
                self.addToXYZTiles(layerName, xyzUrls, tilePixelRatio)

        # reload connections to update Browser Panel content
        self.iface.reloadConnections()

        return layer, xyzUrls
Esempio n. 11
0
    def gee_layer_make_xml(self):
        eelayer = self.iface.activeLayer()
        dest_dir = QgsProject.instance().absolutePath() or os.getcwd()
        dest_name = eelayer.name().replace('/', '_') + '.xml'
        dest_file = os.path.join(dest_dir, dest_name)
        source_xml = eelayer.dataProvider().dataSourceUri()
        dest_xml, _ = QFileDialog.getSaveFileName(self.dlg,
                                                  'Select output file',
                                                  dest_file,
                                                  'XML files (*.xml)')
        if dest_xml:
            shutil.copyfile(source_xml, dest_xml)
            newname = os.path.splitext(os.path.basename(dest_xml))[0]
            newlayer = QgsRasterLayer(dest_xml, newname)

            if newlayer.isValid():
                imageid = eelayer.customProperty('ee-image-id')
                date = eelayer.customProperty('ee-image-date')
                qml = eelayer.customProperty('ee-image-qml')
                extent = eelayer.customProperty('ee-image-wkt')
                # load qml must be first since this clean all custom properties
                if qml is not None:
                    if isfile(qml + '_' +
                              QSettings().value('locale/userLocale') + '.qml'):
                        newlayer.loadNamedStyle(
                            qml + '_' +
                            QSettings().value('locale/userLocale') + '.qml')
                    else:
                        newlayer.loadNamedStyle(qml + '.qml')
                newlayer.setCustomProperty('ee-image', 'XML')
                newlayer.setCustomProperty('ee-image-id', imageid)
                newlayer.setCustomProperty('ee-image-date', date)
                newlayer.setCustomProperty(
                    'ee-image-bands', eelayer.customProperty('ee-image-bands'))
                newlayer.setCustomProperty(
                    'ee-image-scale', eelayer.customProperty('ee-image-scale'))
                newlayer.setCustomProperty(
                    'ee-image-b_min', eelayer.customProperty('ee-image-b_min'))
                newlayer.setCustomProperty(
                    'ee-image-b_max', eelayer.customProperty('ee-image-b_max'))
                newlayer.setCustomProperty(
                    'ee-image-palette',
                    eelayer.customProperty('ee-image-palette'))
                newlayer.setCustomProperty('ee-image-qml', qml)
                newlayer.setCustomProperty('ee-image-wkt', extent)
                if date is not None:
                    newlayer.setAbstract(
                        f"ee.Image('{imageid}') \n\nDate: {date}")
                else:
                    newlayer.setAbstract(f"ee.Image('{imageid}')")
                bb = QgsRectangle.fromWkt(extent)
                newlayer.setExtent(bb)
                QgsProject.instance().addMapLayer(newlayer)
                QgsProject.instance().layerTreeRoot().findLayer(
                    newlayer.id()).setItemVisibilityChecked(False)
Esempio n. 12
0
def add_ee_image_layer(imageid, name, date, bands, scale, b_min=None, b_max=None, palette=None, qml=None, extent=None,
                       shown=False, destination=None):
    nbands = len(bands)
    # if nbands > 3:
    #     rgb = ee.Image(imageid).select(bands[0:3])
    #     pan = ee.Image(imageid).select(bands[3])
    #     huesat = rgb.rgbToHsv().select('hue', 'saturation')
    #     image = ee.Image.cat(huesat, pan).hsvToRgb().select([0, 1, 2], bands[0:3])
    #     nbands = 3
    # else:
    image = ee.Image(imageid)
    if not any([b_min, b_max, palette, qml]):
        image_stats = image.select(bands[0:nbands]).reduceRegion(ee.Reducer.minMax(), None, scale, None, None, False, 1.0E13).getInfo()
        b_min = [image_stats[bands[n] + '_min'] for n in range(nbands)]
        b_max = [image_stats[bands[n] + '_max'] for n in range(nbands)]
        # b_min = [image_stats[bands[0] + '_min'], image_stats[bands[1] + '_min'], image_stats[bands[2] + '_min']]
        # b_max = [image_stats[bands[0] + '_max'], image_stats[bands[1] + '_max'], image_stats[bands[2] + '_max']]
    rgb = image.visualize(bands=bands[0:nbands], min=b_min, max=b_max, palette=palette)
    tms = get_ee_image_tms(rgb)
    if extent is None:
        image_geojson = get_ee_image_bb(rgb)
        extent = geojson_to_wkt(image_geojson)
    bb = QgsRectangle.fromWkt(extent)
    url = tms_to_gdalurl(tms)
    xml = get_gdal_xml(url, nbands=nbands+1)
    # vfn = write_vsimem_xml(xml) # changed to named temporary file
    tmp, fn = write_xmlfile(xml, name, dest=destination)
    layer = QgsRasterLayer(fn, name)
    if layer.isValid():
        if qml is not None:
            if isfile(qml + '_' + QSettings().value('locale/userLocale') + '.qml'):
                layer.loadNamedStyle(qml + '_' + QSettings().value('locale/userLocale') + '.qml')
            else:
                layer.loadNamedStyle(qml + '.qml')
        layer.setExtent(bb)
        if tmp:
            layer.setCustomProperty('ee-image', 'MEM')
        else:
            layer.setCustomProperty('ee-image', 'XML')
        layer.setCustomProperty('ee-image-id', imageid)
        layer.setCustomProperty('ee-image-date', date)
        layer.setCustomProperty('ee-image-bands', bands)
        layer.setCustomProperty('ee-image-scale', scale)
        layer.setCustomProperty('ee-image-b_min', b_min)
        layer.setCustomProperty('ee-image-b_max', b_max)
        layer.setCustomProperty('ee-image-palette', palette)
        layer.setCustomProperty('ee-image-qml', qml)
        layer.setCustomProperty('ee-image-wkt', extent)
        # else:
        #     layer.setAbstract(f"ee.Image('{imageid}')")
        # if len(bands) < 4:
        #     try:
        #         layer.setCustomProperty('ee-image-stats', image_stats)
        #     except NameError:
        #         pass
        if date is not None:
            layer.setAbstract(f"ee.Image('{imageid}') \n\nDate: {date}")
        else:
            layer.setAbstract(f"ee.Image('{imageid}')")
        QgsProject.instance().addMapLayer(layer)
        if not shown:
            QgsProject.instance().layerTreeRoot().findLayer(layer.id()).setItemVisibilityChecked(shown)
Esempio n. 13
0
    def addLayer(self, index, old=None, addToMap=True):
        item = index.data(role=Qt.UserRole)
        if not isinstance(item, LayerItem):
            return
        if not self.plugin.setLoading(True):
            return
        addedData = []
        if isinstance(item, VectorItem):
            connector = self.getConnector()
            self.plugin.msgBar = ProgressMessageBar(self.iface, self.tr("Downloading layer '%s'...")%item.name, connector=connector)
            self.plugin.msgBar.setValue(10)
            connector.downloadingProgress.connect(self.plugin.updateDownloadProgress)
            data = connector.diviGetLayerFeatures(item.id)
            layers = []
            if data:
                permissions = connector.getUserPermission(item.id, 'layer')
                self.plugin.msgBar.setBoundries(50, 50)
                #Disable rendering for changing symbology
                self.iface.mapCanvas().setRenderFlag(False)
                layers = self.plugin.addLayer(data['features'], item, permissions, addToMap=addToMap)
                for layer in layers:
                    #Set symbols based on layer geometry type
                    item.setQgisStyle(layer)
                    self.iface.layerTreeView().refreshLayerSymbology(layer.id())
                self.iface.mapCanvas().setRenderFlag(True)
                addedData.extend( layers )
                item.items.extend( addedData )
            self.plugin.msgBar.setValue(100)
            aborted = self.plugin.msgBar.aborted
            self.plugin.msgBar.close()
            self.plugin.msgBar = None
            if aborted:
                # fix_print_with_import
                print('Aborted')
            elif not layers:
                #User can select geometry type in message bar
                widget = self.iface.messageBar().createMessage(
                    self.tr("Warning"),
                    self.tr(u"Layer '%s' is empty. To open it in QGIS you need to select geometry type.") % item.name
                )
                button = QToolButton(widget)
                button.setText(self.tr("Add layer as..."))
                button.setPopupMode(QToolButton.InstantPopup)
                menu = QMenu(button)
                def load_layer_as(geom_type):
                    self.plugin.loadLayerType(item = item, geom_type = geom_type)
                    self.iface.messageBar().clearWidgets()
                menu.addAction(QgsApplication.getThemeIcon('/mIconPointLayer.svg'), self.tr('Points'), lambda: load_layer_as(geom_type='MultiPoint'))
                menu.addAction(QgsApplication.getThemeIcon('/mIconLineLayer.svg'), self.tr('Linestring'), lambda: load_layer_as(geom_type='MultiLineString'))
                menu.addAction(QgsApplication.getThemeIcon('/mIconPolygonLayer.svg'), self.tr('Polygons'), lambda: load_layer_as(geom_type='MultiPolygon'))
                button.setMenu( menu )
                widget.layout().addWidget(button)
                self.iface.messageBar().pushWidget(widget, Qgis.Warning)

        elif isinstance(item, TableItem):
            if Qgis.QGIS_VERSION_INT < 21400:
                self.iface.messageBar().pushMessage('DIVI',
                    self.tr(u'QGIS 2.14 or later is required for loading DIVI tables.'),
                    Qgis.Critical,
                    duration = 3
                )
            else:
                self.plugin.msgBar = ProgressMessageBar(self.iface, self.tr("Downloading table '%s'...")%item.name)
                self.plugin.msgBar.setValue(10)
                connector = self.getConnector()
                connector.downloadingProgress.connect(self.plugin.updateDownloadProgress)
                data = connector.diviGetTableRecords(item.id)
                if data:
                    permissions = connector.getUserPermission(item.id, 'table')
                    self.plugin.msgBar.setBoundries(50, 50)
                    addedData.append( self.plugin.addTable(data['header'], data['data'], item, permissions, addToMap=addToMap) )
                    item.items.extend( addedData )
                self.plugin.msgBar.setValue(100)
                self.plugin.msgBar.close()
                self.plugin.msgBar = None
        elif isinstance(item, RasterItem):
            if Qgis.QGIS_VERSION_INT < 21800:
                self.iface.messageBar().pushMessage('DIVI',
                    self.tr(u'QGIS 2.18 or later is required for loading DIVI rasters.'),
                    Qgis.Critical,
                    duration = 3
                )
            else:
                uri = item.getUri(self.token)
                uri = uri.replace("b'", "").replace("'", "")
                QgsMessageLog.logMessage( uri, 'DIVI')
                r = QgsRasterLayer(uri, item.name, 'wms')
                r.setCustomProperty('DiviId', item.id)
                if item.extent is not None:
                    #Set extent for raster layer
                    bbox = self.transform2mercator.transformBoundingBox( QgsRectangle(
                            item.extent['st_xmin'],
                            item.extent['st_ymin'],
                            item.extent['st_xmax'],
                            item.extent['st_ymax']
                        ))
                    r.setExtent( bbox )
                addedData.append( r )
                item.items.extend( addedData )
                if addToMap:
                    QgsProject.instance().addMapLayer(r)
        elif isinstance(item, WmsItem):
            uri = item.getUri()
            QgsMessageLog.logMessage( uri, 'DIVI')
            r = QgsRasterLayer(uri, item.name, 'wms')
            r.setCustomProperty('DiviId', item.id)
            addedData.append( r )
            item.items.extend( addedData )
            if addToMap:
                QgsProject.instance().addMapLayer(r)
        elif isinstance(item, BasemapItem):
            uri = item.getUri()
            QgsMessageLog.logMessage( uri, 'DIVI')
            r = QgsRasterLayer(uri, item.name, 'wms')
            r.setCustomProperty('DiviId', item.id)
            addedData.append( r )
            item.items.extend( addedData )
            if addToMap:
                QgsProject.instance().addMapLayer(r)
        else:
            return
        index.model().dataChanged.emit(index.parent().parent(), index)
        self.plugin.setLoading(False)
        return addedData