Ejemplo n.º 1
0
 def reprojectRubberBand(self, geom):
     """
     Reprojects the geometry
     geom: QgsGeometry
     """
     # Defining the crs from src and destiny
     epsg = self.canvas.mapSettings().destinationCrs().authid()
     crsSrc = QgsCoordinateReferenceSystem(epsg)
     #getting srid from something like 'EPSG:31983'
     layer = self.canvas.currentLayer()
     srid = layer.crs().authid()
     crsDest = QgsCoordinateReferenceSystem(srid) #here we have to put authid, not srid
     # Creating a transformer
     coordinateTransformer = QgsCoordinateTransform(crsSrc, crsDest)
     lyrType = self.iface.activeLayer().geometryType()
     # Transforming the points
     if lyrType == QGis.Line:
         geomList = geom.asPolyline()
     elif lyrType == QGis.Polygon:
         geomList = geom.asPolygon()
     newGeom = []
     for j in xrange(len(geomList)):
         if lyrType == QGis.Line:
             newGeom.append(coordinateTransformer.transform(geomList[j]))
         elif lyrType == QGis.Polygon:
             line = geomList[j]
             for i in xrange(len(line)):
                 point = line[i]
                 newGeom.append(coordinateTransformer.transform(point))
     if lyrType == QGis.Line:
         return QgsGeometry.fromPolyline(newGeom + [newGeom[0]])
     elif lyrType == QGis.Polygon:
         return QgsGeometry.fromPolygon([newGeom])                   
 def __signal_pbCopyKml_clicked(self, cheked):
     # Extent Openlayers
     action = "map.getExtent().toGeometry().toString();"
     wkt = self.webViewMap.page().mainFrame().evaluateJavaScript(action)
     rect = QgsGeometry.fromWkt(wkt).boundingBox()
     srsGE = QgsCoordinateReferenceSystem(
         4326, QgsCoordinateReferenceSystem.EpsgCrsId)
     coodTrans = QgsCoordinateTransform(self.__srsOL, srsGE,
                                        QgsProject.instance())
     rect = coodTrans.transform(
         rect, QgsCoordinateTransform.ForwardTransform)
     line = QgsGeometry.fromRect(rect).asPolygon()[0]
     wkt = str(QgsGeometry.fromPolylineXY(line).asWkt())
     # Kml
     proj4 = str(srsGE.toProj4())
     kmlLine = bindogr.exportKml(wkt, proj4)
     kml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"\
           "<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\">" \
           "<Placemark>" \
           "<name>KML from Plugin Openlayers Overview for QGIS</name>" \
           "<description>Extent of openlayers map from Plugin Openlayers \
           Overview for QGIS</description>"\
           "%s" \
           "</Placemark></kml>" % kmlLine
     clipBoard = QApplication.clipboard()
     clipBoard.setText(kml)
Ejemplo n.º 3
0
    def set_bbox_from_map(self):
        """set bounding box from map extent"""

        crs = self.map.mapSettings().destinationCrs()
        try:
            crsid = int(crs.authid().split(':')[1])
        except IndexError:  # no projection
            crsid = 4326

        extent = self.map.extent()

        if crsid != 4326:  # reproject to EPSG:4326
            src = QgsCoordinateReferenceSystem(crsid)
            dest = QgsCoordinateReferenceSystem(4326)
            xform = QgsCoordinateTransform(src, dest, QgsProject.instance())
            minxy = xform.transform(QgsPointXY(extent.xMinimum(),
                                               extent.yMinimum()))
            maxxy = xform.transform(QgsPointXY(extent.xMaximum(),
                                               extent.yMaximum()))
            minx, miny = minxy
            maxx, maxy = maxxy
        else:  # 4326
            minx = extent.xMinimum()
            miny = extent.yMinimum()
            maxx = extent.xMaximum()
            maxy = extent.yMaximum()

        self.leNorth.setText(str(maxy)[0:9])
        self.leSouth.setText(str(miny)[0:9])
        self.leWest.setText(str(minx)[0:9])
        self.leEast.setText(str(maxx)[0:9])
    def bounds(self):
        """
        Function for recalculating the bounded extents of the
        layers as they are processed. Under construction
        :return:
        """
        # Requires refinement for raster manipulation of bounds
        selected_extent = unicode(self.getParameterValue(self.MAP_EXTENT)).split(',')

        xMin = float(selected_extent[0])
        xMax = float(selected_extent[1])
        yMin = float(selected_extent[2])
        yMax = float(selected_extent[3])
        extent = QgsRectangle(xMin, yMin, xMax, yMax)

        mapCRS = iface.mapCanvas().mapSettings().destinationCrs()
        transform = QgsCoordinateTransform(
            mapCRS,
            QgsCoordinateReferenceSystem('EPSG:4326')  # WGS84
            # QgsCoordinateReferenceSystem('EPSG:3785')  # Popular vis mercator
        )

        try:
            layer_extent = transform.transform(extent)
        except QgsCsException:
            ProcessingLog.addToLog(ProcessingLog.LOG_WARNING,
                                   "exception in transform layer srs")
            layer_extent = QgsRectangle(-180, -90, 180, 90)

        ProcessingLog.addToLog(ProcessingLog.LOG_INFO, layer_extent.toString())

        return layer_extent
Ejemplo n.º 5
0
    def onReturnPressed(self):
        try:
            txt = self.editSearch.text().strip()
            self.plugin.lastSearch = self.editSearch.text()
            self.plugin.limitSearchToExtent = (self.cbExtent.isChecked())
            options = self.plugin.gnOptions

            options2 = {}
            if self.plugin.limitSearchToExtent:
                sourceCrs = self.plugin.canvas.mapSettings().destinationCrs()
                targetCrs = QgsCoordinateReferenceSystem()
                targetCrs.createFromSrid(4326)
                xform = QgsCoordinateTransform(sourceCrs, targetCrs, QgsProject.instance())
                geom = xform.transform(self.plugin.canvas.extent())
                options2 = {'viewbox': str(geom.xMinimum()) + ',' +
                            str(geom.yMaximum()) + ',' +
                            str(geom.xMaximum()) + ',' +
                            str(geom.yMinimum())}

            params = {'q': txt, 'addressdetails': '0'}
            self.searchJson(params, self.plugin.gnUsername, options, options2)

        except Exception as e:
            for m in e.args:
                QgsMessageLog.logMessage(m, 'Extensions')
            pass
Ejemplo n.º 6
0
    def show_user_analysis_extent(self):
        """Update the rubber band showing the user defined analysis extent.

        Primary purpose of this slot is to draw a rubber band of where the
        analysis will be carried out based on valid intersection between
        layers and the user's preferred analysis area.

        This slot is called on pan, zoom, layer visibility changes and
        when the user updates the defined extent.

        .. versionadded:: 2.2.0
        """
        self.hide_user_analysis_extent()

        extent = self.user_extent
        source_crs = self.user_extent_crs

        try:
            extent = self.validate_rectangle(extent)
        except InvalidGeometryError:
            # keep existing user extent without updating it
            return

        # make sure the extent is in the same crs as the canvas
        destination_crs = self.iface.mapCanvas().mapSettings().destinationCrs()
        transform = QgsCoordinateTransform(source_crs, destination_crs)
        extent = transform.transformBoundingBox(extent)

        if self.show_rubber_bands:
            # Draw in blue
            self.user_analysis_rubberband = self._draw_rubberband(
                extent, QColor(0, 0, 255, 100))
Ejemplo n.º 7
0
def extent_to_geoarray(extent, source_crs):
    """Convert the supplied extent to geographic and return as as array.

    :param extent: QgsRectangle to be transformed to geocrs.
    :type extent:

    :param source_crs: QgsCoordinateReferenceSystem representing the
        original extent's CRS.
    :type source_crs:

    :returns: Transformed extents in EPSG:4326 in the form
        [xmin, ymin, xmax, ymax]
    """

    myGeoCrs = QgsCoordinateReferenceSystem()
    myGeoCrs.createFromId(4326, QgsCoordinateReferenceSystem.EpsgCrsId)
    myXForm = QgsCoordinateTransform(
        source_crs,
        myGeoCrs)

    # Get the clip area in the layer's crs
    myTransformedExtent = myXForm.transformBoundingBox(extent)

    myGeoExtent = [myTransformedExtent.xMinimum(),
                   myTransformedExtent.yMinimum(),
                   myTransformedExtent.xMaximum(),
                   myTransformedExtent.yMaximum()]
    return myGeoExtent
Ejemplo n.º 8
0
Archivo: gps.py Proyecto: GEO-IASS/Roam
    def gpsStateChanged(self, gpsInfo):
        if gpsInfo.fixType == NMEA_FIX_BAD or gpsInfo.status == 0 or gpsInfo.quality == 0:
            self.gpsfixed.emit(False, gpsInfo)
            return

        elif gpsInfo.fixType == NMEA_FIX_3D or NMEA_FIX_2D:
            self.gpsfixed.emit(True, gpsInfo)


        map_pos = QgsPoint(gpsInfo.longitude, gpsInfo.latitude)

        if self.crs:
            transform = QgsCoordinateTransform(self.wgs84CRS, self.crs)
            try:
                map_pos = transform.transform(map_pos)
            except QgsCsException:
                log("Transform exception")
                return

            if self.postion is None:
                self.firstfix.emit(map_pos, gpsInfo)

            self.gpspostion.emit(map_pos, gpsInfo)
            self.postion = map_pos
            self.elevation = gpsInfo.elevation
 def clicked(self, pt, b):
     '''Capture the coordinate when the mouse button has been released,
     format it, and copy it to the clipboard.'''
     if settings.captureShowLocation:
         if self.marker is None:
             self.marker = QgsVertexMarker(self.canvas)
             self.marker.setIconSize(18)
             self.marker.setPenWidth(2)
             self.marker.setIconType(QgsVertexMarker.ICON_CROSS)
         self.marker.setCenter(pt)
     else:
         self.removeMarker();
     
     try:
         if self.capture4326:
             canvasCRS = self.canvas.mapSettings().destinationCrs()
             transform = QgsCoordinateTransform(canvasCRS, epsg4326, QgsProject.instance())
             pt4326 = transform.transform(pt.x(), pt.y())
             self.capturesig.emit(pt4326)
             return
         msg = self.formatCoord(pt, self.settings.delimiter)
         formatString = self.coordFormatString()
         if msg != None:
             clipboard = QApplication.clipboard()
             clipboard.setText(msg)
             self.iface.messageBar().pushMessage("", "{} coordinate {} copied to the clipboard".format(formatString, msg), level=Qgis.Info, duration=4)
     except Exception as e:
         self.iface.messageBar().pushMessage("", "Invalid coordinate: {}".format(e), level=Qgis.Warning, duration=4)
Ejemplo n.º 10
0
def extent_to_geo_array(extent, source_crs, dest_crs=None):
    """Convert the supplied extent to geographic and return as an array.

    :param extent: Rectangle defining a spatial extent in any CRS.
    :type extent: QgsRectangle

    :param source_crs: Coordinate system used for extent.
    :type source_crs: QgsCoordinateReferenceSystem

    :returns: a list in the form [xmin, ymin, xmax, ymax] where all
            coordinates provided are in Geographic / EPSG:4326.
    :rtype: list

    """

    if dest_crs is None:
        geo_crs = QgsCoordinateReferenceSystem()
        geo_crs.createFromSrid(4326)
    else:
        geo_crs = dest_crs

    transform = QgsCoordinateTransform(source_crs, geo_crs)

    # Get the clip area in the layer's crs
    transformed_extent = transform.transformBoundingBox(extent)

    geo_extent = [
        transformed_extent.xMinimum(),
        transformed_extent.yMinimum(),
        transformed_extent.xMaximum(),
        transformed_extent.yMaximum()]
    return geo_extent
Ejemplo n.º 11
0
    def proj4Utm(self, p):

        mapCrs = self.canvas.mapSettings().destinationCrs()
        if not mapCrs.geographicFlag():
            # if not geographic transform it to a geographic crs
            geographicCrs = QgsCoordinateReferenceSystem(4326, QgsCoordinateReferenceSystem.EpsgCrsId)
            ct = QgsCoordinateTransform(mapCrs, geographicCrs)
            p = ct.transform(p)

        x = p.x()
        y = p.y()
        z = math.floor((x + 180) / 6) + 1

        if y >= 56.0 and y < 64.0 and x >= 3.0 and x < 12.0:
            ZoneNumber = 32

        # Special zones for Svalbard
        if y >= 72.0 and y < 84.0:
            if y >= 0.0 and y < 9.0:
                z = 31
            elif y >= 9.0 and y < 21.0:
                z = 33
            elif y >= 21.0 and y < 33.0:
                z = 35
            elif y >= 33.0 and y < 42.0:
                z = 37

        return "+proj=utm +zone={0} +datum=WGS84 +units=m +no_defs".format(int(z))
 def selectVisibleRasters(self):
     self.refreshRasterList()
     self.selectingVisibleRasters = True
     extCanvas = self.iface.mapCanvas().extent()
     #alle raster in den einstellunge deselektieren
     for r in self.settings.mapData.rasters.rasters():
         r.selected = False
     #alle raster in der ListView deselektieren
     for idx in range(self.ui.IDC_listRasters.count()):
         item = self.ui.IDC_listRasters.item(idx)
         item.setCheckState(Qt.Unchecked)
     #Raster im Extent selektieren
     canvasCrs = self.iface.mapCanvas().mapSettings().destinationCrs()
     for idx in range(self.ui.IDC_listRasters.count()):
         item = self.ui.IDC_listRasters.item(idx)
         raster = item.data(Qt.UserRole)
         for r in self.settings.mapData.rasters.rasters():
             layerCrs = r.grid.crs()
             ct = QgsCoordinateTransform(layerCrs, canvasCrs, QgsProject.instance())
             extent = ct.transform(r.grid.extent())
             if extCanvas.intersects(extent):
                 if r.id == raster.id:
                     r.selected = True
                     item.setCheckState(Qt.Checked)
     self.selectingVisibleRasters = False
Ejemplo n.º 13
0
def getCoordinatesByAddress(address,crs=None):

    # In: Country, City, Postal Address or Parts of it
    #     Target Coordinate Reference System as EPSG Code

    # Out: dict of all informations delivered by googlemaps
    if isinstance(address, unicode):
        address = address.encode('utf-8')

    urlParams = {'q': address,
                 'format': 'json',
                'addressdetails': '1',
        }
    url='http://nominatim.openstreetmap.org/search?'+urllib.urlencode(urlParams)

    response = urllib2.urlopen(url)
    result = json.load(response)
    #print result['results']

    # try:
    addrlist = []
    for addrrecord in result:
        dataset = {}
        dataset['latitude'] = addrrecord['lat']
        dataset['longitude'] = addrrecord['lon']
        if crs:
            targetCRS = QgsCoordinateReferenceSystem(crs, QgsCoordinateReferenceSystem.EpsgCrsId)
            googleMapsCRS = QgsCoordinateReferenceSystem(4326, QgsCoordinateReferenceSystem.EpsgCrsId)
            location = QgsCoordinateTransform(googleMapsCRS, targetCRS).transform(QgsPoint(dataset['longitude'], dataset['latitude']))
            dataset['latitude'] = location.y()
            dataset['longitude'] = location.x()
        addrlist.append(complete_google_dataset(dataset))
    # except:
    #    return []
    return addrlist
Ejemplo n.º 14
0
def extentToGeoArray(theExtent, theSourceCrs):
    """Convert the supplied extent to geographic and return as as array.

    Args:
        theExtent: QgsRectangle to be transformed to geocrs.
        theSourceCrs: QgsCoordinateReferenceSystem representing the original
            extent's CRS.

    Returns:
        list: Transformed extents in EPSG:4326 in the form
              [xmin, ymin, xmix, ymax]

    Raises:
        None
    """

    myGeoCrs = QgsCoordinateReferenceSystem()
    myGeoCrs.createFromId(4326, QgsCoordinateReferenceSystem.EpsgCrsId)
    myXForm = QgsCoordinateTransform(
        theSourceCrs,
        myGeoCrs)

    # Get the clip area in the layer's crs
    myTransformedExtent = myXForm.transformBoundingBox(theExtent)

    myGeoExtent = [myTransformedExtent.xMinimum(),
                   myTransformedExtent.yMinimum(),
                   myTransformedExtent.xMaximum(),
                   myTransformedExtent.yMaximum()]
    return myGeoExtent
Ejemplo n.º 15
0
    def _calc_north(self):
        extent = self.canvas.extent()
        if self.canvas.layerCount() == 0 or extent.isEmpty():
            print "No layers or extent"
            return 0

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

        if outcrs.isValid() and not outcrs.geographicFlag():
            crs = QgsCoordinateReferenceSystem()
            crs.createFromOgcWmsCrs("EPSG:4326")

            transform = QgsCoordinateTransform(outcrs, crs)

            p1 = QgsPoint(extent.center())
            p2 = QgsPoint(p1.x(), p1.y() + extent.height() * 0.25)

            try:
                pp1 = transform.transform(p1)
                pp2 = transform.transform(p2)
            except QgsCsException:
                roam.utils.warning("North arrow. Error transforming.")
                return None

            area = QgsDistanceArea()
            area.setEllipsoid(crs.ellipsoidAcronym())
            area.setEllipsoidalMode(True)
            area.setSourceCrs(crs)
            distance, angle, _ = area.computeDistanceBearing(pp1, pp2)
            angle = math.degrees(angle)
            return angle
        else:
            return 0
Ejemplo n.º 16
0
def rasterScript(layer, safeLayerName):
    out_raster = 'data/' + safeLayerName + '.png'
    pt2 = layer.extent()
    crsSrc = layer.crs()
    crsDest = QgsCoordinateReferenceSystem(4326)
    try:
        xform = QgsCoordinateTransform(crsSrc, crsDest, QgsProject.instance())
    except:
        xform = QgsCoordinateTransform(crsSrc, crsDest)
    pt3 = xform.transformBoundingBox(pt2)
    bbox_canvas2 = [pt3.yMinimum(), pt3.yMaximum(),
                    pt3.xMinimum(), pt3.xMaximum()]
    bounds = '[[' + unicode(pt3.yMinimum()) + ','
    bounds += unicode(pt3.xMinimum()) + '],['
    bounds += unicode(pt3.yMaximum()) + ','
    bounds += unicode(pt3.xMaximum()) + ']]'
    raster = """
        var img_{safeLayerName} = '{out_raster}';
        var img_bounds_{safeLayerName} = {bounds};
        var overlay_{safeLayerName} = """.format(safeLayerName=safeLayerName,
                                                 out_raster=out_raster,
                                                 bounds=bounds)
    raster += "new L.imageOverlay(img_"
    raster += """{safeLayerName}, img_bounds_{safeLayerName});
        bounds_group.addLayer(overlay_{safeLayerName});""".format(
        safeLayerName=safeLayerName)
    return raster
Ejemplo n.º 17
0
    def set_bbox_from_map(self):
        """set bounding box from map extent"""

        crs = self.map.mapRenderer().destinationCrs()
        crsid = int(crs.authid().split(':')[1])

        extent = self.map.extent()

        if crsid != 4326:  # reproject to EPSG:4326
            src = QgsCoordinateReferenceSystem(crsid)
            dest = QgsCoordinateReferenceSystem(4326)
            xform = QgsCoordinateTransform(src, dest)
            minxy = xform.transform(QgsPoint(extent.xMinimum(),
                                             extent.yMinimum()))
            maxxy = xform.transform(QgsPoint(extent.xMaximum(),
                                             extent.yMaximum()))
            minx, miny = minxy
            maxx, maxy = maxxy
        else:  # 4326
            minx = extent.xMinimum()
            miny = extent.yMinimum()
            maxx = extent.xMaximum()
            maxy = extent.yMaximum()

        self.leNorth.setText(unicode(maxy)[0:9])
        self.leSouth.setText(unicode(miny)[0:9])
        self.leWest.setText(unicode(minx)[0:9])
        self.leEast.setText(unicode(maxx)[0:9])
Ejemplo n.º 18
0
    def doGeocoding(self, address):
        address = unicodedata.normalize('NFKD', unicode(address)).encode('ASCII', 'ignore')
        url = "http://api-adresse.data.gouv.fr/search/?q="+address.replace(" ", "%20")
        
        result = self.request(url)

        try:
            data = json.loads(result)
            features = data["features"]
            if len(features) > 0:
                feature_list = []
                for feature in features:
                    feature_list.append(feature["properties"]["label"]+" - "+str(round(feature["properties"]["score"]*100))+"%")
                feature, ok = QInputDialog.getItem(self.iface.mainWindow(), self.tr("Result"), "", feature_list)
                if ok:
                    index = feature_list.index(feature)
                    x = features[index]["geometry"]["coordinates"][0]
                    y = features[index]["geometry"]["coordinates"][1]
                    point_4326 = QgsPoint(x, y)
                    transform = QgsCoordinateTransform(QgsCoordinateReferenceSystem(4326), 
                                                        self.canvas.mapSettings().destinationCrs())
                    point_2154 = transform.transform(point_4326)
                    self.rb.addPoint(point_2154)
                    self.iface.mapCanvas().setCenter(point_2154)
                    self.iface.mapCanvas().refresh()
            else:
                QMessageBox.information(self.iface.mainWindow(), self.tr("Result"), self.tr("No result."))
        except ValueError:
            QMessageBox.critical(self.iface.mainWindow(), self.tr("Error"), self.tr("An error occured. Check your network settings (proxy)."))
Ejemplo n.º 19
0
def extent_to_geo_array(extent, source_crs):
    """Convert the supplied extent to geographic and return as an array.

    :param extent: Rectangle defining a spatial extent in any CRS.
    :type extent: QgsRectangle

    :param source_crs: Coordinate system used for extent.
    :type source_crs: QgsCoordinateReferenceSystem

    :returns: a list in the form [xmin, ymin, xmax, ymax] where all
            coordinates provided are in Geographic / EPSG:4326.
    :rtype: list

    """

    myGeoCrs = QgsCoordinateReferenceSystem()
    myGeoCrs.createFromId(4326, QgsCoordinateReferenceSystem.EpsgCrsId)
    myXForm = QgsCoordinateTransform(source_crs, myGeoCrs)

    # Get the clip area in the layer's crs
    myTransformedExtent = myXForm.transformBoundingBox(extent)

    myGeoExtent = [myTransformedExtent.xMinimum(),
                   myTransformedExtent.yMinimum(),
                   myTransformedExtent.xMaximum(),
                   myTransformedExtent.yMaximum()]
    return myGeoExtent
Ejemplo n.º 20
0
Archivo: gps.py Proyecto: skeenp/Roam
    def gpsStateChanged(self, gpsInfo):
        if gpsInfo.fixType == NMEA_FIX_BAD or gpsInfo.status == 0 or gpsInfo.quality == 0:
            self.gpsfixed.emit(False, gpsInfo)
            return

        elif gpsInfo.fixType == NMEA_FIX_3D or NMEA_FIX_2D:
            self.gpsfixed.emit(True, gpsInfo)


        map_pos = QgsPoint(gpsInfo.longitude, gpsInfo.latitude)
        self.latlong_position = map_pos

        if self.crs:
            transform = QgsCoordinateTransform(self.wgs84CRS, self.crs)
            try:
                map_pos = transform.transform(map_pos)
            except QgsCsException:
                log("Transform exception")
                return

            if self.postion is None:
                self.firstfix.emit(map_pos, gpsInfo)

            self.info = gpsInfo

            if (datetime.now()-self._gpsupdate_last).total_seconds() > self._gpsupdate_frequency:
                self.gpsposition.emit(map_pos, gpsInfo)
                self._gpsupdate_last = datetime.now()

            self.postion = map_pos
            self.elevation = gpsInfo.elevation
Ejemplo n.º 21
0
    def load_layer_features(self, point=None, layers=None):

        # TODO Move this logic into the viewer and let it track it's position
        if point is None and self.marker.map_pos is None:
            return

        if point is None:
            point = self.marker.map_pos

        area, units = self.distancearea()
        rect = search_area(units, area, point)

        if layers is None:
            layers = self.visible_layers()

        for layer in layers:
            transform = self.coordinatetransform(layer)
            # Transform the rect
            source = self.canvas.mapRenderer().destinationCrs()
            dest = layer.crs()
            recttransform = QgsCoordinateTransform(source, dest)
            rect = recttransform.transformBoundingBox(rect)
            features = list(get_features_in_area(layer, rect, transform, self.canvas.mapSettings()))
            geomtype = layer.geometryType()
            layerdata = dict(id=layer.id(), geomtype=QGis.vectorGeometryType(geomtype))
            self.viewer.load_features(layerdata, features)
Ejemplo n.º 22
0
    def josm_remote(self):
        map_settings = self.iface.mapCanvas().mapSettings()
        extent = map_settings.extent()
        crs_map = map_settings.destinationCrs()
        if crs_map.authid() != 'EPSG:4326':
            crs_4326 = QgsCoordinateReferenceSystem(4326)
            transform = QgsCoordinateTransform(crs_map, crs_4326, QgsProject.instance())
            extent = transform.transform(extent)

        url = 'http://localhost:8111/load_and_zoom?'
        query_string = 'left=%f&right=%f&top=%f&bottom=%f' % (
            extent.xMinimum(), extent.xMaximum(), extent.yMaximum(),
            extent.yMinimum())
        url += query_string
        try:
            request = urllib.request.Request(url)
            result_request = urllib.request.urlopen(request)
            result = result_request.read()
            result = result.decode('utf8')
            if result.strip().upper() != 'OK':
                self.iface.messageBar().pushCritical(
                    tr('JOSM Remote'), result)
            else:
                self.iface.messageBar().pushSuccess(
                    tr('JOSM Remote'), tr('Import done, check JOSM'))
        except IOError:
            self.iface.messageBar().pushCritical(
                tr('JOSM Remote'), tr('Is the remote enabled?'))
    def test_province_for_point(self):
        """Test for province for point function."""
        # Point falls in South Africa
        point = QgsPoint(21, -30)
        expected_province = 'Free State'
        province = province_for_point(self.database_manager, point)
        message = 'Should be %s but got %s' % (expected_province, province)
        self.assertEqual(expected_province, province, message)

        # Point falls in Indonesia
        point = QgsPoint(109, -7)
        expected_province = None
        province = province_for_point(self.database_manager, point)
        message = 'Should be %s but got %s' % (expected_province, province)
        self.assertEqual(expected_province, province, message)

        # Point falls in South Africa but uses different CRS
        point = QgsPoint(2265216.874, -3952469.869)
        expected_province = None
        province = province_for_point(self.database_manager, point)
        message = 'Should be %s but got %s' % (expected_province, province)
        self.assertEqual(expected_province, province, message)

        # Point falls in South Africa but uses different CRS, reproject to 4326
        osm_crs = QgsCoordinateReferenceSystem(3857)
        wgs84_crs = QgsCoordinateReferenceSystem(4326)
        transformer = QgsCoordinateTransform(osm_crs, wgs84_crs)

        point = QgsPoint(2265216.874, -3952469.869)
        point_transformed = transformer.transform(point)

        expected_province = 'Western Cape'
        province = province_for_point(self.database_manager, point_transformed)
        message = 'Should be %s but got %s' % (expected_province, province)
        self.assertEqual(expected_province, province, message)
Ejemplo n.º 24
0
def writeTmpLayer(layer, restrictToExtent, iface, extent):
    fields = layer.fields()
    usedFields = []
    for count, field in enumerate(fields):
        fieldIndex = fields.indexFromName(unicode(field.name()))
        editorWidget = layer.editorWidgetSetup(fieldIndex).type()
        addField = False
        try:
            if layer.renderer().classAttribute() == field.name():
                addField = True
        except:
            pass
        if layer.customProperty("labeling/fieldName") == field.name():
            addField = True
        if (editorWidget != 'Hidden'):
            addField = True
        if addField:
            usedFields.append(count)
    uri = TYPE_MAP[layer.wkbType()]
    crs = layer.crs()
    if crs.isValid():
        uri += '?crs=' + crs.authid()
    for field in usedFields:
        fieldIndex = layer.fields().indexFromName(unicode(
            layer.fields().field(field).name()))
        editorWidget = layer.editorWidgetSetup(fieldIndex).type()
        fieldType = layer.fields().field(field).type()
        fieldName = layer.fields().field(field).name()
        if (editorWidget == 'Hidden'):
            fieldName = "q2wHide_" + fieldName
        fieldType = "double" if (fieldType == QVariant.Double or
                                 fieldType == QVariant.Int) else ("string")
        uri += '&field=' + unicode(fieldName) + ":" + fieldType
    newlayer = QgsVectorLayer(uri, layer.name(), 'memory')
    writer = newlayer.dataProvider()
    outFeat = QgsFeature()
    if restrictToExtent and extent == "Canvas extent":
        canvas = iface.mapCanvas()
        extent = canvas.extent()
        canvasCRS = canvas.mapSettings().destinationCrs()
        layerCRS = layer.crs()
        try:
            transform = QgsCoordinateTransform(canvasCRS, layerCRS,
                                               QgsProject.instance())
        except:
            transform = QgsCoordinateTransform(canvasCRS, layerCRS)
        projectedExtent = transform.transformBoundingBox(extent)
        request = QgsFeatureRequest(projectedExtent)
        request.setFlags(QgsFeatureRequest.ExactIntersect)
        features = layer.getFeatures(request)
    else:
        features = layer.getFeatures()
    for feature in features:
        if feature.geometry() is not None:
            outFeat.setGeometry(feature.geometry())
        attrs = [feature[f] for f in usedFields]
        if attrs:
            outFeat.setAttributes(attrs)
        writer.addFeatures([outFeat])
    return newlayer
Ejemplo n.º 25
0
    def show_exposure(self, hostname, username, password):
        selected_extent = self.selectedExtent()
        if selected_extent is None:
            QtGui.QMessageBox.warning(
                self, 'Exposure Download Error', 'No region selected')
            return
        self.enableBusyCursor()
        try:
            crs = self.iface.mapCanvas().mapRenderer().destinationCrs()
            xform = QgsCoordinateTransform(
                crs, QgsCoordinateReferenceSystem(4326))
            extent = xform.transform(selected_extent)
            lon_min, lon_max = extent.xMinimum(), extent.xMaximum()
            lat_min, lat_max = extent.yMinimum(), extent.yMaximum()

            # download data
            ed = ExposureDownloader(hostname)
            ed.login(username, password)
            try:
                fname, msg = ed.download(lat_min, lon_min, lat_max, lon_max)
            except ExposureDownloadError as e:
                QtGui.QMessageBox.warning(
                    self, 'Exposure Download Error', str(e))
                return
            QgsMessageLog.logMessage(msg, 'GEM Exposure Downloader')
            # don't remove the file, otherwise there will concurrency problems
            uri = 'file://%s?delimiter=%s&xField=%s&yField=%s&crs=epsg:4326&' \
                'skipLines=25&trimFields=yes' % (fname, ',', 'lon', 'lat')
            vlayer = QgsVectorLayer(uri, 'exposure_export', 'delimitedtext')
            QgsMapLayerRegistry.instance().addMapLayer(vlayer)
        finally:
            self.disableBusyCursor()
Ejemplo n.º 26
0
def EPSG(self):
    currentEPSG = self.canvas.mapRenderer().destinationCrs().authid()
    if currentEPSG != 'EPSG:4326':
        crsSrc = QgsCoordinateReferenceSystem(int(currentEPSG[5:]))
        crsDest = QgsCoordinateReferenceSystem(4326) ## WGS-84
        xform = QgsCoordinateTransform(crsSrc, crsDest)
        self.coordsClick = xform.transform(self.pntGeom.asPoint())
Ejemplo n.º 27
0
    def __getValsAtPoint(self, pnt):
        vals = []
        rasterNodata = []

        for rObj in self.settings.mapData.rasters.selectedRasters():
            raster = rObj.grid

            nodata = raster.dataProvider().sourceNoDataValue(1)
            if not math.isnan(nodata):
                rasterNodata.append(nodata)
            nodata = raster.dataProvider().userNoDataValues(1)
            for v in nodata:
                if v.min() not in rasterNodata:
                    rasterNodata.append(v.min())
                if v.max() not in rasterNodata:
                    rasterNodata.append(v.max())

            #TODO!!!! QGIS BUG: QGIS 2.0.1: raster.noDataValue() = > AttributeError: 'QgsRasterLayer' object has no attribute 'noDataValue'
            raster_val = self.settings.nodata_value

            #QgsMessageLog.logMessage('raster_val VOR identify:' + str(raster_val), 'VoGis', Qgis.Info)

            #check if coordinate systems match
            p = None
            if self.settings.modeLine == enumModeLine.line:
                if raster.crs() != self.settings.mapData.selectedLineLyr.line.crs():
                    transform = QgsCoordinateTransform(self.settings.mapData.selectedLineLyr.line.crs(),
                                                       raster.crs(), QgsProject.instance())
                    p = transform.transform(pnt)
            else:
                if raster.crs() != self.iface.mapCanvas().mapSettings().destinationCrs():
                    transform = QgsCoordinateTransform(self.iface.mapCanvas().mapSettings().destinationCrs(),
                                                       raster.crs(), QgsProject.instance())
                    p = transform.transform(pnt)

            if p is None:
                #QgsMessageLog.logMessage(u'point not transformed {0}'.format(str(pnt)))
                p = pnt

            identify_result = raster.dataProvider().identify(p, QgsRaster.IdentifyFormatValue)
            #QgsMessageLog.logMessage(u'identify_result: {0}'.format(identify_result.results()), 'VoGis', Qgis.Info)
            for bnd_nr, pix_val in identify_result.results().items():
                if 1 == bnd_nr:
                    try:
                        if pix_val is None:
                            raster_val = self.settings.nodata_value
                        else:
                            raster_val = float(pix_val)
                    #except ValueError:
                    except:
                        QgsMessageLog.logMessage('pix_val Exception: ' + str(pix_val), 'VoGis', Qgis.Info)
                        raster_val = self.settings.nodata_value

            #QgsMessageLog.logMessage('raster_val NACH identify:' + str(raster_val), 'VoGis', Qgis.Info)

            vals.append(raster_val)

        #QMessageBox.warning(self.InterFace.mainWindow(), "VoGIS-Profiltool", str(vals))
        return vals, rasterNodata
 def calcAreaPixelInLayerPolygon(crs_map, paramsTransform):
   crsImage = QgsCoordinateReferenceSystem( crs_map )
   crsLayer = self.paramProcess['layerPolygon'].crs()
   ct =  QgsCoordinateTransform( crsImage, crsLayer, QgsCoordinateTransformContext() )
   p1 = ct.transform( paramsTransform[0], paramsTransform[3] )
   p2 = ct.transform( p1.x() + paramsTransform[1], p1.y() + paramsTransform[5] )
   dist = p1.distance( p2 )
   return dist * dist
Ejemplo n.º 29
0
 def get_current_map(self):
 	curX = self.iface.mapCanvas().extent().center().x()
 	curY = self.iface.mapCanvas().extent().center().y()
 	EPSG = self.iface.mapCanvas().mapRenderer().destinationCrs().authid().split(":")[1]
 	transf = QgsCoordinateTransform( QgsCoordinateReferenceSystem(int(EPSG)), QgsCoordinateReferenceSystem(4326) )
 	centerPoint = transf.transform(QgsPoint(curX, curY))
 	centerCoordinate = str(centerPoint.x()) + "," + str(centerPoint.y())
 	return centerCoordinate
 def transform_to_epsg_4326(self, point):
     if self.canvas.mapRenderer().destinationCrs().authid() != 'EPSG:4326':
         crs_src = self.canvas.mapRenderer().destinationCrs()
         crs_dest = QgsCoordinateReferenceSystem(4326)
         xform = QgsCoordinateTransform(crs_src, crs_dest)
         return QgsGeometry.fromPoint(xform.transform(point)).asPoint()
     else:
         return point
Ejemplo n.º 31
0
class TilesXYZAlgorithmBase(QgisAlgorithm):
    EXTENT = 'EXTENT'
    ZOOM_MIN = 'ZOOM_MIN'
    ZOOM_MAX = 'ZOOM_MAX'
    DPI = 'DPI'
    BACKGROUND_COLOR = 'BACKGROUND_COLOR'
    TILE_FORMAT = 'TILE_FORMAT'
    QUALITY = 'QUALITY'
    METATILESIZE = 'METATILESIZE'

    def initAlgorithm(self, config=None):
        self.addParameter(
            QgsProcessingParameterExtent(self.EXTENT, self.tr('Extent')))
        self.addParameter(
            QgsProcessingParameterNumber(self.ZOOM_MIN,
                                         self.tr('Minimum zoom'),
                                         minValue=0,
                                         maxValue=25,
                                         defaultValue=12))
        self.addParameter(
            QgsProcessingParameterNumber(self.ZOOM_MAX,
                                         self.tr('Maximum zoom'),
                                         minValue=0,
                                         maxValue=25,
                                         defaultValue=12))
        self.addParameter(
            QgsProcessingParameterNumber(self.DPI,
                                         self.tr('DPI'),
                                         minValue=48,
                                         maxValue=600,
                                         defaultValue=96))
        self.addParameter(
            QgsProcessingParameterColor(self.BACKGROUND_COLOR,
                                        self.tr('Background color'),
                                        defaultValue=QColor(Qt.transparent),
                                        optional=True))
        self.formats = ['PNG', 'JPG']
        self.addParameter(
            QgsProcessingParameterEnum(self.TILE_FORMAT,
                                       self.tr('Tile format'),
                                       self.formats,
                                       defaultValue=0))
        self.addParameter(
            QgsProcessingParameterNumber(self.QUALITY,
                                         self.tr('Quality (JPG only)'),
                                         minValue=1,
                                         maxValue=100,
                                         defaultValue=75))
        self.addParameter(
            QgsProcessingParameterNumber(self.METATILESIZE,
                                         self.tr('Metatile size'),
                                         minValue=1,
                                         maxValue=20,
                                         defaultValue=4))
        self.thread_nr_re = re.compile('[0-9]+$')  # thread number regex

    def prepareAlgorithm(self, parameters, context, feedback):
        project = context.project()
        visible_layers = [
            item.layer() for item in project.layerTreeRoot().findLayers()
            if item.isVisible()
        ]
        self.layers = [
            l for l in project.layerTreeRoot().layerOrder()
            if l in visible_layers
        ]
        return True

    def renderSingleMetatile(self, metatile):
        if self.feedback.isCanceled():
            return
            # Haven't found a better way to break than to make all the new threads return instantly

        if "Dummy" in threading.current_thread().name or len(
                self.settingsDictionary) == 1:  # single thread testing
            threadSpecificSettings = list(self.settingsDictionary.values())[0]
        else:
            thread_nr = self.thread_nr_re.search(
                threading.current_thread().name)[0]  # terminating number only
            threadSpecificSettings = self.settingsDictionary[thread_nr]

        size = QSize(self.tile_width * metatile.rows(),
                     self.tile_height * metatile.columns())
        extent = QgsRectangle(*metatile.extent())
        threadSpecificSettings.setExtent(
            self.wgs_to_dest.transformBoundingBox(extent))
        threadSpecificSettings.setOutputSize(size)

        #Append MapSettings scope in order to update map variables (e.g @map_scale) with new extent data
        exp_context = threadSpecificSettings.expressionContext()
        exp_context.appendScope(
            QgsExpressionContextUtils.mapSettingsScope(threadSpecificSettings))
        threadSpecificSettings.setExpressionContext(exp_context)

        image = QImage(size, QImage.Format_ARGB32_Premultiplied)
        image.fill(self.color)
        dpm = threadSpecificSettings.outputDpi() / 25.4 * 1000
        image.setDotsPerMeterX(dpm)
        image.setDotsPerMeterY(dpm)
        painter = QPainter(image)
        job = QgsMapRendererCustomPainterJob(threadSpecificSettings, painter)
        job.renderSynchronously()
        painter.end()

        ## For analysing metatiles (labels, etc.)
        ## metatile_dir = os.path.join(output_dir, str(zoom))
        ## os.makedirs(metatile_dir, exist_ok=True)
        ## image.save(os.path.join(metatile_dir, 'metatile_%s.png' % i))

        for r, c, tile in metatile.tiles:
            tileImage = image.copy(self.tile_width * r, self.tile_height * c,
                                   self.tile_width, self.tile_height)
            self.writer.write_tile(tile, tileImage)

        # to stop thread sync issues
        with self.progressThreadLock:
            self.progress += 1
            self.feedback.setProgress(100 *
                                      (self.progress / self.totalMetatiles))

    def generate(self, writer, parameters, context, feedback):
        self.feedback = feedback
        feedback.setProgress(1)

        extent = self.parameterAsExtent(parameters, self.EXTENT, context)
        self.min_zoom = self.parameterAsInt(parameters, self.ZOOM_MIN, context)
        self.max_zoom = self.parameterAsInt(parameters, self.ZOOM_MAX, context)
        dpi = self.parameterAsInt(parameters, self.DPI, context)
        self.color = self.parameterAsColor(parameters, self.BACKGROUND_COLOR,
                                           context)
        self.tile_format = self.formats[self.parameterAsEnum(
            parameters, self.TILE_FORMAT, context)]
        self.quality = self.parameterAsInt(parameters, self.QUALITY, context)
        self.metatilesize = self.parameterAsInt(parameters, self.METATILESIZE,
                                                context)
        self.maxThreads = int(
            ProcessingConfig.getSetting(ProcessingConfig.MAX_THREADS))
        try:
            self.tile_width = self.parameterAsInt(parameters, self.TILE_WIDTH,
                                                  context)
            self.tile_height = self.parameterAsInt(parameters,
                                                   self.TILE_HEIGHT, context)
        except AttributeError:
            self.tile_width = 256
            self.tile_height = 256

        wgs_crs = QgsCoordinateReferenceSystem('EPSG:4326')
        dest_crs = QgsCoordinateReferenceSystem('EPSG:3857')

        project = context.project()
        self.src_to_wgs = QgsCoordinateTransform(project.crs(), wgs_crs,
                                                 context.transformContext())
        self.wgs_to_dest = QgsCoordinateTransform(wgs_crs, dest_crs,
                                                  context.transformContext())
        # without re-writing, we need a different settings for each thread to stop async errors
        # naming doesn't always line up, but the last number does
        self.settingsDictionary = {
            str(i): QgsMapSettings()
            for i in range(self.maxThreads)
        }
        for thread in self.settingsDictionary:
            self.settingsDictionary[thread].setOutputImageFormat(
                QImage.Format_ARGB32_Premultiplied)
            self.settingsDictionary[thread].setDestinationCrs(dest_crs)
            self.settingsDictionary[thread].setLayers(self.layers)
            self.settingsDictionary[thread].setOutputDpi(dpi)
            if self.tile_format == 'PNG':
                self.settingsDictionary[thread].setBackgroundColor(self.color)

            ## disable partial labels (they would be cut at the edge of tiles)
            labeling_engine_settings = self.settingsDictionary[
                thread].labelingEngineSettings()
            labeling_engine_settings.setFlag(
                QgsLabelingEngineSettings.UsePartialCandidates, False)
            self.settingsDictionary[thread].setLabelingEngineSettings(
                labeling_engine_settings)

            # Transfer context scopes to MapSettings
            self.settingsDictionary[thread].setExpressionContext(
                context.expressionContext())

        self.wgs_extent = self.src_to_wgs.transformBoundingBox(extent)
        self.wgs_extent = [
            self.wgs_extent.xMinimum(),
            self.wgs_extent.yMinimum(),
            self.wgs_extent.xMaximum(),
            self.wgs_extent.yMaximum()
        ]

        metatiles_by_zoom = {}
        self.totalMetatiles = 0
        allMetatiles = []
        for zoom in range(self.min_zoom, self.max_zoom + 1):
            metatiles = get_metatiles(self.wgs_extent, zoom, self.metatilesize)
            metatiles_by_zoom[zoom] = metatiles
            allMetatiles += metatiles
            self.totalMetatiles += len(metatiles)

        lab_buffer_px = 100
        self.progress = 0

        tile_params = {
            'format': self.tile_format,
            'quality': self.quality,
            'width': self.tile_width,
            'height': self.tile_height,
            'min_zoom': self.min_zoom,
            'max_zoom': self.max_zoom,
            'extent': self.wgs_extent,
        }
        writer.set_parameters(tile_params)
        self.writer = writer

        self.progressThreadLock = threading.Lock()
        if self.maxThreads > 1:
            feedback.pushConsoleInfo(
                self.tr('Using {max_threads} CPU Threads:').format(
                    max_threads=self.maxThreads))
            for zoom in range(self.min_zoom, self.max_zoom + 1):
                feedback.pushConsoleInfo(
                    self.tr('Generating tiles for zoom level: {zoom}').format(
                        zoom=zoom))
                with ThreadPoolExecutor(
                        max_workers=self.maxThreads) as threadPool:
                    threadPool.map(self.renderSingleMetatile,
                                   metatiles_by_zoom[zoom])
        else:
            feedback.pushConsoleInfo(self.tr('Using 1 CPU Thread:'))
            for zoom in range(self.min_zoom, self.max_zoom + 1):
                feedback.pushConsoleInfo(
                    self.tr('Generating tiles for zoom level: {zoom}').format(
                        zoom=zoom))
                for i, metatile in enumerate(metatiles_by_zoom[zoom]):
                    self.renderSingleMetatile(metatile)

        writer.close()

    def checkParameterValues(self, parameters, context):
        min_zoom = self.parameterAsInt(parameters, self.ZOOM_MIN, context)
        max_zoom = self.parameterAsInt(parameters, self.ZOOM_MAX, context)
        if max_zoom < min_zoom:
            return False, self.tr('Invalid zoom levels range.')

        return super().checkParameterValues(parameters, context)
Ejemplo n.º 32
0
 def updateCoordinates(self, id, pt, crs):
     self.origPt = pt
     self.origCrs = crs
     projCRS = self.canvas.mapSettings().destinationCrs()
     customCRS = self.customProjectionSelectionWidget.crs()
     if crs == epsg4326:
         pt4326 = pt
     else:
         trans = QgsCoordinateTransform(crs, epsg4326,
                                        QgsProject.instance())
         pt4326 = trans.transform(pt.x(), pt.y())
     if id != 0:  # WGS 84
         if self.inputXYOrder == 0:  # Y, X
             s = '{:.{prec}f}{}{:.{prec}f}'.format(
                 pt4326.y(),
                 settings.converterDelimiter,
                 pt4326.x(),
                 prec=settings.converter4326DDPrec)
         else:
             s = '{:.{prec}f}{}{:.{prec}f}'.format(
                 pt4326.x(),
                 settings.converterDelimiter,
                 pt4326.y(),
                 prec=settings.converter4326DDPrec)
         self.wgs84LineEdit.setText(s)
     if id != 1:  # Project CRS
         if crs == projCRS:
             newpt = pt
         else:
             trans = QgsCoordinateTransform(crs, projCRS,
                                            QgsProject.instance())
             newpt = trans.transform(pt.x(), pt.y())
         if projCRS == epsg4326:
             precision = settings.converter4326DDPrec
         else:
             precision = settings.converterDDPrec
         if self.inputXYOrder == 0:  # Y, X
             s = '{:.{prec}f}{}{:.{prec}f}'.format(
                 newpt.y(),
                 settings.converterDelimiter,
                 newpt.x(),
                 prec=precision)
         else:
             s = '{:.{prec}f}{}{:.{prec}f}'.format(
                 newpt.x(),
                 settings.converterDelimiter,
                 newpt.y(),
                 prec=precision)
         self.projLineEdit.setText(s)
     if id != 2:  # Custom CRS
         if crs == customCRS:
             newpt = pt
         else:
             trans = QgsCoordinateTransform(crs, customCRS,
                                            QgsProject.instance())
             newpt = trans.transform(pt.x(), pt.y())
         if customCRS == epsg4326:
             precision = settings.converter4326DDPrec
         else:
             precision = settings.converterDDPrec
         if self.inputXYOrder == 0:  # Y, X
             s = '{:.{prec}f}{}{:.{prec}f}'.format(
                 newpt.y(),
                 settings.converterDelimiter,
                 newpt.x(),
                 prec=precision)
         else:
             s = '{:.{prec}f}{}{:.{prec}f}'.format(
                 newpt.x(),
                 settings.converterDelimiter,
                 newpt.y(),
                 prec=precision)
         self.customLineEdit.setText(s)
     if id != 3:  # D M' S"
         s = formatDmsString(pt4326.y(), pt4326.x(), True,
                             settings.converterDmsPrec, self.inputXYOrder,
                             settings.converterDelimiter)
         self.dmsLineEdit.setText(s)
     if id != 4:  # DDMMSS
         s = formatDmsString(pt4326.y(), pt4326.x(), False,
                             settings.converterDmsPrec, self.inputXYOrder,
                             settings.converterDdmmssDelimiter)
         self.ddmmssLineEdit.setText(s)
     if id != 5:  # UTM
         s = latLon2UtmString(pt4326.y(), pt4326.x(),
                              settings.converterUtmPrec)
         self.utmLineEdit.setText(s)
     if id != 6:  # MGRS
         try:
             s = mgrs.toMgrs(pt4326.y(), pt4326.x())
         except Exception:
             s = 'Invalid'
         self.mgrsLineEdit.setText(s)
     if id != 7:  # Plus Codes
         try:
             s = olc.encode(pt4326.y(), pt4326.x(),
                            settings.converterPlusCodeLength)
         except Exception:
             s = 'Invalid'
         self.plusLineEdit.setText(s)
Ejemplo n.º 33
0
    def generate(self, writer, parameters, context, feedback):
        feedback.setProgress(1)

        extent = self.parameterAsExtent(parameters, self.EXTENT, context)
        self.min_zoom = self.parameterAsInt(parameters, self.ZOOM_MIN, context)
        self.max_zoom = self.parameterAsInt(parameters, self.ZOOM_MAX, context)
        dpi = self.parameterAsInt(parameters, self.DPI, context)
        self.tile_format = self.formats[self.parameterAsEnum(
            parameters, self.TILE_FORMAT, context)]
        quality = self.parameterAsInt(parameters, self.QUALITY, context)
        try:
            tile_width = self.parameterAsInt(parameters, self.TILE_WIDTH,
                                             context)
            tile_height = self.parameterAsInt(parameters, self.TILE_HEIGHT,
                                              context)
        except AttributeError:
            tile_width = 256
            tile_height = 256

        wgs_crs = QgsCoordinateReferenceSystem('EPSG:4326')
        dest_crs = QgsCoordinateReferenceSystem('EPSG:3857')

        project = context.project()
        src_to_wgs = QgsCoordinateTransform(project.crs(), wgs_crs,
                                            context.transformContext())
        wgs_to_dest = QgsCoordinateTransform(wgs_crs, dest_crs,
                                             context.transformContext())

        settings = QgsMapSettings()
        settings.setOutputImageFormat(QImage.Format_ARGB32_Premultiplied)
        settings.setDestinationCrs(dest_crs)
        settings.setLayers(self.layers)
        settings.setOutputDpi(dpi)
        if self.tile_format == 'PNG':
            settings.setBackgroundColor(QColor(Qt.transparent))

        # disable partial labels (they would be cut at the edge of tiles)
        labeling_engine_settings = settings.labelingEngineSettings()
        labeling_engine_settings.setFlag(
            QgsLabelingEngineSettings.UsePartialCandidates, False)
        settings.setLabelingEngineSettings(labeling_engine_settings)

        self.wgs_extent = src_to_wgs.transformBoundingBox(extent)
        self.wgs_extent = [
            self.wgs_extent.xMinimum(),
            self.wgs_extent.yMinimum(),
            self.wgs_extent.xMaximum(),
            self.wgs_extent.yMaximum()
        ]

        metatiles_by_zoom = {}
        metatiles_count = 0
        for zoom in range(self.min_zoom, self.max_zoom + 1):
            metatiles = get_metatiles(self.wgs_extent, zoom, 4)
            metatiles_by_zoom[zoom] = metatiles
            metatiles_count += len(metatiles)

        lab_buffer_px = 100
        progress = 0

        tile_params = {
            'format': self.tile_format,
            'quality': quality,
            'width': tile_width,
            'height': tile_height,
            'min_zoom': self.min_zoom,
            'max_zoom': self.max_zoom,
            'extent': self.wgs_extent,
        }
        writer.set_parameters(tile_params)

        for zoom in range(self.min_zoom, self.max_zoom + 1):
            feedback.pushConsoleInfo('Generating tiles for zoom level: %s' %
                                     zoom)

            for i, metatile in enumerate(metatiles_by_zoom[zoom]):
                if feedback.isCanceled():
                    break

                size = QSize(tile_width * metatile.rows(),
                             tile_height * metatile.columns())
                extent = QgsRectangle(*metatile.extent())
                settings.setExtent(wgs_to_dest.transformBoundingBox(extent))
                settings.setOutputSize(size)

                image = QImage(size, QImage.Format_ARGB32_Premultiplied)
                image.fill(Qt.transparent)
                dpm = settings.outputDpi() / 25.4 * 1000
                image.setDotsPerMeterX(dpm)
                image.setDotsPerMeterY(dpm)
                painter = QPainter(image)
                job = QgsMapRendererCustomPainterJob(settings, painter)
                job.renderSynchronously()
                painter.end()

                # For analysing metatiles (labels, etc.)
                # metatile_dir = os.path.join(output_dir, str(zoom))
                # os.makedirs(metatile_dir, exist_ok=True)
                # image.save(os.path.join(metatile_dir, 'metatile_%s.png' % i))

                for r, c, tile in metatile.tiles:
                    tile_img = image.copy(tile_width * r, tile_height * c,
                                          tile_width, tile_height)
                    writer.write_tile(tile, tile_img)

                progress += 1
                feedback.setProgress(100 * (progress / metatiles_count))

        writer.close()
    def formatCoord(self, pt, delimiter):
        '''Format the coordinate string according to the settings from
        the settings dialog.'''
        if self.settings.captureProjIsWgs84():  # ProjectionTypeWgs84
            # Make sure the coordinate is transformed to EPSG:4326
            canvasCRS = self.canvas.mapSettings().destinationCrs()
            if canvasCRS == epsg4326:
                pt4326 = pt
            else:
                transform = QgsCoordinateTransform(canvasCRS, epsg4326, QgsProject.instance())
                pt4326 = transform.transform(pt.x(), pt.y())
            lat = pt4326.y()
            lon = pt4326.x()
            if self.settings.wgs84NumberFormat == self.settings.Wgs84TypeDMS:  # DMS
                msg = formatDmsString(lat, lon, True, self.settings.dmsPrecision, self.settings.coordOrder, delimiter)
            elif self.settings.wgs84NumberFormat == self.settings.Wgs84TypeDDMMSS:  # DDMMSS
                msg = formatDmsString(lat, lon, False, self.settings.dmsPrecision, self.settings.coordOrder, delimiter)
            elif self.settings.wgs84NumberFormat == self.settings.Wgs84TypeWKT:  # WKT
                msg = 'POINT({:.{prec}f} {:.{prec}f})'.format(pt4326.x(), pt4326.y(), prec=self.settings.decimalDigits)
            elif self.settings.wgs84NumberFormat == self.settings.Wgs84TypeGeoJSON:  # GeoJSON
                msg = '{{"type": "Point","coordinates": [{:.{prec}f},{:.{prec}f}]}}'.format(pt4326.x(), pt4326.y(), prec=self.settings.decimalDigits)
            else:  # decimal degrees
                if self.settings.coordOrder == self.settings.OrderYX:
                    msg = '{:.{prec}f}{}{:.{prec}f}'.format(pt4326.y(), delimiter, pt4326.x(), prec=self.settings.decimalDigits)
                else:
                    msg = '{:.{prec}f}{}{:.{prec}f}'.format(pt4326.x(), delimiter, pt4326.y(), prec=self.settings.decimalDigits)
        elif self.settings.captureProjIsProjectCRS():
            # Projection in the project CRS
            if self.settings.otherNumberFormat == 0:  # Numerical
                if self.settings.coordOrder == self.settings.OrderYX:
                    msg = '{:.{prec}f}{}{:.{prec}f}'.format(pt.y(), delimiter, pt.x(), prec=self.settings.decimalDigits)
                else:
                    msg = '{:.{prec}f}{}{:.{prec}f}'.format(pt.x(), delimiter, pt.y(), prec=self.settings.decimalDigits)
            else:
                msg = 'POINT({:.{prec}f} {:.{prec}f})'.format(pt.x(), pt.y(), prec=self.settings.decimalDigits)
        elif self.settings.captureProjIsCustomCRS():
            # Projection is a custom CRS
            canvasCRS = self.canvas.mapSettings().destinationCrs()
            customCRS = self.settings.captureCustomCRS()
            transform = QgsCoordinateTransform(canvasCRS, customCRS, QgsProject.instance())
            pt = transform.transform(pt.x(), pt.y())
            if self.settings.otherNumberFormat == 0:  # Numerical
                if self.settings.coordOrder == self.settings.OrderYX:
                    msg = '{:.{prec}f}{}{:.{prec}f}'.format(pt.y(), delimiter, pt.x(), prec=self.settings.decimalDigits)
                else:
                    msg = '{:.{prec}f}{}{:.{prec}f}'.format(pt.x(), delimiter, pt.y(), prec=self.settings.decimalDigits)
            else:
                msg = 'POINT({:.{prec}f} {:.{prec}f})'.format(pt.x(), pt.y(), prec=self.settings.decimalDigits)
        elif self.settings.captureProjIsMGRS():
            # Make sure the coordinate is transformed to EPSG:4326
            canvasCRS = self.canvas.mapSettings().destinationCrs()
            if canvasCRS == epsg4326:
                pt4326 = pt
            else:
                transform = QgsCoordinateTransform(canvasCRS, epsg4326, QgsProject.instance())
                pt4326 = transform.transform(pt.x(), pt.y())
            try:
                msg = mgrs.toMgrs(pt4326.y(), pt4326.x())
            except Exception:
                msg = None
        elif self.settings.captureProjIsPlusCodes():
            # Make sure the coordinate is transformed to EPSG:4326
            canvasCRS = self.canvas.mapSettings().destinationCrs()
            if canvasCRS == epsg4326:
                pt4326 = pt
            else:
                transform = QgsCoordinateTransform(canvasCRS, epsg4326, QgsProject.instance())
                pt4326 = transform.transform(pt.x(), pt.y())
            try:
                msg = olc.encode(pt4326.y(), pt4326.x(), self.settings.plusCodesLength)
            except Exception:
                msg = None
        elif self.settings.captureProjIsUTM():
            # Make sure the coordinate is transformed to EPSG:4326
            canvasCRS = self.canvas.mapSettings().destinationCrs()
            if canvasCRS == epsg4326:
                pt4326 = pt
            else:
                transform = QgsCoordinateTransform(canvasCRS, epsg4326, QgsProject.instance())
                pt4326 = transform.transform(pt.x(), pt.y())
            msg = latLon2UtmString(pt4326.y(), pt4326.x(), self.settings.dmsPrecision)
            if msg == '':
                msg = None

        msg = '{}{}{}'.format(self.settings.capturePrefix, msg, self.settings.captureSuffix)
        return msg
Ejemplo n.º 35
0
    def processAlgorithm(self, parameters, context, feedback):
        """
        Here is where the processing itself takes place.
        """

        # Retrieve the feature source and sink. The 'dest_id' variable is used
        # to uniquely identify the feature sink, and must be included in the
        # dictionary returned by the processAlgorithm function.
        reseau = self.parameterAsVectorLayer(parameters, self.RESEAU, context)
        sens = self.parameterAsFields(parameters, self.SENS, context)
        ident = self.parameterAsFields(parameters, self.IDENT, context)
        prefixe = self.parameterAsString(parameters, self.PREFIXE, context)
        if len(sens) > 0:
            sens = sens[0]

        ##CEREMA=group
        ##reseau=vector line
        ##prefixe=optional string
        ##sens= field reseau
        ##fichier_noeuds=output vector
        layer = reseau
        nom_champs = []
        for i in layer.fields():
            nom_champs.append(i.name())
        if ("i" not in nom_champs):
            layer.dataProvider().addAttributes(
                [QgsField("i", QVariant.String, len=15)])
        if ("j" not in nom_champs):
            layer.dataProvider().addAttributes(
                [QgsField("j", QVariant.String, len=15)])
        if ("ij" not in nom_champs):
            layer.dataProvider().addAttributes(
                [QgsField("ij", QVariant.String, len=31)])
        layer.updateFields()
        layer.commitChanges()
        ida = layer.fields().indexFromName("i")
        idb = layer.fields().indexFromName("j")
        idij = layer.fields().indexFromName("ij")
        lines = layer.getFeatures()
        noeuds = {}
        #nom_fichier=fichier_noeuds
        champs = QgsFields()
        champs.append(QgsField("num", QVariant.String, len=35))
        champs.append(QgsField("nb", QVariant.Int))
        (table_noeuds, dest_id) = self.parameterAsSink(parameters, self.NOEUDS,
                                                       context, champs,
                                                       QgsWkbTypes.Point,
                                                       layer.sourceCrs())
        src = QgsCoordinateReferenceSystem(layer.crs())
        dest = QgsCoordinateReferenceSystem("EPSG:4326")
        xtr = QgsCoordinateTransform(src, dest, QgsProject.instance())
        for ligne in lines:
            if len(sens) == 0:
                test_sens = '1'
            else:
                if ligne[sens] == '1':
                    test_sens = '1'
                else:
                    test_sens = '0'
            gligne = ligne.geometry()
            if test_sens == '1':
                if gligne.wkbType() == QgsWkbTypes.MultiLineString:
                    g = gligne.asMultiPolyline()
                    na = g[0][0]
                    liba = str(
                        int(xtr.transform(na)[0] * 1e6 +
                            180 * 1e6)).zfill(9) + str(
                                int(xtr.transform(na)[1] * 1e6 +
                                    180 * 1e6)).zfill(9)
                    nb = g[-1][-1]
                    libb = str(
                        int(xtr.transform(nb)[0] * 1e6 +
                            180 * 1e6)).zfill(9) + str(
                                int(xtr.transform(nb)[1] * 1e6 +
                                    180 * 1e6)).zfill(9)

                elif gligne.wkbType() == QgsWkbTypes.LineString:
                    g = gligne.AsPolyline()
                    na = g[0]
                    liba = str(
                        int(xtr.transform(na)[0] * 1e6 +
                            180 * 1e6)).zfill(9) + str(
                                int(xtr.transform(na)[1] * 1e6 +
                                    180 * 1e6)).zfill(9)
                    nb = g[-1]
                    libb = str(
                        int(xtr.transform(nb)[0] * 1e6 +
                            180 * 1e6)).zfill(9) + str(
                                int(xtr.transform(nb)[1] * 1e6 +
                                    180 * 1e6)).zfill(9)
                if (na not in noeuds):
                    noeuds[na] = (prefixe + liba, 1)
                else:
                    noeuds[na] = (prefixe + liba, noeuds[na][1] + 1)
                if (nb not in noeuds):
                    noeuds[nb] = (prefixe + libb, 1)
                else:
                    noeuds[nb] = (prefixe + libb, noeuds[nb][1] + 1)
        #outs=open("c:/temp/noeuds.txt","w")
        for i, n in enumerate(noeuds):
            node = QgsFeature()
            node.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(n[0], n[1])))
            #node.setAttributes([noeuds[n]])
            #feedback.setProgressText(unicode(i)+" "+unicode(ident[0])+" "+unicode(ident[0]=='0'))
            if ident[0] == '0':
                noeuds[n] = (prefixe + unicode(i), noeuds[n][1])
                #feedback.setProgressText(unicode(noeuds[n][0]))
            node.setAttributes([noeuds[n][0], noeuds[n][1]])
            table_noeuds.addFeature(node)
        #outs.write(str(n)+";"+str(noeuds[n])+"\n")
        del table_noeuds
        #outs.close()
        lines = layer.getFeatures()
        layer.startEditing()
        layer.beginEditCommand(
            QCoreApplication.translate("Building graph", "Building graph"))
        for ligne in lines:
            if len(sens) == 0:
                test_sens = '1'
            else:
                if ligne[sens] == '1':
                    test_sens = '1'
                else:
                    test_sens = '0'
            if test_sens == '1':
                gligne = ligne.geometry()
                if gligne.wkbType() == QgsWkbTypes.MultiLineString:

                    g = gligne.asMultiPolyline()

                    na = g[0][0]
                    nb = g[-1][-1]
                    liba = str(
                        int(xtr.transform(na)[0] * 1e6 +
                            180 * 1e6)).zfill(9) + str(
                                int(xtr.transform(na)[1] * 1e6 +
                                    180 * 1e6)).zfill(9)
                    libb = str(
                        int(xtr.transform(nb)[0] * 1e6 +
                            180 * 1e6)).zfill(9) + str(
                                int(xtr.transform(nb)[1] * 1e6 +
                                    180 * 1e6)).zfill(9)
                elif gligne.wkbType() == QgsWkbTypes.LineString:

                    g = gligne.asPolyline()
                    na = g[0]
                    nb = g[-1]
                    liba = str(
                        int(xtr.transform(na)[0] * 1e6 +
                            180 * 1e6)).zfill(9) + str(
                                int(xtr.transform(na)[1] * 1e6 +
                                    180 * 1e6)).zfill(9)

                    libb = str(
                        int(xtr.transform(nb)[0] * 1e6 +
                            180 * 1e6)).zfill(9) + str(
                                int(xtr.transform(nb)[1] * 1e6 +
                                    180 * 1e6)).zfill(9)

                id = ligne.id()
                #valid={ida : noeuds[na], idb: noeuds[nb]}
                layer.changeAttributeValue(id, ida, unicode(noeuds[na][0]))
                layer.changeAttributeValue(id, idb, unicode(noeuds[nb][0]))
                layer.changeAttributeValue(
                    id, idij, unicode(noeuds[na][0] + "-" + noeuds[nb][0]))
        layer.commitChanges()
        layer.endEditCommand()
        return {self.NOEUDS: dest_id}
    def processAlgorithm(self, parameters, context, feedback):
        source = self.parameterAsSource(parameters, self.INPUT, context)
        if source is None:
            raise QgsProcessingException(self.invalidSourceError(parameters, self.INPUT))

        method = self.parameterAsEnum(parameters, self.METHOD, context)

        wkb_type = source.wkbType()

        if QgsWkbTypes.geometryType(wkb_type) != QgsWkbTypes.PolygonGeometry:
            # TODO IMPROVE FEEDBACK
            feedback.reportError('The layer geometry type is different from a polygon')
            return {}

        fields = source.fields()

        new_fields = QgsFields()
        new_fields.append(QgsField('perimeter', QVariant.Double))
        new_fields.append(QgsField('area', QVariant.Double))

        fields = QgsProcessingUtils.combineFields(fields, new_fields)
        (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context,
                                               fields, wkb_type, source.sourceCrs())
        if sink is None:
            raise QgsProcessingException(self.invalidSinkError(parameters, self.OUTPUT))

        coordTransform = None

        # Calculate with:
        # 0 - layer CRS
        # 1 - project CRS
        # 2 - ellipsoidal

        self.distance_area = QgsDistanceArea()
        if method == 2:
            self.distance_area.setSourceCrs(source.sourceCrs(), context.transformContext())
            self.distance_area.setEllipsoid(context.ellipsoid())
        elif method == 1:
            if not context.project():
                raise QgsProcessingException(self.tr('No project is available in this context'))
            coordTransform = QgsCoordinateTransform(source.sourceCrs(), context.project().crs(), context.project())

        features = source.getFeatures()
        total = 100.0 / source.featureCount() if source.featureCount() else 0
        for current, f in enumerate(features):
            if feedback.isCanceled():
                break

            outFeat = f
            attrs = f.attributes()
            inGeom = f.geometry()
            if inGeom:
                if coordTransform is not None:
                    inGeom.transform(coordTransform)

                attrs.extend(self.polygon_attributes(inGeom))

            # ensure consistent count of attributes - otherwise null
            # geometry features will have incorrect attribute length
            # and provider may reject them
            if len(attrs) < len(fields):
                attrs += [NULL] * (len(fields) - len(attrs))

            outFeat.setAttributes(attrs)
            sink.addFeature(outFeat, QgsFeatureSink.FastInsert)

            feedback.setProgress(int(current * total))

        return {self.OUTPUT: dest_id}
Ejemplo n.º 37
0
    def processAlgorithm(self, parameters, context, feedback):
        source = self.parameterAsSource(parameters, self.INPUT, context)
        if source is None:
            raise QgsProcessingException(
                self.invalidSourceError(parameters, self.INPUT))

        extent = self.parameterAsExtent(parameters, self.TARGET_AREA, context)
        target_crs = self.parameterAsCrs(parameters, self.TARGET_AREA_CRS,
                                         context)

        target_geom = QgsGeometry.fromRect(extent)

        fields = QgsFields()
        fields.append(QgsField('auth_id', QVariant.String, '', 20))

        (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT,
                                               context, fields,
                                               QgsWkbTypes.NoGeometry,
                                               QgsCoordinateReferenceSystem())
        if sink is None:
            raise QgsProcessingException(
                self.invalidSinkError(parameters, self.OUTPUT))

        # make intersection tests nice and fast
        engine = QgsGeometry.createGeometryEngine(target_geom.constGet())
        engine.prepareGeometry()

        layer_bounds = QgsGeometry.fromRect(source.sourceExtent())

        crses_to_check = QgsCoordinateReferenceSystem.validSrsIds()
        total = 100.0 / len(crses_to_check)

        found_results = 0

        transform_context = QgsCoordinateTransformContext()
        for current, srs_id in enumerate(crses_to_check):
            if feedback.isCanceled():
                break

            candidate_crs = QgsCoordinateReferenceSystem.fromSrsId(srs_id)
            if not candidate_crs.isValid():
                continue

            transform_candidate = QgsCoordinateTransform(
                candidate_crs, target_crs, transform_context)
            transformed_bounds = QgsGeometry(layer_bounds)
            try:
                if not transformed_bounds.transform(transform_candidate) == 0:
                    continue
            except:
                continue

            try:
                if engine.intersects(transformed_bounds.constGet()):
                    feedback.pushInfo(
                        self.tr('Found candidate CRS: {}').format(
                            candidate_crs.authid()))
                    f = QgsFeature(fields)
                    f.setAttributes([candidate_crs.authid()])
                    sink.addFeature(f, QgsFeatureSink.FastInsert)
                    found_results += 1
            except:
                continue

            feedback.setProgress(int(current * total))

        if found_results == 0:
            feedback.reportError(self.tr('No matching projections found'))

        return {self.OUTPUT: dest_id}
Ejemplo n.º 38
0
    def testReprojectionErrorsWhileRendering(self):
        # WKT of a polygon which causes reprojection errors while rendering
        # (apologies for the ridiculously complex wkt, but I can't find a way to reproduce with simplifiction)
        wkt = 'MultiPolygon (((16.93392988400009358 42.77094147300012139, 16.88493899800005238 42.72939687700012712, ' \
              '16.80298912900011032 42.76349518400014915, 16.85816491000014139 42.78400299700011544, ' \
              '16.93392988400009358 42.77094147300012139)),((17.38200931100010393 42.79783763200002511, ' \
              '17.65894616000011297 42.74298737200008702, 17.74887129000009622 42.69456614800010641, ' \
              '17.32374108200008322 42.79083893400003547, 17.38200931100010393 42.79783763200002511)),' \
              '((16.768565300000148 42.97223541900014254, 17.03207441500009622 42.98261139500014849, ' \
              '17.13184655000009116 42.96954987200014386, 17.20020592500009116 42.92177969000012183, ' \
              '16.85141035200010151 42.90070221600008438, 16.65544681100004709 42.92625560099999404, ' \
              '16.70679772200014668 42.96954987200014386, 16.63168379000003938 42.98261139500014849, ' \
              '16.768565300000148 42.97223541900014254)),((17.05567467500011958 43.02895742400001211, ' \
              '17.24024498800011429 43.02277252800014651, 17.74146569100011561 42.83926015800001608, ' \
              '17.70736738400009358 42.88703034100014122, 17.65334906206413734 42.8909283361407887, ' \
              '17.70158573400010482 42.91950022500007833, 17.81175988700005064 42.909862570000044, ' \
              '17.85847538200005147 42.81697418200012351, 18.22413781700009849 42.62807098500009317, ' \
              '18.43735477700010961 42.55921213800017711, 18.4371480710000526 42.4934022020000981, ' \
              '18.49642988400009358 42.41632721600008438, 18.23894290500010129 42.55906810100005089, ' \
              '18.21753991000014139 42.6201032570001388, 18.07601972700010151 42.65131256700003348, ' \
              '18.0432235040000819 42.70205312700007028, 17.90162194100014403 42.75189850500014188, ' \
              '17.8928328790000819 42.79083893400003547, 17.72095787900005348 42.8262393250000315, ' \
              '17.7618921230000808 42.77871328300012976, 17.74870853000004445 42.77204010600017625, ' \
              '17.21387780000011958 42.98261139500014849, 17.04615319100011561 42.9950625670000619, ' \
              '17.00163821700004974 43.05149974200010377, 17.05567467500011958 43.02895742400001211)),' \
              '((16.19467207100007045 43.07440827000000638, 16.254893425000148 43.06854889500006323, ' \
              '16.08716881600014403 43.01146067900008063, 16.04883873800011429 43.06517161700004692, ' \
              '16.19467207100007045 43.07440827000000638)),((16.56275475400011032 43.22898997600010773, ' \
              '16.65951582100009887 43.21596914300012315, 16.72771243600001867 43.16461823100003414, ' \
              '17.19336998800014271 43.12726471600016964, 16.67017662900013875 43.12547435099999404, ' \
              '16.37159264400014536 43.19550202000006323, 16.49642988400006516 43.21808502800014651, ' \
              '16.58326256600014403 43.18866608300005794, 16.52051842500006273 43.22898997600010773, ' \
              '16.56275475400011032 43.22898997600010773)),((16.80681399800010922 43.34247467700005529, ' \
              '16.89234459700011826 43.31220123900006058, 16.84620201900008851 43.27338288000005662, ' \
              '16.62826582100012729 43.26373932500008834, 16.50074303500014139 43.28424713700003679, ' \
              '16.42188561300008587 43.31757233300011478, 16.40577233200011165 43.33270905200011214, ' \
              '16.45346113400009358 43.35317617400009738, 16.42628014400008851 43.39411041900011412, ' \
              '16.44703209700008983 43.39484284100014122, 16.80681399800010922 43.34247467700005529)),' \
              '((16.29818769600012729 43.40363190300011809, 16.30274498800008587 43.38727448100009099, ' \
              '16.39144941500012465 43.34638092700005529, 16.348643425000148 43.33869049700003018, ' \
              '16.20045006600014403 43.40704987200003018, 16.29818769600012729 43.40363190300011809)),' \
              '((16.33415774800010922 43.50153229400014254, 16.3752547540000819 43.49017975500008504, ' \
              '16.21143639400008851 43.49005768400009231, 16.26441491000014139 43.51288483300011478, ' \
              '16.33415774800010922 43.50153229400014254)),((15.67888431100004709 43.64801666900014254, ' \
              '15.74040774800010922 43.62750885600009099, 15.67204837300002396 43.63743724200010377, ' \
              '15.60377037900013875 43.67470937700007028, 15.67888431100004709 43.64801666900014254)),' \
              '((15.36736087300005238 43.79010651200015047, 15.39568118600007551 43.7724063170000619, ' \
              '15.22779381600014403 43.87445709800014981, 15.24073326900014536 43.88076406500009341, ' \
              '15.36736087300005238 43.79010651200015047)),((15.44271894600009887 43.89907461100013109, ' \
              '15.35865319100014403 43.91937897300014981, 15.26124108200011165 44.01105377800003282, ' \
              '15.38404381600008719 43.9701602230000077, 15.44271894600009887 43.89907461100013109)),' \
              '((15.22575931100010393 44.06622955900014915, 15.25440514400008851 44.01788971600014122, ' \
              '15.12183678500014139 44.09223053600005926, 15.06251061300008587 44.16193268400012073, ' \
              '15.22575931100010393 44.06622955900014915)),((14.83545983200014007 44.15102773600013109, ' \
              '14.85726972700010151 44.15204498900000374, 14.86915123800014271 44.14052969000006499, ' \
              '14.83521569100008719 44.14166901200009363, 14.81983483200014007 44.15302155199999845, ' \
              '14.82243899800005238 44.16868724200004692, 14.83545983200014007 44.15102773600013109)),' \
              '((14.98511803500011297 44.09096914300012315, 15.21680748800008587 43.91278717700008372, ' \
              '15.13331139400011693 43.92121002800003282, 15.19450931100004709 43.87262604400017096, ' \
              '15.10661868600007551 43.92544179900015422, 14.84961998800014271 44.17560455900014915, ' \
              '14.98511803500011297 44.09096914300012315)),((14.765961134000122 44.26504140800015819, ' \
              '14.74854576900014536 44.26166413000014188, 14.73959394600012729 44.28017812700015554, ' \
              '14.79167728000007287 44.27252838700003679, 14.765961134000122 44.26504140800015819)),' \
              '((14.66138756600011561 44.30866120000014519, 14.6407983730000808 44.31183502800003282, ' \
              '14.59506269600007045 44.34711334800006455, 14.643565300000148 44.32575104400011412, ' \
              '14.66138756600011561 44.30866120000014519)),((14.81120853000004445 44.35004303600000242, ' \
              '14.75619550900009358 44.36399974200004692, 14.76343834700008983 44.41535065300017493, ' \
              '14.80323326900008851 44.40550364800004957, 14.81120853000004445 44.35004303600000242)),' \
              '((14.27116946700002131 44.61253489800004957, 14.23259524800005238 44.62604401200012205, ' \
              '14.2657983730000808 44.67951080900003547, 14.28044681100007551 44.67755768400009231, ' \
              '14.27116946700002131 44.61253489800004957)),((14.84522545700008322 44.60053131700011875, ' \
              '14.93824303500014139 44.59414297100001079, 15.07553144600007045 44.48407623900006058, ' \
              '14.91114342500011958 44.54547760600014783, 15.04802493600004709 44.43943919500001982, ' \
              '15.09669030000009116 44.41518789300000947, 15.04151451900014536 44.47662995000008834, ' \
              '15.25440514400008851 44.34003327000000638, 15.165049675000148 44.36737702000006323, ' \
              '15.22022545700008322 44.3127302100001117, 15.13086998800008587 44.33258698100003414, ' \
              '15.17237389400014536 44.29913971600016964, 15.12875410200007309 44.31199778900018771, ' \
              '15.08920332100009887 44.37421295800000109, 15.11719811300014271 44.38719310099999404, ' \
              '15.04900149800010922 44.39468008000015686, 14.89747155000009116 44.49091217699999845, ' \
              '14.91863040500010129 44.50454336100013109, 14.87696373800011429 44.55975983300005794, ' \
              '14.73365319100008719 44.70319245000014519, 14.84522545700008322 44.60053131700011875)),' \
              '((14.41000410200010151 44.60097890800001608, 14.52662194100011561 44.50372955900012073, ' \
              '14.53435306100010393 44.48407623900006058, 14.42261803500008455 44.57387929900009738, ' \
              '14.36304772200014668 44.57343170800000109, 14.38257897200014668 44.60325755399999537, ' \
              '14.33578535200007309 44.71678294500010509, 14.39747155000009116 44.6856143250000315, ' \
              '14.41000410200010151 44.60097890800001608)),((14.75326582100007045 44.84585195500012844, ' \
              '14.74048912900011032 44.82050202000000638, 14.82243899800005238 44.77142975500005662, ' \
              '14.84961998800014271 44.70319245000014519, 14.65788821700004974 44.79877350500014188, ' \
              '14.7268172540000819 44.79877350500014188, 14.6858016290000819 44.8471540390000456, ' \
              '14.75326582100007045 44.84585195500012844)),((14.47103925900006516 44.95392487200003018, ' \
              '14.45191491000008455 44.79877350500014188, 14.47217858200011165 44.7079531920000619, ' \
              '14.53435306100010393 44.63426341400010244, 14.51335696700007816 44.618841864000089, ' \
              '14.42790774800005238 44.65656159100014122, 14.29420006600008719 44.9086367860001161, ' \
              '14.30152428500011297 44.94342682500014519, 14.38738040500004445 44.90900299700003018, ' \
              '14.39031009200004974 44.96039459800012139, 14.41138756600008719 44.95636627800014651, ' \
              '14.27849368600004709 45.1133487000000315, 14.29957116000014139 45.16233958499999801, ' \
              '14.35621178500014139 45.16925690300008966, 14.387705925000148 45.03904857000013351, ' \
              '14.47103925900006516 44.95392487200003018)),((14.56332441500012465 45.24974192900008063, ' \
              '14.62378991000011297 45.17548248900006058, 14.59742272200011826 45.16644928600005926, ' \
              '14.66529381600011561 45.16181061400011743, 14.66529381600011561 45.08734772300006455, ' \
              '14.74048912900011032 45.07306549700014386, 14.81495201900008851 44.97748444200009033, ' \
              '14.70639082100009887 44.9467227230000077, 14.62891686300014271 44.97817617400004053, ' \
              '14.62086022200008983 45.04559967700011214, 14.61695397200008983 45.02464427300007799, ' \
              '14.51050866000014139 45.03217194200011875, 14.43873131600014403 45.07050202000006323, ' \
              '14.4670516290000819 45.12409088700015047, 14.53012129000009622 45.13483307500014519, ' \
              '14.53435306100010393 45.23753489800002114, 14.56332441500012465 45.24974192900008063)),' \
              '((16.36947066200013978 46.54057118800012915, 16.63767134600004738 46.47447703100009164, ' \
              '16.75508020000012266 46.38187286400001597, 16.83765913900006694 46.38187286400001597, ' \
              '16.88923221800007468 46.29216257800014489, 17.05294315600005461 46.15346303300005104, ' \
              '17.20859257000006437 46.11656606000003933, 17.27587528500004055 46.01202463800002818, ' \
              '17.31680301900004793 45.99765859000002877, 17.29013798000011093 45.98463612900009423, ' \
              '17.40620324700006449 45.94365671800015605, 17.59110152100009827 45.93621531200012953, ' \
              '17.65652388500006964 45.84541982000014571, 17.80917606600013414 45.81441396100005647, ' \
              '17.85806197100004056 45.77172922800004073, 18.21121870900006456 45.78537180600012846, ' \
              '18.40438521300006869 45.74180857400001798, 18.57347049900010916 45.81668772400014689, ' \
              '18.6556360270001278 45.90758656800015558, 18.7755253500000947 45.88283355700004051, ' \
              '18.90130578600007993 45.93120269800006383, 18.87288374800004931 45.89523590100002082, ' \
              '18.90699019400011593 45.86795074500018643, 18.85531376100007606 45.85735707600009903, ' \
              '18.84497847500006174 45.8157058720000947, 18.96848514800012708 45.66873809800016204, ' \
              '18.90357954900008508 45.57308502200005762, 18.94171675700005153 45.53892689999999277, ' \
              '19.01809452300011571 45.56740061400002162, 19.10625451700005328 45.51164174500017623, ' \
              '19.00961958800010621 45.49867095900005154, 19.00300500400010151 45.45536611000007099, ' \
              '19.03742150900006891 45.42229319300010104, 18.97592655400006834 45.39495636000008005, ' \
              '19.09199182100007874 45.34999786400005917, 19.12475467900009107 45.29811472600006539, ' \
              '19.36308638500014467 45.24824696900010679, 19.40783817500010855 45.20313344400013023, ' \
              '19.39068160000005037 45.16933705700016333, 19.22593713300008744 45.16194732700016345, ' \
              '19.12186079900010327 45.195795390000157, 19.13767378700009658 45.14603098600004216, ' \
              '19.04486291500009543 45.13724599300006446, 19.08227665200013234 45.08494944300004192, ' \
              '19.0872375890000967 44.97710072800013847, 19.13167932100006396 44.95317454000003465, ' \
              '19.06667036900009293 44.90568389900012392, 18.99142948400006503 44.9149339800001286, ' \
              '19.01582076000008215 44.86563466400004074, 18.88962691200009658 44.86119049100013001, ' \
              '18.78338016700013213 44.91374542300012251, 18.79175174900009893 45.00154368100008639, ' \
              '18.73831831900008638 45.0159097290000858, 18.68405806500004473 45.08479441400000098, ' \
              '18.64871138500012648 45.06267689999999959, 18.61667199700013953 45.09766184500010411, ' \
              '18.54959598800010667 45.09476796500011631, 18.51703983500007666 45.05585561200003042, ' \
              '18.23788374800011525 45.15745147700012296, 18.15365116400005263 45.0975584930001645, ' \
              '18.00347945100011771 45.1493382780000303, 17.83573775200005684 45.0644338990000648, ' \
              '17.68473921700012852 45.1639627080000281, 17.48185754400009273 45.11440500900012296, ' \
              '17.49622359200009214 45.1416901650001563, 17.44775109900012922 45.13430043600014585, ' \
              '17.44330692500011537 45.16205068000009248, 17.38243208800008688 45.1396231090000839, ' \
              '17.26895064300006766 45.18954254200015441, 17.24548954300007608 45.15538442000017483, ' \
              '17.18709517400012032 45.14856313100001728, 17.0363033440001459 45.23047027600007652, ' \
              '17.00829471800011561 45.21615590500009318, 17.00829471800011561 45.24416453100009505, ' \
              '16.94731652900014751 45.23568959600000028, 16.9243721930001243 45.28452382500016427, ' \
              '16.81171757000004163 45.18122263700009, 16.52894413300009546 45.22225372400005483, ' \
              '16.38921106000003647 45.11683380099999852, 16.31624393700010955 45.00123362300008978, ' \
              '16.12152714000009723 45.09616322900008356, 16.02044803900011516 45.213933818000001, ' \
              '15.79234826700013627 45.18980092400012438, 15.76361617000014803 44.97555043600003444, ' \
              '15.7308533120001357 44.92723297200008403, 15.77343469200010873 44.84501576800015243, ' \
              '15.71607385200013596 44.80320953400008932, 15.72847619600008784 44.76910308800002269, ' \
              '15.80568078600006743 44.69665273000013883, 15.88877648900006534 44.72424794500012979, ' \
              '15.96897831200004703 44.63924021400013942, 16.02830285600006732 44.62471913700009907, ' \
              '16.04473596200011798 44.58937245700018082, 16.00608199000004106 44.54100331600012908, ' \
              '16.11646285000011858 44.52146962500013672, 16.15966434700004584 44.41610138000002905, ' \
              '16.13827030500004867 44.37760243800015303, 16.20286584400008678 44.35977406800010669, ' \
              '16.18756962000011868 44.28241444999999032, 16.21578495300011014 44.20815541600011045, ' \
              '16.32688928200008149 44.08237498000012522, 16.50103885900011846 43.99271637000008184, ' \
              '16.67859908100004418 43.8406843060001421, 16.71260217300007866 43.77151540100005889, ' \
              '17.03051558500007445 43.54847991900005866, 17.27050093600007585 43.46321380700000248, ' \
              '17.28993127500007176 43.3034302780000786, 17.44206669100009321 43.15243174300015028, ' \
              '17.6284119050001209 43.04657257100008394, 17.66272505700004558 42.96569895500012137, ' \
              '17.63450972400008254 42.950402731000068, 17.51563561300008587 42.95888906500012183, ' \
              '17.47087649800005238 43.01341380400010905, 17.50196373800014271 43.03099192900005221, ' \
              '17.43360436300014271 43.01740143400009231, 17.46021569100011561 43.03099192900005221, ' \
              '17.42611738400009358 43.06517161700004692, 17.4045516290000819 43.05149974200010377, ' \
              '17.31625410200012993 43.12726471600016964, 17.11394290500004445 43.21320221600008438, ' \
              '16.88062584700011826 43.40595123900006058, 16.62582441500009622 43.44904205900009231, ' \
              '16.52466881600011561 43.51080963700009363, 16.39144941500012465 43.51080963700009363, ' \
              '16.47339928500008455 43.5381533870001789, 16.43384850400013875 43.54975006700000506, ' \
              '16.11768639400008851 43.52448151200003679, 16.17237389400014536 43.4896914730000077, ' \
              '16.11312910200004467 43.47890859600009605, 15.95948326900011693 43.50397370000008834, ' \
              '15.987315300000148 43.54490794500010509, 15.92530358200011165 43.55857982000004824, ' \
              '15.91895592500009116 43.62872955900012073, 15.96631920700011165 43.64118073100003414, ' \
              '15.90479576900014536 43.64801666900014254, 15.95297285200010151 43.65086497599999404, ' \
              '15.95045006600008719 43.68854401200015047, 15.70630944100008719 43.76341380400005221, ' \
              '15.6174422540000819 43.82550690300017493, 15.66309655000009116 43.81297435099999404, ' \
              '15.67888431100004709 43.81928131700011875, 15.45508873800014271 43.92804596600014122, ' \
              '15.14454186300011429 44.19546133000015686, 15.15219160200012993 44.23529694200014717, ' \
              '15.11036217500011958 44.26434967700011214, 15.14063561300011429 44.28245677300013483, ' \
              '15.17660566500009622 44.24994538000005662, 15.20777428500008455 44.27277252800014651, ' \
              '15.19809004000012465 44.30166250200007028, 15.295258009000122 44.25067780199999845, ' \
              '15.30274498800008587 44.29913971600016964, 15.26124108200011165 44.33258698100003414, ' \
              '15.42448978000001603 44.26797109600006763, 15.52865644600009887 44.27179596600008438, ' \
              '15.30795332100009887 44.35439687700007028, 15.00733483200014007 44.56972890800012976, ' \
              '14.883799675000148 44.7236188820001388, 14.883799675000148 44.86147695500012844, 14.92164147200008983 ' \
              '44.95880768400009231, 14.85279381600011561 45.09365469000000815, 14.65788821700004974 ' \
              '45.19660065300017493, 14.57081139400008851 45.29364655200011214, 14.31153405000009116 ' \
              '45.34398021000005485, 14.23259524800005238 45.14935944200000506, 14.17937259200007816 ' \
              '45.13450755400005221, 14.19312584700008983 45.10561758000012844, 14.14389082100007045 ' \
              '45.05939362200003018, 14.151377800000148 44.97748444200009033, 14.06885826900014536 ' \
              '44.94953034100014122, 14.08383222700007309 44.9863955750000315, 14.04029381600014403 ' \
              '45.03896719000015025, 14.0756942070000548 44.98371002800003282, 14.02051842500011958 ' \
              '44.90110911700004692, 13.97266686300011429 44.90110911700004692, 13.99301191500009622 ' \
              '44.88129303600014453, 13.97266686300011429 44.82664622599999404, 14.00001061300008587 ' \
              '44.81305573100003414, 13.89014733200011165 44.83348216400010244, 13.91797936300014271 ' \
              '44.77826569200009033, 13.90316816500009622 44.77240631700014717, 13.89698326900011693 ' \
              '44.81305573100003414, 13.78711998800014271 44.87506745000008834, 13.84229576900008851 ' \
              '44.88812897300006455, 13.79460696700010658 44.89496491100008768, 13.77409915500007287 ' \
              '44.96381256700014717, 13.6232202480000808 45.07306549700014386, 13.61255944100014403 ' \
              '45.11786530199999845, 13.72624759200004974 45.13450755400005221, 13.5959578790000819 ' \
              '45.14541250200001343, 13.57545006600011561 45.26487864800007799, 13.60271243600001867 ' \
              '45.28534577000012007, 13.57545006600011561 45.30646393400006389, 13.60954837300005238 ' \
              '45.32013580900017757, 13.54127037900013875 45.34613678600005926, 13.50709069100014403 ' \
              '45.51190827000000638, 13.62901778100007277 45.45898346000016943, 13.75929406800014476 ' \
              '45.46316925100011019, 13.88900191200011136 45.42363678000005223, 13.98263960800005634 ' \
              '45.47531321200001742, 13.97189091000012695 45.5142255660000643, 14.09291711400010172 ' \
              '45.47391794800002174, 14.21869755100007637 45.49717234400004884, 14.37279667100006009 ' \
              '45.47784535800009564, 14.4689148350000778 45.52559438100014688, 14.49857710800012001 ' \
              '45.59618438800005435, 14.58094934100009255 45.66780792200010808, 14.66848921700008646 ' \
              '45.53396596300005683, 14.79716353300005949 45.46518463200006011, 14.88160282300009385 ' \
              '45.46978383400001178, 14.9226339110000481 45.51494903600017494, 15.13926151500010064 ' \
              '45.43004465799999991, 15.32519331800011742 45.45283396399999276, 15.36136682100004691 ' \
              '45.48203114900003641, 15.29666792800006192 45.52295888300012905, 15.2685559480001416 ' \
              '45.60166208900012919, 15.37376916500011248 45.64021270800010655, 15.25501672300006817 ' \
              '45.72346344000011698, 15.42906294700014769 45.77529490200011253, 15.45128381300008868 ' \
              '45.81513743100013869, 15.67607629400006886 45.84169911700014666, 15.65943648300003588 ' \
              '45.88882802400014782, 15.69798710100010908 46.0362092080000167, 15.58988000500005455 ' \
              '46.11351715100001059, 15.62284956800010605 46.19170359400006021, 16.01920780400010358 ' \
              '46.29882883700007312, 16.05961877400008575 46.33231516600015709, 16.0579651280001201 ' \
              '46.37753204400003426, 16.2756262620000598 46.37316538500006402, 16.23490523300009158 ' \
              '46.4933389280001137, 16.36947066200013978 46.54057118800012915))) '
        geom = QgsGeometry.fromWkt(wkt)
        f = QgsFeature()
        f.setGeometry(geom)

        image = QImage(200, 200, QImage.Format_RGB32)

        painter = QPainter()
        ms = QgsMapSettings()
        crs = QgsCoordinateReferenceSystem.fromProj4(
            '+proj=ortho +lat_0=36.5 +lon_0=-118.8 +x_0=0 +y_0=0 +a=6371000 +b=6371000 +units=m +no_defs'
        )
        self.assertTrue(crs.isValid())
        ms.setDestinationCrs(crs)
        ms.setExtent(QgsRectangle(1374999.8, 3912610.7, 4724462.5, 6505499.6))
        ms.setOutputSize(image.size())
        context = QgsRenderContext.fromMapSettings(ms)
        context.setPainter(painter)
        context.setScaleFactor(96 / 25.4)  # 96 DPI
        ct = QgsCoordinateTransform(QgsCoordinateReferenceSystem('epsg:4326'),
                                    crs, QgsProject.instance())
        self.assertTrue(ct.isValid())
        context.setCoordinateTransform(ct)
        context.setExtent(
            ct.transformBoundingBox(ms.extent(),
                                    QgsCoordinateTransform.ReverseTransform))

        fill_symbol = QgsFillSymbol.createSimple({
            'color': '#ffffff',
            'outline_color': '#ffffff',
            'outline_width': '10'
        })

        painter.begin(image)
        try:
            image.fill(QColor(0, 0, 0))
            fill_symbol.startRender(context)
            fill_symbol.renderFeature(f, context)
            fill_symbol.stopRender(context)
        finally:
            painter.end()

        assert self.imageCheck('Reprojection errors polygon',
                               'reprojection_errors_polygon', image)

        #also test linestring
        linestring = QgsGeometry(geom.constGet().boundary())
        f.setGeometry(linestring)
        line_symbol = QgsLineSymbol.createSimple({
            'color': '#ffffff',
            'outline_width': '10'
        })

        image = QImage(200, 200, QImage.Format_RGB32)
        painter.begin(image)
        try:
            image.fill(QColor(0, 0, 0))
            line_symbol.startRender(context)
            line_symbol.renderFeature(f, context)
            line_symbol.stopRender(context)
        finally:
            painter.end()

        assert self.imageCheck('Reprojection errors linestring',
                               'reprojection_errors_linestring', image)
Ejemplo n.º 39
0
 def _getExtent(self, canvas, layer):
     crsCanvas = canvas.mapSettings().destinationCrs()
     crsLayer = layer.crs()
     ctCanvas = QgsCoordinateTransform(crsLayer, crsCanvas)
     return ctCanvas.transform(layer.extent())
Ejemplo n.º 40
0
    def testContextSingle(self):
        """
        Various tests to ensure that datum transforms are correctly set respecting context
        """
        context = QgsCoordinateTransformContext()
        context.addSourceDatumTransform(
            QgsCoordinateReferenceSystem('EPSG:28356'), 1)
        context.addDestinationDatumTransform(
            QgsCoordinateReferenceSystem('EPSG:4283'), 2)
        context.addSourceDestinationDatumTransform(
            QgsCoordinateReferenceSystem('EPSG:28356'),
            QgsCoordinateReferenceSystem('EPSG:4283'), 3, 4)

        transform = QgsCoordinateTransform(
            QgsCoordinateReferenceSystem('EPSG:28354'),
            QgsCoordinateReferenceSystem('EPSG:28353'), context)
        # should be no datum transforms
        self.assertEqual(transform.sourceDatumTransformId(), -1)
        self.assertEqual(transform.destinationDatumTransformId(), -1)
        # matching source
        transform = QgsCoordinateTransform(
            QgsCoordinateReferenceSystem('EPSG:28356'),
            QgsCoordinateReferenceSystem('EPSG:28353'), context)
        self.assertEqual(transform.sourceDatumTransformId(), 1)
        self.assertEqual(transform.destinationDatumTransformId(), -1)
        # matching dest
        transform = QgsCoordinateTransform(
            QgsCoordinateReferenceSystem('EPSG:28354'),
            QgsCoordinateReferenceSystem('EPSG:4283'), context)
        self.assertEqual(transform.sourceDatumTransformId(), -1)
        self.assertEqual(transform.destinationDatumTransformId(), 2)
        # matching src/dest pair
        transform = QgsCoordinateTransform(
            QgsCoordinateReferenceSystem('EPSG:28356'),
            QgsCoordinateReferenceSystem('EPSG:4283'), context)
        self.assertEqual(transform.sourceDatumTransformId(), 3)
        self.assertEqual(transform.destinationDatumTransformId(), 4)

        # test manual overwriting
        transform.setSourceDatumTransform(11)
        transform.setDestinationDatumTransform(13)
        self.assertEqual(transform.sourceDatumTransformId(), 11)
        self.assertEqual(transform.destinationDatumTransformId(), 13)

        # test that auto datum setting occurs when updating src/dest crs
        transform.setSourceCrs(QgsCoordinateReferenceSystem('EPSG:28356'))
        self.assertEqual(transform.sourceDatumTransformId(), 3)
        self.assertEqual(transform.destinationDatumTransformId(), 4)
        transform.setSourceDatumTransform(11)
        transform.setDestinationDatumTransform(13)

        transform.setDestinationCrs(QgsCoordinateReferenceSystem('EPSG:4283'))
        self.assertEqual(transform.sourceDatumTransformId(), 3)
        self.assertEqual(transform.destinationDatumTransformId(), 4)
        transform.setSourceDatumTransform(11)
        transform.setDestinationDatumTransform(13)

        # delayed context set
        transform = QgsCoordinateTransform()
        self.assertEqual(transform.sourceDatumTransformId(), -1)
        self.assertEqual(transform.destinationDatumTransformId(), -1)
        transform.setSourceCrs(QgsCoordinateReferenceSystem('EPSG:28356'))
        transform.setDestinationCrs(QgsCoordinateReferenceSystem('EPSG:4283'))
        self.assertEqual(transform.sourceDatumTransformId(), -1)
        self.assertEqual(transform.destinationDatumTransformId(), -1)
        transform.setContext(context)
        self.assertEqual(transform.sourceDatumTransformId(), 3)
        self.assertEqual(transform.destinationDatumTransformId(), 4)
Ejemplo n.º 41
0
    def processAlgorithm(self, context, feedback):
        layer = dataobjects.getLayerFromString(
            self.getParameterValue(self.INPUT))
        method = self.getParameterValue(self.METHOD)

        geometryType = layer.geometryType()
        fields = layer.fields()

        export_z = False
        export_m = False
        if geometryType == QgsWkbTypes.PolygonGeometry:
            areaName = vector.createUniqueFieldName('area', fields)
            fields.append(QgsField(areaName, QVariant.Double))
            perimeterName = vector.createUniqueFieldName('perimeter', fields)
            fields.append(QgsField(perimeterName, QVariant.Double))
        elif geometryType == QgsWkbTypes.LineGeometry:
            lengthName = vector.createUniqueFieldName('length', fields)
            fields.append(QgsField(lengthName, QVariant.Double))
        else:
            xName = vector.createUniqueFieldName('xcoord', fields)
            fields.append(QgsField(xName, QVariant.Double))
            yName = vector.createUniqueFieldName('ycoord', fields)
            fields.append(QgsField(yName, QVariant.Double))
            if QgsWkbTypes.hasZ(layer.wkbType()):
                export_z = True
                zName = vector.createUniqueFieldName('zcoord', fields)
                fields.append(QgsField(zName, QVariant.Double))
            if QgsWkbTypes.hasM(layer.wkbType()):
                export_m = True
                zName = vector.createUniqueFieldName('mvalue', fields)
                fields.append(QgsField(zName, QVariant.Double))

        writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(fields.toList(), layer.wkbType(), layer.crs(),
                                                                     context)

        ellips = None
        crs = None
        coordTransform = None

        # Calculate with:
        # 0 - layer CRS
        # 1 - project CRS
        # 2 - ellipsoidal

        if method == 2:
            ellips = QgsProject.instance().ellipsoid()
            crs = layer.crs().srsid()
        elif method == 1:
            mapCRS = iface.mapCanvas().mapSettings().destinationCrs()
            layCRS = layer.crs()
            coordTransform = QgsCoordinateTransform(layCRS, mapCRS)

        outFeat = QgsFeature()

        outFeat.initAttributes(len(fields))
        outFeat.setFields(fields)

        features = QgsProcessingUtils.getFeatures(layer, context)
        total = 100.0 / QgsProcessingUtils.featureCount(layer, context)
        for current, f in enumerate(features):
            inGeom = f.geometry()

            if method == 1:
                inGeom.transform(coordTransform)

            (attr1, attr2) = vector.simpleMeasure(inGeom, method, ellips, crs)

            outFeat.setGeometry(inGeom)
            attrs = f.attributes()
            attrs.append(attr1)
            if attr2 is not None:
                attrs.append(attr2)

            # add point z/m
            if export_z:
                attrs.append(inGeom.geometry().z())
            if export_m:
                attrs.append(inGeom.geometry().m())

            outFeat.setAttributes(attrs)
            writer.addFeature(outFeat)

            feedback.setProgress(int(current * total))

        del writer
Ejemplo n.º 42
0
    def processAlgorithm(self, parameters, context, feedback):
        source = self.parameterAsSource(parameters, self.INPUT, context)
        if source is None:
            raise QgsProcessingException(
                self.invalidSourceError(parameters, self.INPUT))

        method = self.parameterAsEnum(parameters, self.METHOD, context)

        wkb_type = source.wkbType()
        fields = source.fields()

        new_fields = QgsFields()
        if QgsWkbTypes.geometryType(wkb_type) == QgsWkbTypes.PolygonGeometry:
            new_fields.append(QgsField('area', QVariant.Double))
            new_fields.append(QgsField('perimeter', QVariant.Double))
        elif QgsWkbTypes.geometryType(wkb_type) == QgsWkbTypes.LineGeometry:
            new_fields.append(QgsField('length', QVariant.Double))
            if not QgsWkbTypes.isMultiType(source.wkbType()):
                new_fields.append(QgsField('straightdis', QVariant.Double))
                new_fields.append(QgsField('sinuosity', QVariant.Double))
        else:
            new_fields.append(QgsField('xcoord', QVariant.Double))
            new_fields.append(QgsField('ycoord', QVariant.Double))
            if QgsWkbTypes.hasZ(source.wkbType()):
                self.export_z = True
                new_fields.append(QgsField('zcoord', QVariant.Double))
            if QgsWkbTypes.hasM(source.wkbType()):
                self.export_m = True
                new_fields.append(QgsField('mvalue', QVariant.Double))

        fields = QgsProcessingUtils.combineFields(fields, new_fields)
        (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT,
                                               context, fields, wkb_type,
                                               source.sourceCrs())
        if sink is None:
            raise QgsProcessingException(
                self.invalidSinkError(parameters, self.OUTPUT))

        coordTransform = None

        # Calculate with:
        # 0 - layer CRS
        # 1 - project CRS
        # 2 - ellipsoidal

        self.distance_area = QgsDistanceArea()
        if method == 2:
            self.distance_area.setSourceCrs(source.sourceCrs(),
                                            context.transformContext())
            self.distance_area.setEllipsoid(context.project().ellipsoid())
        elif method == 1:
            coordTransform = QgsCoordinateTransform(source.sourceCrs(),
                                                    context.project().crs(),
                                                    context.project())

        features = source.getFeatures()
        total = 100.0 / source.featureCount() if source.featureCount() else 0
        for current, f in enumerate(features):
            if feedback.isCanceled():
                break

            outFeat = f
            attrs = f.attributes()
            inGeom = f.geometry()
            if inGeom:
                if coordTransform is not None:
                    inGeom.transform(coordTransform)

                if inGeom.type() == QgsWkbTypes.PointGeometry:
                    attrs.extend(self.point_attributes(inGeom))
                elif inGeom.type() == QgsWkbTypes.PolygonGeometry:
                    attrs.extend(self.polygon_attributes(inGeom))
                else:
                    attrs.extend(self.line_attributes(inGeom))

            # ensure consistent count of attributes - otherwise null
            # geometry features will have incorrect attribute length
            # and provider may reject them
            if len(attrs) < len(fields):
                attrs += [NULL] * (len(fields) - len(attrs))

            outFeat.setAttributes(attrs)
            sink.addFeature(outFeat, QgsFeatureSink.FastInsert)

            feedback.setProgress(int(current * total))

        return {self.OUTPUT: dest_id}
Ejemplo n.º 43
0
    def processAlgorithm(self, parameters, context, feedback):

        source = self.parameterAsSource(parameters, self.INPUT, context)

        sampled_raster = self.parameterAsRasterLayer(parameters,
                                                     self.RASTERCOPY, context)

        columnPrefix = self.parameterAsString(parameters, self.COLUMN_PREFIX,
                                              context)

        if source is None:
            raise QgsProcessingException(
                self.invalidSourceError(parameters, self.INPUT))

        source_fields = source.fields()
        raster_fields = QgsFields()

        # append field to vector as columnPrefix_bandCount
        for b in range(sampled_raster.bandCount()):
            raster_fields.append(
                QgsField(columnPrefix + str('_{}'.format(b + 1)),
                         QVariant.Double))

        # combine all the vector fields
        out_fields = QgsProcessingUtils.combineFields(source_fields,
                                                      raster_fields)

        (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT,
                                               context, out_fields,
                                               source.wkbType(),
                                               source.sourceCrs())

        if sink is None:
            raise QgsProcessingException(
                self.invalidSinkError(parameters, self.OUTPUT))

        total = 100.0 / source.featureCount() if source.featureCount() else 0
        features = source.getFeatures()

        # create the coordinates transformation context
        ct = QgsCoordinateTransform(source.sourceCrs(), sampled_raster.crs(),
                                    context.transformContext())

        for n, i in enumerate(source.getFeatures()):

            attrs = i.attributes()

            if i.geometry().isMultipart(
            ) and i.geometry().constGet().partCount() > 1:
                sink.addFeature(i, QgsFeatureSink.FastInsert)
                feedback.setProgress(int(n * total))
                feedback.reportError(
                    self.tr(
                        'Impossible to sample data of multipart feature {}.').
                    format(i.id()))
                continue

            # get the feature geometry as point
            point = QgsPointXY()
            if i.geometry().isMultipart():
                point = i.geometry().asMultiPoint()[0]
            else:
                point = i.geometry().asPoint()

            # reproject to raster crs
            try:
                point = ct.transform(point)
            except QgsCsException:
                for b in range(sampled_raster.bandCount()):
                    attrs.append(None)
                i.setAttributes(attrs)
                sink.addFeature(i, QgsFeatureSink.FastInsert)
                feedback.setProgress(int(n * total))
                feedback.reportError(
                    self.tr(
                        'Could not reproject feature {} to raster CRS').format(
                            i.id()))
                continue

            for b in range(sampled_raster.bandCount()):
                value, ok = sampled_raster.dataProvider().sample(point, b + 1)
                if ok:
                    attrs.append(value)
                else:
                    attrs.append(NULL)

            i.setAttributes(attrs)

            sink.addFeature(i, QgsFeatureSink.FastInsert)
            feedback.setProgress(int(n * total))

        return {self.OUTPUT: dest_id}
Ejemplo n.º 44
0
    def processAlgorithm(self, parameters, context, feedback):
        expression = self.parameterAsString(parameters, self.EXPRESSION,
                                            context)
        layers = self.parameterAsLayerList(parameters, self.LAYERS, context)

        layersDict = {}
        if layers:
            layersDict = {lyr.source(): lyr for lyr in layers}

        crs = self.parameterAsCrs(parameters, self.CRS, context)
        if crs is None or not crs.isValid():
            if not layers:
                raise QgsProcessingException(
                    self.tr("No reference layer selected nor CRS provided"))
            else:
                crs = list(layersDict.values())[0].crs()

        bbox = self.parameterAsExtent(parameters, self.EXTENT, context)
        if bbox.isNull() and not layers:
            raise QgsProcessingException(
                self.tr("No reference layer selected nor extent box provided"))

        if not bbox.isNull():
            bboxCrs = self.parameterAsExtentCrs(parameters, self.EXTENT,
                                                context)
            if bboxCrs != crs:
                transform = QgsCoordinateTransform(bboxCrs, crs,
                                                   context.project())
                bbox = transform.transformBoundingBox(bbox)

        if bbox.isNull() and layers:
            bbox = QgsProcessingUtils.combineLayerExtents(layers, crs)

        cellsize = self.parameterAsDouble(parameters, self.CELLSIZE, context)
        if cellsize == 0 and not layers:
            raise QgsProcessingException(
                self.tr(
                    "No reference layer selected nor cellsize value provided"))

        def _cellsize(layer):
            ext = layer.extent()
            if layer.crs() != crs:
                transform = QgsCoordinateTransform(layer.crs(), crs,
                                                   context.project())
                ext = transform.transformBoundingBox(ext)
            return (ext.xMaximum() - ext.xMinimum()) / layer.width()

        if cellsize == 0:
            cellsize = min([_cellsize(lyr) for lyr in layersDict.values()])

        # check for layers available in the model
        layersDictCopy = layersDict.copy(
        )  # need a shallow copy because next calls invalidate iterator
        for lyr in layersDictCopy.values():
            expression = self.mappedNameToLayer(lyr, expression, layersDict,
                                                context)

        # check for layers available in the project
        for lyr in QgsProcessingUtils.compatibleRasterLayers(
                context.project()):
            expression = self.mappedNameToLayer(lyr, expression, layersDict,
                                                context)

        # create the list of layers to be passed as inputs to RasterCalculaltor
        # at this phase expression has been modified to match available layers
        # in the current scope
        entries = []
        for name, lyr in layersDict.items():
            for n in range(lyr.bandCount()):
                ref = '{:s}@{:d}'.format(name, n + 1)

                if ref in expression:
                    entry = QgsRasterCalculatorEntry()
                    entry.ref = ref
                    entry.raster = lyr
                    entry.bandNumber = n + 1
                    entries.append(entry)

        # Append any missing entry from the current project
        for entry in QgsRasterCalculatorEntry.rasterEntries():
            if not [e for e in entries if e.ref == entry.ref]:
                entries.append(entry)

        output = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)

        width = round((bbox.xMaximum() - bbox.xMinimum()) / cellsize)
        height = round((bbox.yMaximum() - bbox.yMinimum()) / cellsize)
        driverName = GdalUtils.getFormatShortNameFromFilename(output)

        calc = QgsRasterCalculator(expression, output, driverName, bbox, crs,
                                   width, height, entries)

        res = calc.processCalculation(feedback)
        if res == QgsRasterCalculator.ParserError:
            raise QgsProcessingException(self.tr("Error parsing formula"))

        return {self.OUTPUT: output}
Ejemplo n.º 45
0
    def processAlgorithm(self, parameters, context, feedback):
        expression = self.parameterAsString(parameters, self.EXPRESSION,
                                            context)
        layers = self.parameterAsLayerList(parameters, self.LAYERS, context)

        layersDict = {}
        if layers:
            layersDict = {
                os.path.basename(lyr.source().split(".")[0]): lyr
                for lyr in layers
            }

        crs = self.parameterAsCrs(parameters, self.CRS, context)
        if not layers and not crs.isValid():
            raise QgsProcessingException(
                self.tr("No reference layer selected nor CRS provided"))

        if not crs.isValid() and layers:
            crs = list(layersDict.values())[0].crs()

        bbox = self.parameterAsExtent(parameters, self.EXTENT, context)
        if not layers and bbox.isNull():
            raise QgsProcessingException(
                self.tr("No reference layer selected nor extent box provided"))

        if not bbox.isNull():
            bboxCrs = self.parameterAsExtentCrs(parameters, self.EXTENT,
                                                context)
            if bboxCrs != crs:
                transform = QgsCoordinateTransform(bboxCrs, crs,
                                                   context.project())
                bbox = transform.transformBoundingBox(bbox)

        if bbox.isNull() and layers:
            bbox = QgsProcessingUtils.combineLayerExtents(layers, crs)

        cellsize = self.parameterAsDouble(parameters, self.CELLSIZE, context)
        if not layers and cellsize == 0:
            raise QgsProcessingException(
                self.tr(
                    "No reference layer selected nor cellsize value provided"))

        def _cellsize(layer):
            ext = layer.extent()
            if layer.crs() != crs:
                transform = QgsCoordinateTransform(layer.crs(), crs,
                                                   context.project())
                ext = transform.transformBoundingBox(ext)
            return (ext.xMaximum() - ext.xMinimum()) / layer.width()

        if cellsize == 0:
            cellsize = min([_cellsize(lyr) for lyr in layersDict.values()])

        for lyr in QgsProcessingUtils.compatibleRasterLayers(
                context.project()):
            name = lyr.name()
            if (name + "@") in expression:
                layersDict[name] = lyr

        entries = []
        for name, lyr in layersDict.items():
            for n in range(lyr.bandCount()):
                ref = '{:s}@{:d}'.format(name, n + 1)
                if ref in expression:
                    entry = QgsRasterCalculatorEntry()
                    entry.ref = ref
                    entry.raster = lyr
                    entry.bandNumber = n + 1
                    entries.append(entry)

        output = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)

        width = math.floor((bbox.xMaximum() - bbox.xMinimum()) / cellsize)
        height = math.floor((bbox.yMaximum() - bbox.yMinimum()) / cellsize)
        driverName = GdalUtils.getFormatShortNameFromFilename(output)
        calc = QgsRasterCalculator(expression, output, driverName, bbox, crs,
                                   width, height, entries)

        res = calc.processCalculation(feedback)
        if res == QgsRasterCalculator.ParserError:
            raise QgsProcessingException(self.tr("Error parsing formula"))

        return {self.OUTPUT: output}
Ejemplo n.º 46
0
def multi_buffering(layer, radii, callback=None):
    """Buffer a vector layer using many buffers (for volcanoes or rivers).

    This processing algorithm will keep the original attribute table and
    will add a new one for the hazard class name according to
    safe.definitions.fields.hazard_value_field.

    radii = OrderedDict()
    radii[500] = 'high'
    radii[1000] = 'medium'
    radii[2000] = 'low'

    Issue https://github.com/inasafe/inasafe/issues/3185

    :param layer: The layer to polygonize.
    :type layer: QgsVectorLayer

    :param radii: A dictionary of radius.
    :type radii: OrderedDict

    :param callback: A function to all to indicate progress. The function
        should accept params 'current' (int), 'maximum' (int) and 'step' (str).
        Defaults to None.
    :type callback: function

    :return: The buffered vector layer.
    :rtype: QgsVectorLayer
    """
    # Layer output
    output_layer_name = buffer_steps['output_layer_name']
    processing_step = buffer_steps['step_name']

    input_crs = layer.crs()
    feature_count = layer.featureCount()

    fields = layer.fields()
    # Set the new hazard class field.
    new_field = create_field_from_definition(hazard_class_field)
    fields.append(new_field)
    # Set the new buffer distances field.
    new_field = create_field_from_definition(buffer_distance_field)
    fields.append(new_field)

    buffered = create_memory_layer(output_layer_name, QGis.Polygon, input_crs,
                                   fields)
    data_provider = buffered.dataProvider()

    # Reproject features if needed into UTM if the layer is in 4326.
    if layer.crs().authid() == 'EPSG:4326':
        center = layer.extent().center()
        utm = QgsCoordinateReferenceSystem(
            get_utm_epsg(center.x(), center.y(), input_crs))
        transform = QgsCoordinateTransform(layer.crs(), utm)
        reverse_transform = QgsCoordinateTransform(utm, layer.crs())
    else:
        transform = None
        reverse_transform = None

    for i, feature in enumerate(layer.getFeatures()):
        geom = QgsGeometry(feature.geometry())

        if transform:
            geom.transform(transform)

        inner_ring = None

        for radius in radii:
            attributes = feature.attributes()

            # We add the hazard value name to the attribute table.
            attributes.append(radii[radius])
            # We add the value of buffer distance to the attribute table.
            attributes.append(radius)

            circle = geom.buffer(radius, 30)

            if inner_ring:
                circle.addRing(inner_ring)

            inner_ring = circle.asPolygon()[0]

            new_feature = QgsFeature()
            if reverse_transform:
                circle.transform(reverse_transform)

            new_feature.setGeometry(circle)
            new_feature.setAttributes(attributes)

            data_provider.addFeatures([new_feature])

        if callback:
            callback(current=i, maximum=feature_count, step=processing_step)

    # We transfer keywords to the output.
    buffered.keywords = layer.keywords
    buffered.keywords['layer_geometry'] = 'polygon'
    buffered.keywords['layer_purpose'] = layer_purpose_hazard['key']
    buffered.keywords['inasafe_fields'][hazard_class_field['key']] = (
        hazard_class_field['field_name'])

    check_layer(buffered)
    return buffered
Ejemplo n.º 47
0
    def testRenderWithTransform(self):
        layer = QgsAnnotationLayer(
            'test',
            QgsAnnotationLayer.LayerOptions(
                QgsProject.instance().transformContext()))
        self.assertTrue(layer.isValid())

        item = QgsAnnotationPolygonItem(
            QgsPolygon(
                QgsLineString([
                    QgsPoint(11.5, 13),
                    QgsPoint(12, 13),
                    QgsPoint(12, 13.5),
                    QgsPoint(11.5, 13)
                ])))
        item.setSymbol(
            QgsFillSymbol.createSimple({
                'color': '200,100,100',
                'outline_color': 'black',
                'outline_width': '2'
            }))
        item.setZIndex(1)
        layer.addItem(item)

        item = QgsAnnotationLineItem(
            QgsLineString(
                [QgsPoint(11, 13),
                 QgsPoint(12, 13),
                 QgsPoint(12, 15)]))
        item.setSymbol(
            QgsLineSymbol.createSimple({
                'color': '#ffff00',
                'line_width': '3'
            }))
        item.setZIndex(2)
        layer.addItem(item)

        item = QgsAnnotationMarkerItem(QgsPoint(12, 13))
        item.setSymbol(
            QgsMarkerSymbol.createSimple({
                'color': '100,200,200',
                'size': '6',
                'outline_color': 'black'
            }))
        item.setZIndex(3)
        layer.addItem(item)

        layer.setCrs(QgsCoordinateReferenceSystem('EPSG:4326'))

        settings = QgsMapSettings()
        settings.setDestinationCrs(QgsCoordinateReferenceSystem('EPSG:3857'))
        settings.setExtent(QgsRectangle(1250958, 1386945, 1420709, 1532518))
        settings.setOutputSize(QSize(300, 300))

        settings.setFlag(QgsMapSettings.Antialiasing, False)

        rc = QgsRenderContext.fromMapSettings(settings)
        rc.setCoordinateTransform(
            QgsCoordinateTransform(layer.crs(), settings.destinationCrs(),
                                   QgsProject.instance()))
        image = QImage(200, 200, QImage.Format_ARGB32)
        image.setDotsPerMeterX(96 / 25.4 * 1000)
        image.setDotsPerMeterY(96 / 25.4 * 1000)
        image.fill(QColor(255, 255, 255))
        painter = QPainter(image)
        rc.setPainter(painter)

        try:
            renderer = layer.createMapRenderer(rc)
            renderer.render()
        finally:
            painter.end()

        self.assertTrue(
            self.imageCheck('layer_render_transform', 'layer_render_transform',
                            image))
Ejemplo n.º 48
0
def build_layer_table(layer_list=None,only_raster_boundingbox=True):
    """Build a table of layer properties.
    Can be used in conjunction with selecting layers to exclude from mapcomboboxes

    Layer_list: default  None
                if None then it will build the table from all layers in the QGIS project
                otherwise it will use the list.
    
    only_raster_boundingbox: default False 
                    create a bounding box from the raster data 
                   ie removing nodata from polygon. 
                   This will slow it down if large numbers of rasters are present.
    """

    dest_crs = QgsProject.instance().crs()

    gdf_layers = gpd.GeoDataFrame(columns=['layer', 'layer_name', 'layer_id', 'layer_type', 'source','format',
                                           'epsg', 'crs_name', 'is_projected', 'extent', 'provider','geometry'],
                                           geometry='geometry', crs=dest_crs.authid())  # pd.DataFrame()


    if layer_list is None or len(layer_list) == 0:
        layermap = QgsProject.instance().mapLayers().values()

    else:
        layermap = layer_list

    new_rows = []

    for layer in layermap:
        if layer.type() not in [QgsMapLayer.VectorLayer, QgsMapLayer.RasterLayer]:
            continue

        if layer.providerType() not in ['ogr','gdal','delimitedtext']:
            continue
        
        if layer.type() == QgsMapLayer.VectorLayer:
            format = layer.dataProvider().storageType()
        else:
            format=None
            
        if layer.crs().isValid() and layer.crs().authid() == '':
            # Try and convert older style coordinates systems
            # were correctly definied in QGIS 2 as GDA94 / MGA zone 54 
            # but get interpreted in QGIS 3 as  Unknown CRS: BOUNDCRS[SOURCECRS[PROJCRS["GDA94 / MGA zone 54",.....
            
            layer_crs = QgsCoordinateReferenceSystem()
            if not layer_crs.createFromProj(layer.crs().toWkt()):
                #print('Could not match a coordinate system for {}'.format(layer.id()))
                layer_crs = layer.crs()
                
                # could apply to the layer, but what if it's wrong....
                #layer.setCrs(layer_crs)
            
        else: 
            layer_crs = layer.crs()
        
        # project the bounding box extents to be the same as the qgis project.
        if layer_crs.authid() != dest_crs.authid():
            transform = QgsCoordinateTransform(layer_crs, dest_crs, QgsProject.instance())
            prj_ext  = transform.transformBoundingBox(layer.extent())
        else:
            prj_ext  = layer.extent()

        row_dict = {'layer': layer,
                    'layer_name': layer.name(),
                    'layer_id': layer.id(),
                    'layer_type': layerTypes[ layer.type()],
                    'format': format,
                    'source': get_layer_source(layer),
                    'epsg': layer_crs.authid(),
                    'crs_name': layer_crs.description(),
                    'is_projected': not layer_crs.isGeographic(),
                    'provider': layer.providerType(),
                    'geometry': wkt.loads(prj_ext.asWktPolygon())}

            # 'extent': prj_ext.asWktPolygon(),

        if layer.type() == QgsMapLayer.RasterLayer:
            pixel_size = get_pixel_size(layer)
            if not only_raster_boundingbox:
                with rasterio.open(get_layer_source(layer)) as src:
                    msk = src.dataset_mask()  # 0 = nodata 255=valid
                    rast_shapes = rasterio.features.shapes(np.ma.masked_equal(np.where(msk > 0, 1, 0), 0),
                                                           transform=src.transform)
                try:
                    results = ({'properties': {'raster_val': v}, 'geometry': s} for i, (s, v) in enumerate(rast_shapes))
    
                    geoms = list(results)
                    gpd_rPoly = gpd.GeoDataFrame.from_features(geoms, crs=layer.crs().authid())
                    dest_crs.authid().replace('epgs:', '')
                    gpd_rPoly.to_crs(dest_crs.authid().replace('epgs:', ''), inplace=True)
                    row_dict.update({'geometry': gpd_rPoly.unary_union})
    
                    del gpd_rPoly, results, msk,rast_shapes
                except:
                    pass

            row_dict.update({'bandcount': layer.bandCount(),
                        'datatype':dataTypes[layer.dataProvider().dataType(1)],
                        'pixel_size': pixel_size[0],
                        'pixel_text': '{} {}'.format(*pixel_size),
                        })

        new_rows.append(row_dict)

#    gdf_layers = gpd.GeoDataFrame(new_rows, geometry='extent')

    if len(new_rows) == 0:
        return gdf_layers

    # for pandas 0.23.4 add sort=False to prevent row and column orders to change.
    try:
        gdf_layers = gdf_layers.append(new_rows, ignore_index=True, sort=False)
    except:
        gdf_layers = gdf_layers.append(new_rows, ignore_index=True)

    #df_layers.set_geometry('geometry')
    return gdf_layers
Ejemplo n.º 49
0
    def _reverseAdresCallback(self, point):
        self._addMarker(point)
        lam72 = QgsCoordinateReferenceSystem(31370)
        mapCrs = self.gh.getGetMapCrs(self.iface)
        xform = QgsCoordinateTransform(mapCrs, lam72, QgsProject.instance())
        lam72clickt = xform.transform(point)

        #to clear or not clear that is the question
        self.iface.messageBar().clearWidgets()

        #fetch Location from geopunt
        adres = self.gp.fetchLocation(
            str(lam72clickt.x()) + "," + str(lam72clickt.y()), 1)
        Timer(3, self._clearGraphicLayer, ()).start()

        if len(adres) and type(adres) is list:
            #only one result in list, was set in request
            FormattedAddress = adres[0]["FormattedAddress"]

            #add a button to the messageBar widget
            xlam72, ylam72 = adres[0]["Location"]["X_Lambert72"], adres[0][
                "Location"]["Y_Lambert72"]

            diff = int(((xlam72 - lam72clickt.x())**2 +
                        (ylam72 - lam72clickt.y())**2)**(0.5))

            widget = self.iface.messageBar().createMessage(
                QCoreApplication.translate("geopunt4Qgis", "Resultaat: "),
                "{0} (verschil: {1}m)".format(FormattedAddress, diff))

            xy = self.gh.prjPtToMapCrs([xlam72, ylam72], 31370)
            self._addMarker(xy, QColor(0, 255, 200))

            button = QPushButton(widget)
            button.clicked.connect(lambda: self._addReverse(adres[0]))
            button.setText(
                QCoreApplication.translate("geopunt4Qgis", "Voeg toe"))

            widget.layout().addWidget(button)

            self.iface.messageBar().clearWidgets()
            self.iface.messageBar().pushWidget(widget, level=Qgis.Info)

        elif len(adres) == 0:
            self.iface.messageBar().pushMessage(
                QCoreApplication.translate("geopunt4Qgis", "Waarschuwing"),
                QCoreApplication.translate("geopunt4Qgis",
                                           "Geen resultaten gevonden"),
                level=QgsMessageBar.INFO,
                duration=3)

        elif type(adres) is str:
            self.iface.messageBar().pushMessage(QCoreApplication.translate(
                "geopunt4Qgis", "Waarschuwing"),
                                                adres,
                                                level=QgsMessageBar.WARNING)
        else:
            self.iface.messageBar().pushMessage("Error",
                                                QCoreApplication.translate(
                                                    "geopunt4Qgis",
                                                    "onbekende fout"),
                                                level=Qgis.Critical)
Ejemplo n.º 50
0
    def search(self):
        plots_found = []
        features_not_found = []

        fields = PLOTS_LAYER_DEFAULT_FIELDS + self.additional_output_fields

        self.layer_found.startEditing()
        self.layer_found.dataProvider().addAttributes(fields)

        self.layer_not_found.startEditing()
        self.layer_not_found.dataProvider().addAttributes([
            QgsField("tresc_bledu", QVariant.String),
        ])

        features = []
        features_iterator = self.source_layer.getSelectedFeatures(
        ) if self.selected_only else self.source_layer.getFeatures()
        source_crs = self.source_layer.sourceCrs()
        if source_crs != CRS_2180:
            transformation = (QgsCoordinateTransform(
                source_crs, CRS_2180, QgsCoordinateTransformContext()))
            for f in features_iterator:
                point = f.geometry().asPoint()
                point = transformation.transform(point)
                f.setGeometry(QgsGeometry.fromPointXY(point))
                features.append(f)
        else:
            transformation = None
            features = features_iterator

        uldk_search = ULDKSearchPoint("dzialka",
                                      ("geom_wkt", "wojewodztwo", "powiat",
                                       "gmina", "obreb", "numer", "teryt"))

        uldk_search = ULDKSearchLogger(uldk_search)

        found_features = []
        geometries = []
        for source_feature in features:
            if QThread.currentThread().isInterruptionRequested():
                self.__commit()
                self.interrupted.emit(self.layer_found, self.layer_not_found)
                return

            point = source_feature.geometry().asPoint()
            uldk_point = ULDKPoint(point.x(), point.y(), 2180)
            try:
                uldk_response_row = uldk_search.search(uldk_point)
                additional_attributes = []
                for field in self.additional_output_fields:
                    additional_attributes.append(source_feature[field.name()])
                try:
                    found_feature = uldk_response_to_qgs_feature(
                        uldk_response_row, additional_attributes)
                    geometry_wkt = found_feature.geometry().asWkt()
                except BadGeometryException:
                    raise BadGeometryException("Niepoprawna geometria")
                saved = False
                if geometry_wkt not in geometries:
                    saved = True
                    found_features.append(found_feature)
                    self.layer_found.dataProvider().addFeature(found_feature)
                    geometries.append(geometry_wkt)
                self.progressed.emit(True, 0, saved)
            except Exception as e:
                not_found_feature = self.__make_not_found_feature(
                    source_feature.geometry(), e)
                self.layer_not_found.dataProvider().addFeature(
                    not_found_feature)
                self.progressed.emit(False, 0, False)

        self.__commit()
        self.finished.emit(self.layer_found, self.layer_not_found)
Ejemplo n.º 51
0
    def processAlgorithm(self, parameters, context, feedback):
        """
        Here is where the processing itself takes place.
        """

        # Retrieve the feature source and sink. The 'dest_id' variable is used
        # to uniquely identify the feature sink, and must be included in the
        # dictionary returned by the processAlgorithm function.
        source = self.parameterAsSource(parameters, self.INPUT, context)
        # allow only regular point layers. no Multipoints
        if (source.wkbType() == 4 or source.wkbType() == 1004
                or source.wkbType() == 3004):
            raise QgsProcessingException("MultiPoint layer is not supported!")
        # radius = self.parameterAsString(
        #    parameters,
        #    self.RADIUS,
        #    context
        # )
        # mode = self.parameterAsEnum(
        #    parameters,
        #    self.MODES,
        #    context
        # )
        categories = self.parameterAsEnums(parameters, self.KEYS, context)
        # feedback.pushInfo(addressField)

        # If source was not found, throw an exception to indicate that the algorithm
        # encountered a fatal error. The exception text can be any string, but in this
        # case we use the pre-built invalidSourceError method to return a standard
        # helper text for when a source cannot be evaluated
        if source is None:
            raise QgsProcessingException(
                self.invalidSourceError(parameters, self.INPUT))

        fields = QgsFields()
        fields.append(QgsField("id", QVariant.String))
        fields.append(QgsField("origin_id", QVariant.Int))
        fields.append(QgsField("title", QVariant.String))
        fields.append(QgsField("label", QVariant.String))
        fields.append(QgsField("distance", QVariant.Double))
        fields.append(QgsField("categories", QVariant.String))
        (sink,
         dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context,
                                         fields, QgsWkbTypes.Point,
                                         QgsCoordinateReferenceSystem(4326))
        # Send some information to the user
        feedback.pushInfo('{} points for POI finding'.format(
            source.featureCount()))
        # If sink was not created, throw an exception to indicate that the algorithm
        # encountered a fatal error. The exception text can be any string, but in this
        # case we use the pre-built invalidSinkError method to return a standard
        # helper text for when a sink cannot be evaluated
        if sink is None:
            raise QgsProcessingException(
                self.invalidSinkError(parameters, self.OUTPUT))

        # Compute the number of steps to display within the progress bar and
        # get features from source
        total = 100.0 / source.featureCount() if source.featureCount() else 0
        features = source.getFeatures()
        # get the keys:
        creds = self.loadCredFunctionAlg()
        # convert categories to list for API call:
        categoriesList = []
        #self.keys[keyField].split(" | ")[1]
        for category in categories:
            categoriesList.append(self.keys[category])
        categories = ",".join(categoriesList)
        layerCRS = source.sourceCrs()
        if layerCRS != QgsCoordinateReferenceSystem(4326):
            sourceCrs = source.sourceCrs()
            destCrs = QgsCoordinateReferenceSystem(4326)
            tr = QgsCoordinateTransform(sourceCrs, destCrs,
                                        QgsProject.instance())
        for current, feature in enumerate(features):
            # Stop the algorithm if cancel button has been clicked
            if feedback.isCanceled():
                break
            # convert coordinates:
            if layerCRS != QgsCoordinateReferenceSystem(4326):
                # we reproject:
                geom = feature.geometry()
                newGeom = tr.transform(geom.asPoint())
                x = newGeom.x()
                y = newGeom.y()
            else:
                x = feature.geometry().asPoint().x()
                y = feature.geometry().asPoint().y()
            coordinates = str(y) + "," + str(x)
            # get the location from the API:
            header = {"referer": "HQGIS"}
            ApiUrl = 'https://browse.search.hereapi.com/v1/browse?at=' + coordinates + \
                "&categories=" + categories + "&limit=100&apiKey=" + creds["id"]
            feedback.pushInfo('calling Url {}'.format(ApiUrl))
            r = requests.get(ApiUrl, headers=header)
            responsePlaces = json.loads(r.text)["items"]
            for place in responsePlaces:
                lat = place["position"]["lat"]
                lng = place["position"]["lng"]
                # iterate over categories:
                categoriesResp = []
                for cat in place["categories"]:
                    categoriesResp.append(cat["id"])
                fet = QgsFeature()
                fet.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(lng, lat)))
                fet.setAttributes([
                    place["id"],
                    feature.id(), place["title"], place["address"]["label"],
                    place["distance"], ";".join(categoriesResp)
                ])
                sink.addFeature(fet, QgsFeatureSink.FastInsert)
            #lat = responseAddress["Location"]["DisplayPosition"]["Latitude"]
            #lng = responseAddress["Location"]["DisplayPosition"]["Longitude"]
            # Add a feature in the sink
            # feedback.pushInfo(str(lat))

            # fet.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(lng,lat)))
            # fet.setAttributes([

            # Update the progress bar
            feedback.setProgress(int(current * total))

        # To run another Processing algorithm as part of this algorithm, you can use
        # processing.run(...). Make sure you pass the current context and feedback
        # to processing.run to ensure that all temporary layer outputs are available
        # to the executed algorithm, and that the executed algorithm can send feedback
        # reports to the user (and correctly handle cancelation and progress
        # reports!)

        # Return the results of the algorithm. In this case our only result is
        # the feature sink which contains the processed features, but some
        # algorithms may return multiple feature sinks, calculated numeric
        # statistics, etc. These should all be included in the returned
        # dictionary, with keys matching the feature corresponding parameter
        # or output names.
        return {self.OUTPUT: dest_id}
Ejemplo n.º 52
0
    def __init__(self, iface, parent=None, extent=None, crs=None):
        """Constructor for the dialog.

        :param iface: A Quantum GIS QGisAppInterface instance.
        :type iface: QGisAppInterface

        :param parent: Parent widget of this dialog.
        :type parent: QWidget

        :param extent: Extent of the user's preferred analysis area.
        :type extent: QgsRectangle

        :param crs: CRS for user defined analysis extent.
        :type crs: QgsCoordinateReferenceSystem
        """
        QDialog.__init__(self, parent)
        self.setupUi(self)

        self.iface = iface
        self.parent = parent
        self.canvas = iface.mapCanvas()
        self.previous_map_tool = None
        # Prepare the map tool
        self.tool = RectangleMapTool(self.canvas)
        self.previous_map_tool = self.canvas.mapTool()

        if extent is None:
            # Use the current map canvas extents as a starting point
            self.tool.set_rectangle(self.canvas.extent())
        else:

            if isinstance(extent, QgsGeometry):
                # In InaSAFE V4, the extent is a QgsGeometry.
                # This like a hack to transform a geometry to a rectangle.
                extent = wkt_to_rectangle(extent.exportToWkt())

            # Ensure supplied extent is in current canvas crs
            transform = QgsCoordinateTransform(
                crs,
                self.canvas.mapSettings().destinationCrs())
            transformed_extent = transform.transformBoundingBox(extent)
            self.tool.set_rectangle(transformed_extent)

        self._populate_coordinates()

        # Observe inputs for changes
        self.x_minimum.valueChanged.connect(self._coordinates_changed)
        self.y_minimum.valueChanged.connect(self._coordinates_changed)
        self.x_maximum.valueChanged.connect(self._coordinates_changed)
        self.y_maximum.valueChanged.connect(self._coordinates_changed)

        # Draw the rubberband
        self._coordinates_changed()

        # Wire up button events
        self.capture_button.clicked.connect(self.start_capture)
        # Handle cancel
        cancel_button = self.button_box.button(QtGui.QDialogButtonBox.Cancel)
        cancel_button.clicked.connect(self.reject)
        # Make sure to reshow this dialog when rectangle is captured
        self.tool.rectangle_created.connect(self.stop_capture)
        # Setup ok button
        self.ok_button = self.button_box.button(QtGui.QDialogButtonBox.Ok)
        self.ok_button.clicked.connect(self.accept)
        # Set up context help
        self.help_button = self.button_box.button(QtGui.QDialogButtonBox.Help)
        # Allow toggling the help button
        self.help_button.setCheckable(True)
        self.help_button.toggled.connect(self.help_toggled)
        self.main_stacked_widget.setCurrentIndex(1)
        # Reset / Clear button
        clear_button = self.button_box.button(QtGui.QDialogButtonBox.Reset)
        clear_button.setText(self.tr('Clear'))
        clear_button.clicked.connect(self.clear)

        # Populate the bookmarks list and connect the combobox
        self._populate_bookmarks_list()
        self.bookmarks_list.currentIndexChanged.connect(
            self.bookmarks_index_changed)

        # Reinstate the last used radio button
        mode = setting('analysis_extents_mode', HAZARD_EXPOSURE_VIEW)

        if mode == HAZARD_EXPOSURE_VIEW:
            self.hazard_exposure_view_extent.setChecked(True)
        elif mode == EXPOSURE:
            self.exposure_only.setChecked(True)
        elif mode == HAZARD_EXPOSURE:
            self.hazard_exposure_only.setChecked(True)
        elif mode == HAZARD_EXPOSURE_BOOKMARK:
            self.hazard_exposure_bookmark.setChecked(True)
        elif mode == HAZARD_EXPOSURE_BOUNDINGBOX:
            self.hazard_exposure_user_extent.setChecked(True)

        self.show_warnings.setChecked(
            setting('show_extent_warnings', True, bool))
        self.show_confirmations.setChecked(
            setting('show_extent_confirmations', True, bool))
Ejemplo n.º 53
0
    def testContextProj6(self):
        """
        Various tests to ensure that datum transforms are correctly set respecting context
        """
        context = QgsCoordinateTransformContext()
        context.addCoordinateOperation(
            QgsCoordinateReferenceSystem('EPSG:28356'),
            QgsCoordinateReferenceSystem('EPSG:4283'), 'proj')

        transform = QgsCoordinateTransform(
            QgsCoordinateReferenceSystem('EPSG:28354'),
            QgsCoordinateReferenceSystem('EPSG:28353'), context)
        self.assertEqual(
            list(transform.context().coordinateOperations().keys()),
            [('EPSG:28356', 'EPSG:4283')])

        # should be no coordinate operation
        self.assertEqual(transform.coordinateOperation(), '')

        # matching source
        transform = QgsCoordinateTransform(
            QgsCoordinateReferenceSystem('EPSG:28356'),
            QgsCoordinateReferenceSystem('EPSG:28353'), context)
        self.assertEqual(transform.coordinateOperation(), '')
        # matching dest
        transform = QgsCoordinateTransform(
            QgsCoordinateReferenceSystem('EPSG:28354'),
            QgsCoordinateReferenceSystem('EPSG:4283'), context)
        self.assertEqual(transform.coordinateOperation(), '')
        # matching src/dest pair
        transform = QgsCoordinateTransform(
            QgsCoordinateReferenceSystem('EPSG:28356'),
            QgsCoordinateReferenceSystem('EPSG:4283'), context)
        self.assertEqual(transform.coordinateOperation(), 'proj')

        # test manual overwriting
        transform.setCoordinateOperation('proj2')
        self.assertEqual(transform.coordinateOperation(), 'proj2')

        # test that auto operation setting occurs when updating src/dest crs
        transform.setSourceCrs(QgsCoordinateReferenceSystem('EPSG:28356'))
        self.assertEqual(transform.coordinateOperation(), 'proj')
        transform.setCoordinateOperation('proj2')

        transform.setDestinationCrs(QgsCoordinateReferenceSystem('EPSG:4283'))
        self.assertEqual(transform.coordinateOperation(), 'proj')
        transform.setCoordinateOperation('proj2')

        # delayed context set
        transform = QgsCoordinateTransform()
        self.assertEqual(transform.coordinateOperation(), '')
        transform.setSourceCrs(QgsCoordinateReferenceSystem('EPSG:28356'))
        transform.setDestinationCrs(QgsCoordinateReferenceSystem('EPSG:4283'))
        self.assertEqual(transform.coordinateOperation(), '')
        transform.setContext(context)
        self.assertEqual(transform.coordinateOperation(), 'proj')
        self.assertEqual(
            list(transform.context().coordinateOperations().keys()),
            [('EPSG:28356', 'EPSG:4283')])
Ejemplo n.º 54
0
    def processAlgorithm(self, progress):
        layer = dataobjects.getObjectFromUri(
            self.getParameterValue(self.INPUT))
        method = self.getParameterValue(self.METHOD)

        geometryType = layer.geometryType()
        fields = layer.pendingFields()

        if geometryType == QGis.Polygon:
            areaName = vector.createUniqueFieldName('area', fields)
            fields.append(QgsField(areaName, QVariant.Double))
            perimeterName = vector.createUniqueFieldName('perimeter', fields)
            fields.append(QgsField(perimeterName, QVariant.Double))
        elif geometryType == QGis.Line:
            lengthName = vector.createUniqueFieldName('length', fields)
            fields.append(QgsField(lengthName, QVariant.Double))
        else:
            xName = vector.createUniqueFieldName('xcoord', fields)
            fields.append(QgsField(xName, QVariant.Double))
            yName = vector.createUniqueFieldName('ycoord', fields)
            fields.append(QgsField(yName, QVariant.Double))

        writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(
            fields.toList(), layer.wkbType(), layer.crs())

        ellips = None
        crs = None
        coordTransform = None

        # Calculate with:
        # 0 - layer CRS
        # 1 - project CRS
        # 2 - ellipsoidal

        if method == 2:
            ellips = QgsProject.instance().readEntry('Measure', '/Ellipsoid',
                                                     'NONE')[0]
            crs = layer.crs().srsid()
        elif method == 1:
            mapCRS = iface.mapCanvas().mapSettings().destinationCrs()
            layCRS = layer.crs()
            coordTransform = QgsCoordinateTransform(layCRS, mapCRS)

        outFeat = QgsFeature()
        inGeom = QgsGeometry()

        outFeat.initAttributes(len(fields))
        outFeat.setFields(fields)

        features = vector.features(layer)
        total = 100.0 / len(features) if len(features) > 0 else 1
        for current, f in enumerate(features):
            inGeom = f.geometry()

            if method == 1:
                inGeom.transform(coordTransform)

            (attr1, attr2) = vector.simpleMeasure(inGeom, method, ellips, crs)

            outFeat.setGeometry(inGeom)
            attrs = f.attributes()
            attrs.append(attr1)
            if attr2 is not None:
                attrs.append(attr2)
            outFeat.setAttributes(attrs)
            writer.addFeature(outFeat)

            progress.setPercentage(int(current * total))

        del writer
Ejemplo n.º 55
0
def exportRaster(layer, count, layersFolder, feedback, iface, matchCRS):
    feedback.showFeedback("Exporting %s to PNG..." % layer.name())
    name_ts = (safeName(layer.name()) + unicode(count) +
               unicode(int(time.time())))

    # We need to create a new file to export style
    piped_file = os.path.join(tempfile.gettempdir(), name_ts + '_piped.tif')

    piped_extent = layer.extent()
    piped_width = layer.height()
    piped_height = layer.width()
    piped_crs = layer.crs()
    piped_renderer = layer.renderer()
    piped_provider = layer.dataProvider()

    pipe = QgsRasterPipe()
    pipe.set(piped_provider.clone())
    pipe.set(piped_renderer.clone())

    file_writer = QgsRasterFileWriter(piped_file)

    file_writer.writeRaster(pipe, piped_height, -1, piped_extent, piped_crs)

    # Export layer as PNG
    out_raster = os.path.join(layersFolder, safeName(layer.name()) + "_" +
                              unicode(count) + ".png")

    projectCRS = iface.mapCanvas().mapSettings().destinationCrs()
    if not (matchCRS and layer.crs() == projectCRS):
        # Extent of the layer in EPSG:3857
        crsSrc = layer.crs()
        crsDest = QgsCoordinateReferenceSystem(3857)
        try:
            xform = QgsCoordinateTransform(crsSrc, crsDest,
                                           QgsProject.instance())
        except:
            xform = QgsCoordinateTransform(crsSrc, crsDest)
        extentRep = xform.transformBoundingBox(layer.extent())

        extentRepNew = ','.join([unicode(extentRep.xMinimum()),
                                 unicode(extentRep.xMaximum()),
                                 unicode(extentRep.yMinimum()),
                                 unicode(extentRep.yMaximum())])

        # Reproject in 3857
        piped_3857 = os.path.join(tempfile.gettempdir(),
                                  name_ts + '_piped_3857.tif')
        qgis_version = Qgis.QGIS_VERSION

        old_stdout = sys.stdout
        sys.stdout = mystdout = StringIO()
        try:
            processing.algorithmHelp("gdal:warpreproject")
        except:
            pass
        sys.stdout = old_stdout

        params = {
            "INPUT": piped_file,
            "SOURCE_CRS": layer.crs().authid(),
            "TARGET_CRS": "EPSG:3857",
            "NODATA": 0,
            "TARGET_RESOLUTION": 0,
            "RESAMPLING": 2,
            "TARGET_EXTENT": extentRepNew,
            "EXT_CRS": "EPSG:3857",
            "TARGET_EXTENT_CRS": "EPSG:3857",
            "DATA_TYPE": 0,
            "COMPRESS": 4,
            "JPEGCOMPRESSION": 75,
            "ZLEVEL": 6,
            "PREDICTOR": 1,
            "TILED": False,
            "BIGTIFF": 0,
            "TFW": False,
            "MULTITHREADING": False,
            "COPY_SUBDATASETS": False,
            "EXTRA": "",
            "OUTPUT": piped_3857
        }

        warpArgs = {}

        lines = mystdout.getvalue()
        for count, line in enumerate(lines.split("\n")):
            if count != 0 and ":" in line:
                try:
                    k = line.split(":")[0]
                    warpArgs[k] = params[k]
                except:
                    pass

        try:
            processing.run("gdal:warpreproject", warpArgs)
        except:
            shutil.copyfile(piped_file, piped_3857)

        try:
            processing.run("gdal:translate", {"INPUT": piped_3857,
                                              "OUTSIZE": 100,
                                              "OUTSIZE_PERC": True,
                                              "NODATA": 0,
                                              "EXPAND": 0,
                                              "TARGET_CRS": "",
                                              "PROJWIN": extentRepNew,
                                              "SDS": False,
                                              "DATA_TYPE": 0,
                                              "COMPRESS": 4,
                                              "JPEGCOMPRESSION": 75,
                                              "ZLEVEL": 6,
                                              "PREDICTOR": 1,
                                              "TILED": False,
                                              "BIGTIFF": 0,
                                              "TFW": False,
                                              "COPY_SUBDATASETS": False,
                                              "OPTIONS": "",
                                              "OUTPUT": out_raster})
        except:
            shutil.copyfile(piped_3857, out_raster)
    else:
        srcExtent = ','.join([unicode(piped_extent.xMinimum()),
                              unicode(piped_extent.xMaximum()),
                              unicode(piped_extent.yMinimum()),
                              unicode(piped_extent.yMaximum())])
        processing.run("gdal:translate", {"INPUT": piped_file,
                                          "OUTSIZE": 100,
                                          "OUTSIZE_PERC": True,
                                          "NODATA": 0,
                                          "EXPAND": 0,
                                          "TARGET_CRS": "",
                                          "PROJWIN": srcExtent,
                                          "SDS": False,
                                          "DATA_TYPE": 0,
                                          "COMPRESS": 4,
                                          "JPEGCOMPRESSION": 75,
                                          "ZLEVEL": 6,
                                          "PREDICTOR": 1,
                                          "TILED": False,
                                          "BIGTIFF": 0,
                                          "TFW": False,
                                          "COPY_SUBDATASETS": False,
                                          "OPTIONS": "",
                                          "OUTPUT": out_raster})
Ejemplo n.º 56
0
class GSIElevTileProvider:
    def __init__(self, dest_wkt):
        self.dest_wkt = dest_wkt

        # crs transformer, which aims to calculate bbox in EPSG:3857
        self.crs3857 = QgsCoordinateReferenceSystem(3857)
        self.dest_crs = QgsCoordinateReferenceSystem()
        if not self.dest_crs.createFromWkt(dest_wkt):
            logMessage("Failed to create CRS from WKT: {0}".format(dest_wkt))
        self.transform = QgsCoordinateTransform(self.dest_crs, self.crs3857)

        # approximate bbox of this data
        self.boundingbox = QgsRectangle(13667807, 2320477, 17230031, 5713298)

        self.downloader = Downloader()
        self.downloader.userAgent = "QGIS/{0} Qgis2threejs GSIElevTileProvider".format(
            QGis.QGIS_VERSION)  # not written since QGIS 2.2
        self.downloader.DEFAULT_CACHE_EXPIRATION = QSettings().value(
            "/qgis/defaultTileExpiry", 24, type=int)

        self.driver = gdal.GetDriverByName("MEM")
        self.last_dataset = None

    def name(self):
        return "GSI Elevation Tile"

    def read(self, width, height, extent):
        # calculate bounding box in EPSG:3857
        geometry = extent.geometry()
        geometry.transform(self.transform)
        merc_rect = geometry.boundingBox()

        # if the bounding box doesn't intersect with the bounding box of this
        # data, return a list filled with nodata value
        if not self.boundingbox.intersects(merc_rect):
            return [NODATA_VALUE] * width * height

        # get tiles
        over_smpl = 1
        segments_x = 1 if width == 1 else width - 1
        res = extent.width() / segments_x / over_smpl
        ds = self.getDataset(merc_rect.xMinimum(), merc_rect.yMinimum(),
                             merc_rect.xMaximum(), merc_rect.yMaximum(), res)

        geotransform = extent.geotransform(width, height)
        return self._read(ds, width, height, geotransform)

    def readValue(self, x, y):
        """Get value at the position using 1px * 1px memory raster. The value is calculated using a tile of max zoom level"""
        # coordinate transformation into EPSG:3857
        pt = self.transform.transform(QgsPoint(x, y))

        # if the point is not within the bounding box of this data, return
        # nodata value
        if not self.boundingbox.contains(pt):
            return NODATA_VALUE

        res = 0.1
        hres = res / 2
        ds = self.getDataset(pt.x() - hres,
                             pt.y() - hres,
                             pt.x() + hres,
                             pt.y() + hres, res)

        geotransform = [x - hres, res, 0, y + hres, 0, -res]
        return self._read(ds, 1, 1, geotransform)[0]

    def _read(self, ds, width, height, geotransform):
        # create a memory dataset
        warped_ds = self.driver.Create("", width, height, 1, gdal.GDT_Float32)
        warped_ds.SetProjection(self.dest_wkt)
        warped_ds.SetGeoTransform(geotransform)

        # reproject image
        gdal.ReprojectImage(ds, warped_ds, None, None, gdal.GRA_Bilinear)

        # load values into an array
        band = warped_ds.GetRasterBand(1)
        fs = "f" * width * height
        return struct.unpack(
            fs, band.ReadRaster(0, 0, width, height,
                                buf_type=gdal.GDT_Float32))

    def getDataset(self, xmin, ymin, xmax, ymax, mapUnitsPerPixel):
        # calculate zoom level
        mpp1 = TSIZE1 / TILE_SIZE
        zoom = int(math.ceil(math.log(mpp1 / mapUnitsPerPixel, 2) + 1))
        zoom = max(0, min(zoom, ZMAX))

        # calculate tile range (yOrigin is top)
        size = TSIZE1 / 2**(zoom - 1)
        matrixSize = 2**zoom
        ulx = max(0, int((xmin + TSIZE1) / size))
        uly = max(0, int((TSIZE1 - ymax) / size))
        lrx = min(int((xmax + TSIZE1) / size), matrixSize - 1)
        lry = min(int((TSIZE1 - ymin) / size), matrixSize - 1)

        cols = lrx - ulx + 1
        rows = lry - uly + 1

        # download count limit
        if cols * rows > 128:
            logMessage("Number of tiles to fetch is too large!")
            width = height = 1
            return self.driver.Create("", width, height, 1, gdal.GDT_Float32,
                                      [])

        if self.last_dataset and self.last_dataset[0] == [
                zoom, ulx, uly, lrx, lry
        ]:  # if same as last tile set, return cached dataset
            return self.last_dataset[1]

        urltmpl = "http://cyberjapandata.gsi.go.jp/xyz/dem/{z}/{x}/{y}.txt"
        #urltmpl = "http://localhost/xyz/dem/{z}/{x}/{y}.txt"
        tiles = self.fetchFiles(urltmpl, zoom, ulx, uly, lrx, lry)

        # create a memory dataset
        width = cols * TILE_SIZE
        height = rows * TILE_SIZE
        res = size / TILE_SIZE
        geotransform = [
            ulx * size - TSIZE1, res, 0, TSIZE1 - uly * size, 0, -res
        ]

        #mem_driver = gdal.GetDriverByName("GTiff")
        #ds = mem_driver.Create("D:/fetched_tile.tif", width, height, 1, gdal.GDT_Float32, [])

        ds = self.driver.Create("", width, height, 1, gdal.GDT_Float32, [])
        ds.SetProjection(str(self.crs3857.toWkt()))
        ds.SetGeoTransform(geotransform)

        band = ds.GetRasterBand(1)
        for i, tile in enumerate(tiles):
            if tile:
                col = i % cols
                row = i / cols
                band.WriteRaster(col * TILE_SIZE, row * TILE_SIZE, TILE_SIZE,
                                 TILE_SIZE, tile)

        ds.FlushCache()

        self.last_dataset = [[zoom, ulx, uly, lrx, lry], ds]  # cache dataset
        return ds

    def fetchFiles(self, urltmpl, zoom, xmin, ymin, xmax, ymax):
        downloadTimeout = 60

        urls = []
        for y in range(ymin, ymax + 1):
            for x in range(xmin, xmax + 1):
                urls.append(
                    urltmpl.replace("{x}",
                                    str(x)).replace("{y}", str(y)).replace(
                                        "{z}", str(zoom)))
        files = self.downloader.fetchFiles(urls, downloadTimeout)

        for url in urls:
            data = files[url]
            if data:
                # to byte array
                yield numpy.fromstring(data.replace("e",
                                                    str(NODATA_VALUE)).replace(
                                                        "\n", ","),
                                       dtype=numpy.float32,
                                       sep=",").tostring()
            else:
                array = numpy.empty(TILE_SIZE * TILE_SIZE, dtype=numpy.float32)
                array.fill(NODATA_VALUE)
                yield array.tostring()
Ejemplo n.º 57
0
    def generate(self, writer, parameters, context, feedback):
        self.feedback = feedback
        feedback.setProgress(1)

        extent = self.parameterAsExtent(parameters, self.EXTENT, context)
        self.min_zoom = self.parameterAsInt(parameters, self.ZOOM_MIN, context)
        self.max_zoom = self.parameterAsInt(parameters, self.ZOOM_MAX, context)
        dpi = self.parameterAsInt(parameters, self.DPI, context)
        self.color = self.parameterAsColor(parameters, self.BACKGROUND_COLOR,
                                           context)
        self.tile_format = self.formats[self.parameterAsEnum(
            parameters, self.TILE_FORMAT, context)]
        self.quality = self.parameterAsInt(parameters, self.QUALITY, context)
        self.metatilesize = self.parameterAsInt(parameters, self.METATILESIZE,
                                                context)
        self.maxThreads = int(
            ProcessingConfig.getSetting(ProcessingConfig.MAX_THREADS))
        try:
            self.tile_width = self.parameterAsInt(parameters, self.TILE_WIDTH,
                                                  context)
            self.tile_height = self.parameterAsInt(parameters,
                                                   self.TILE_HEIGHT, context)
        except AttributeError:
            self.tile_width = 256
            self.tile_height = 256

        wgs_crs = QgsCoordinateReferenceSystem('EPSG:4326')
        dest_crs = QgsCoordinateReferenceSystem('EPSG:3857')

        project = context.project()
        self.src_to_wgs = QgsCoordinateTransform(project.crs(), wgs_crs,
                                                 context.transformContext())
        self.wgs_to_dest = QgsCoordinateTransform(wgs_crs, dest_crs,
                                                  context.transformContext())
        # without re-writing, we need a different settings for each thread to stop async errors
        # naming doesn't always line up, but the last number does
        self.settingsDictionary = {
            str(i): QgsMapSettings()
            for i in range(self.maxThreads)
        }
        for thread in self.settingsDictionary:
            self.settingsDictionary[thread].setOutputImageFormat(
                QImage.Format_ARGB32_Premultiplied)
            self.settingsDictionary[thread].setDestinationCrs(dest_crs)
            self.settingsDictionary[thread].setLayers(self.layers)
            self.settingsDictionary[thread].setOutputDpi(dpi)
            if self.tile_format == 'PNG':
                self.settingsDictionary[thread].setBackgroundColor(self.color)

            ## disable partial labels (they would be cut at the edge of tiles)
            labeling_engine_settings = self.settingsDictionary[
                thread].labelingEngineSettings()
            labeling_engine_settings.setFlag(
                QgsLabelingEngineSettings.UsePartialCandidates, False)
            self.settingsDictionary[thread].setLabelingEngineSettings(
                labeling_engine_settings)

            # Transfer context scopes to MapSettings
            self.settingsDictionary[thread].setExpressionContext(
                context.expressionContext())

        self.wgs_extent = self.src_to_wgs.transformBoundingBox(extent)
        self.wgs_extent = [
            self.wgs_extent.xMinimum(),
            self.wgs_extent.yMinimum(),
            self.wgs_extent.xMaximum(),
            self.wgs_extent.yMaximum()
        ]

        metatiles_by_zoom = {}
        self.totalMetatiles = 0
        allMetatiles = []
        for zoom in range(self.min_zoom, self.max_zoom + 1):
            metatiles = get_metatiles(self.wgs_extent, zoom, self.metatilesize)
            metatiles_by_zoom[zoom] = metatiles
            allMetatiles += metatiles
            self.totalMetatiles += len(metatiles)

        lab_buffer_px = 100
        self.progress = 0

        tile_params = {
            'format': self.tile_format,
            'quality': self.quality,
            'width': self.tile_width,
            'height': self.tile_height,
            'min_zoom': self.min_zoom,
            'max_zoom': self.max_zoom,
            'extent': self.wgs_extent,
        }
        writer.set_parameters(tile_params)
        self.writer = writer

        self.progressThreadLock = threading.Lock()
        if self.maxThreads > 1:
            feedback.pushConsoleInfo(
                self.tr('Using {max_threads} CPU Threads:').format(
                    max_threads=self.maxThreads))
            for zoom in range(self.min_zoom, self.max_zoom + 1):
                feedback.pushConsoleInfo(
                    self.tr('Generating tiles for zoom level: {zoom}').format(
                        zoom=zoom))
                with ThreadPoolExecutor(
                        max_workers=self.maxThreads) as threadPool:
                    threadPool.map(self.renderSingleMetatile,
                                   metatiles_by_zoom[zoom])
        else:
            feedback.pushConsoleInfo(self.tr('Using 1 CPU Thread:'))
            for zoom in range(self.min_zoom, self.max_zoom + 1):
                feedback.pushConsoleInfo(
                    self.tr('Generating tiles for zoom level: {zoom}').format(
                        zoom=zoom))
                for i, metatile in enumerate(metatiles_by_zoom[zoom]):
                    self.renderSingleMetatile(metatile)

        writer.close()
Ejemplo n.º 58
0
    def processAlgorithm(self, parameters, context, feedback):
        source = self.parameterAsSource(parameters, self.PrmInputLayer,
                                        context)
        shapetype = self.parameterAsInt(parameters, self.PrmShapeType, context)
        radius = self.parameterAsDouble(parameters, self.PrmRadius, context)
        startAngle = self.parameterAsDouble(parameters, self.PrmStartingAngle,
                                            context)
        k = self.parameterAsInt(parameters, self.PrmPetals, context)
        units = self.parameterAsInt(parameters, self.PrmUnitsOfMeasure,
                                    context)
        export_geom = self.parameterAsBool(parameters,
                                           self.PrmExportInputGeometry,
                                           context)

        measureFactor = conversionToMeters(units)
        radius *= measureFactor

        srcCRS = source.sourceCrs()
        fields = source.fields()
        if export_geom:
            names = fields.names()
            name_x, name_y = settings.getGeomNames(names)
            fields.append(QgsField(name_x, QVariant.Double))
            fields.append(QgsField(name_y, QVariant.Double))
        if shapetype == 0:
            (sink, dest_id) = self.parameterAsSink(parameters,
                                                   self.PrmOutputLayer,
                                                   context, fields,
                                                   QgsWkbTypes.Polygon, srcCRS)
        else:
            (sink,
             dest_id) = self.parameterAsSink(parameters, self.PrmOutputLayer,
                                             context, fields,
                                             QgsWkbTypes.LineString, srcCRS)

        if srcCRS != epsg4326:
            geomTo4326 = QgsCoordinateTransform(srcCRS, epsg4326,
                                                QgsProject.instance())
            toSinkCrs = QgsCoordinateTransform(epsg4326, srcCRS,
                                               QgsProject.instance())

        dist = []
        if k == 1:
            dist.append(0.0)
        step = 1
        angle = -90.0 + step
        while angle < 90.0:
            a = math.radians(angle)
            r = math.cos(a)
            dist.append(r)
            angle += step
        cnt = len(dist)

        featureCount = source.featureCount()
        total = 100.0 / featureCount if featureCount else 0

        iterator = source.getFeatures()
        for item, feature in enumerate(iterator):
            if feedback.isCanceled():
                break
            pts = []
            pt = feature.geometry().asPoint()
            pt_orig_x = pt.x()
            pt_orig_y = pt.y()
            # make sure the coordinates are in EPSG:4326
            if srcCRS != epsg4326:
                pt = geomTo4326.transform(pt.x(), pt.y())
            arange = 360.0 / k
            angle = -arange / 2.0
            astep = arange / cnt
            for i in range(k):
                aoffset = arange * (k - 1)
                index = 0
                while index < cnt:
                    r = dist[index] * radius
                    g = geod.Direct(pt.y(), pt.x(),
                                    angle + aoffset + startAngle, r,
                                    Geodesic.LATITUDE | Geodesic.LONGITUDE)
                    pts.append(QgsPointXY(g['lon2'], g['lat2']))
                    angle += astep
                    index += 1
            # repeat the very first point to close the polygon
            pts.append(pts[0])

            # If the Output crs is not 4326 transform the points to the proper crs
            if srcCRS != epsg4326:
                for x, ptout in enumerate(pts):
                    pts[x] = toSinkCrs.transform(ptout)

            f = QgsFeature()
            if shapetype == 0:
                f.setGeometry(QgsGeometry.fromPolygonXY([pts]))
            else:
                f.setGeometry(QgsGeometry.fromPolylineXY(pts))
            attr = feature.attributes()
            if export_geom:
                attr.append(pt_orig_x)
                attr.append(pt_orig_y)
            f.setAttributes(attr)
            sink.addFeature(f)

            if item % 100 == 0:
                feedback.setProgress(int(item * total))

        return {self.PrmOutputLayer: dest_id}
Ejemplo n.º 59
0
    def processAlgorithm(self, parameters, context, feedback):
        source = self.parameterAsSource(parameters, self.INPUT, context)
        if source is None:
            raise QgsProcessingException(self.invalidSourceError(parameters, self.INPUT))

        join_source = self.parameterAsSource(parameters, self.JOIN, context)
        if join_source is None:
            raise QgsProcessingException(self.invalidSourceError(parameters, self.JOIN))

        join_fields = self.parameterAsFields(parameters, self.JOIN_FIELDS, context)
        discard_nomatch = self.parameterAsBool(parameters, self.DISCARD_NONMATCHING, context)
        summaries = [self.statistics[i][0] for i in
                     sorted(self.parameterAsEnums(parameters, self.SUMMARIES, context))]

        if not summaries:
            # none selected, so use all
            summaries = [s[0] for s in self.statistics]

        source_fields = source.fields()
        fields_to_join = QgsFields()
        join_field_indexes = []
        if not join_fields:
            # no fields selected, use all
            join_fields = [join_source.fields().at(i).name() for i in range(len(join_source.fields()))]

        def addFieldKeepType(original, stat):
            """
            Adds a field to the output, keeping the same data type as the original
            """
            field = QgsField(original)
            field.setName(field.name() + '_' + stat)
            fields_to_join.append(field)

        def addField(original, stat, type):
            """
            Adds a field to the output, with a specified type
            """
            field = QgsField(original)
            field.setName(field.name() + '_' + stat)
            field.setType(type)
            if type == QVariant.Double:
                field.setLength(20)
                field.setPrecision(6)
            fields_to_join.append(field)

        numeric_fields = (
            ('count', QVariant.Int, 'count'),
            ('unique', QVariant.Int, 'variety'),
            ('min', QVariant.Double, 'min'),
            ('max', QVariant.Double, 'max'),
            ('range', QVariant.Double, 'range'),
            ('sum', QVariant.Double, 'sum'),
            ('mean', QVariant.Double, 'mean'),
            ('median', QVariant.Double, 'median'),
            ('stddev', QVariant.Double, 'stDev'),
            ('minority', QVariant.Double, 'minority'),
            ('majority', QVariant.Double, 'majority'),
            ('q1', QVariant.Double, 'firstQuartile'),
            ('q3', QVariant.Double, 'thirdQuartile'),
            ('iqr', QVariant.Double, 'interQuartileRange')
        )

        datetime_fields = (
            ('count', QVariant.Int, 'count'),
            ('unique', QVariant.Int, 'countDistinct'),
            ('empty', QVariant.Int, 'countMissing'),
            ('filled', QVariant.Int),
            ('min', None),
            ('max', None)
        )

        string_fields = (
            ('count', QVariant.Int, 'count'),
            ('unique', QVariant.Int, 'countDistinct'),
            ('empty', QVariant.Int, 'countMissing'),
            ('filled', QVariant.Int),
            ('min', None, 'min'),
            ('max', None, 'max'),
            ('min_length', QVariant.Int, 'minLength'),
            ('max_length', QVariant.Int, 'maxLength'),
            ('mean_length', QVariant.Double, 'meanLength')
        )

        field_types = []
        for f in join_fields:
            idx = join_source.fields().lookupField(f)
            if idx >= 0:
                join_field_indexes.append(idx)

                join_field = join_source.fields().at(idx)
                if join_field.isNumeric():
                    field_types.append('numeric')
                    field_list = numeric_fields
                elif join_field.type() in (QVariant.Date, QVariant.Time, QVariant.DateTime):
                    field_types.append('datetime')
                    field_list = datetime_fields
                else:
                    field_types.append('string')
                    field_list = string_fields

                for f in field_list:
                    if f[0] in summaries:
                        if f[1] is not None:
                            addField(join_field, f[0], f[1])
                        else:
                            addFieldKeepType(join_field, f[0])

        out_fields = QgsProcessingUtils.combineFields(source_fields, fields_to_join)

        (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context,
                                               out_fields, source.wkbType(), source.sourceCrs())
        if sink is None:
            raise QgsProcessingException(self.invalidSinkError(parameters, self.OUTPUT))

        # do the join
        predicates = [self.predicates[i][0] for i in self.parameterAsEnums(parameters, self.PREDICATE, context)]

        features = source.getFeatures()
        total = 100.0 / source.featureCount() if source.featureCount() else 0

        # bounding box transform
        bbox_transform = QgsCoordinateTransform(source.sourceCrs(), join_source.sourceCrs(), context.project())

        for current, f in enumerate(features):
            if feedback.isCanceled():
                break

            if not f.hasGeometry():
                if not discard_nomatch:
                    # ensure consistent count of attributes - otherwise non matching
                    # features will have incorrect attribute length
                    # and provider may reject them
                    attrs = f.attributes()
                    if len(attrs) < len(out_fields):
                        attrs += [NULL] * (len(out_fields) - len(attrs))
                    f.setAttributes(attrs)
                    sink.addFeature(f, QgsFeatureSink.FastInsert)
                continue

            bbox = bbox_transform.transformBoundingBox(f.geometry().boundingBox())
            engine = None

            values = []

            request = QgsFeatureRequest().setFilterRect(bbox).setSubsetOfAttributes(join_field_indexes).setDestinationCrs(source.sourceCrs(), context.transformContext())
            for test_feat in join_source.getFeatures(request):
                if feedback.isCanceled():
                    break

                join_attributes = []
                for a in join_field_indexes:
                    join_attributes.append(test_feat[a])

                if engine is None:
                    engine = QgsGeometry.createGeometryEngine(f.geometry().constGet())
                    engine.prepareGeometry()

                for predicate in predicates:
                    if getattr(engine, predicate)(test_feat.geometry().constGet()):
                        values.append(join_attributes)
                        break

            feedback.setProgress(int(current * total))

            if len(values) == 0:
                if discard_nomatch:
                    continue
                else:
                    # ensure consistent count of attributes - otherwise non matching
                    # features will have incorrect attribute length
                    # and provider may reject them
                    attrs = f.attributes()
                    if len(attrs) < len(out_fields):
                        attrs += [NULL] * (len(out_fields) - len(attrs))
                    f.setAttributes(attrs)
                    sink.addFeature(f, QgsFeatureSink.FastInsert)
            else:
                attrs = f.attributes()
                for i in range(len(join_field_indexes)):
                    attribute_values = [v[i] for v in values]
                    field_type = field_types[i]
                    if field_type == 'numeric':
                        stat = QgsStatisticalSummary()
                        for v in attribute_values:
                            stat.addVariant(v)
                        stat.finalize()
                        for s in numeric_fields:
                            if s[0] in summaries:
                                attrs.append(getattr(stat, s[2])())
                    elif field_type == 'datetime':
                        stat = QgsDateTimeStatisticalSummary()
                        stat.calculate(attribute_values)
                        for s in datetime_fields:
                            if s[0] in summaries:
                                if s[0] == 'filled':
                                    attrs.append(stat.count() - stat.countMissing())
                                elif s[0] == 'min':
                                    attrs.append(stat.statistic(QgsDateTimeStatisticalSummary.Min))
                                elif s[0] == 'max':
                                    attrs.append(stat.statistic(QgsDateTimeStatisticalSummary.Max))
                                else:
                                    attrs.append(getattr(stat, s[2])())
                    else:
                        stat = QgsStringStatisticalSummary()
                        for v in attribute_values:
                            if v == NULL:
                                stat.addString('')
                            else:
                                stat.addString(str(v))
                        stat.finalize()
                        for s in string_fields:
                            if s[0] in summaries:
                                if s[0] == 'filled':
                                    attrs.append(stat.count() - stat.countMissing())
                                else:
                                    attrs.append(getattr(stat, s[2])())

                f.setAttributes(attrs)
                sink.addFeature(f, QgsFeatureSink.FastInsert)

        return {self.OUTPUT: dest_id}
Ejemplo n.º 60
0
 def copyCanvas(self):
     extent = self.iface.mapCanvas().extent()
     canvasCrs = self.canvas.mapSettings().destinationCrs()
     if settings.bBoxCrs == 0 and canvasCrs != epsg4326:
         transform = QgsCoordinateTransform(canvasCrs, epsg4326,
                                            QgsProject.instance())
         p1x, p1y = transform.transform(float(extent.xMinimum()),
                                        float(extent.yMinimum()))
         p2x, p2y = transform.transform(float(extent.xMaximum()),
                                        float(extent.yMaximum()))
         extent.set(p1x, p1y, p2x, p2y)
     delim = settings.bBoxDelimiter
     prefix = settings.bBoxPrefix
     suffix = settings.bBoxSuffix
     precision = settings.bBoxDigits
     outStr = ''
     minX = extent.xMinimum()
     minY = extent.yMinimum()
     maxX = extent.xMaximum()
     maxY = extent.yMaximum()
     if settings.bBoxFormat == 0:  # minX,minY,maxX,maxY - using the delimiter
         outStr = '{:.{prec}f}{}{:.{prec}f}{}{:.{prec}f}{}{:.{prec}f}'.format(
             minX, delim, minY, delim, maxX, delim, maxY, prec=precision)
     elif settings.bBoxFormat == 1:  # minX,maxX,minY,maxY - Using the selected delimiter'
         outStr = '{:.{prec}f}{}{:.{prec}f}{}{:.{prec}f}{}{:.{prec}f}'.format(
             minX, delim, maxX, delim, minY, delim, maxY, prec=precision)
     elif settings.bBoxFormat == 2:  # x1 y1,x2 y2,x3 y3,x4 y4,x1 y1 - Polygon format
         outStr = '{:.{prec}f} {:.{prec}f},{:.{prec}f} {:.{prec}f},{:.{prec}f} {:.{prec}f},{:.{prec}f} {:.{prec}f},{:.{prec}f} {:.{prec}f}'.format(
             minX,
             minY,
             minX,
             maxY,
             maxX,
             maxY,
             maxX,
             minY,
             minX,
             minY,
             prec=precision)
     elif settings.bBoxFormat == 3:  # x1,y1 x2,y2 x3,y3 x4,y4 x1,y1 - Polygon format
         outStr = '{:.{prec}f},{:.{prec}f} {:.{prec}f},{:.{prec}f} {:.{prec}f},{:.{prec}f} {:.{prec}f},{:.{prec}f} {:.{prec}f},{:.{prec}f}'.format(
             minX,
             minY,
             minX,
             maxY,
             maxX,
             maxY,
             maxX,
             minY,
             minX,
             minY,
             prec=precision)
     elif settings.bBoxFormat == 4:  # WKT Polygon
         outStr = extent.asWktPolygon()
     elif settings.bBoxFormat == 5:  # bbox: [minX, minY, maxX, maxY] - MapProxy
         outStr = 'bbox: [{}, {}, {}, {}]'.format(minX, minY, maxX, maxY)
     elif settings.bBoxFormat == 6:  # bbox: [minX, minY, maxX, maxY] - MapProxy
         outStr = 'bbox={},{},{},{}'.format(minX, minY, maxX, maxY)
     outStr = '{}{}{}'.format(prefix, outStr, suffix)
     clipboard = QApplication.clipboard()
     clipboard.setText(outStr)
     self.iface.messageBar().pushMessage(
         "",
         "'{}' copied to the clipboard".format(outStr),
         level=Qgis.Info,
         duration=4)