Python qgis.core.QgsCoordinateTransform() Examples

The following are 26 code examples of qgis.core.QgsCoordinateTransform(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module qgis.core , or try the search function .
Example #1
Source File: azDigitizer.py    From qgis-shapetools-plugin with GNU General Public License v2.0 14 votes vote down vote up
def canvasPressEvent(self, event):
        """Capture the coordinate when the mouse button has been released."""
        pt = self.snappoint(event.originalPixelPoint())
        self.removeVertexMarker()
        if self.azDigitizerDialog is None:
            from .azDigitizer import AzDigitizerWidget
            self.azDigitizerDialog = AzDigitizerWidget(self.iface, self.iface.mainWindow())

        layer = self.iface.activeLayer()
        if layer is None or layer.wkbType() != QgsWkbTypes.Point:
            self.azDigitizerDialog.includeStartLabel.setEnabled(False)
            self.azDigitizerDialog.checkBox.setEnabled(False)
        else:
            self.azDigitizerDialog.includeStartLabel.setEnabled(True)
            self.azDigitizerDialog.checkBox.setEnabled(True)
        try:
            canvasCRS = self.canvas.mapSettings().destinationCrs()
            transform = QgsCoordinateTransform(canvasCRS, epsg4326, QgsProject.instance())
            pt4326 = transform.transform(pt.x(), pt.y())
            self.azDigitizerDialog.setPoint(pt4326)
            self.azDigitizerDialog.show()
        except Exception:
            self.iface.messageBar().pushMessage("", tr("Clicked location is invalid"), level=Qgis.Warning, duration=4) 
Example #2
Source File: Map.py    From qgis-earthengine-plugin with MIT License 8 votes vote down vote up
def setCenter(lon, lat, zoom=None):
    """
        Centers the map view at the given coordinates with the given zoom level. If no zoom level is provided, it uses the most recent zoom level on the map.

        https://developers.google.com/earth-engine/api_docs#map.setcenter

        Uses:
            >>> from ee_plugin import Map
            >>> Map.setCenter(lon, lat, zoom)
    """

    ### center
    center_point_in = QgsPointXY(lon, lat)
    # convert coordinates
    crsSrc = QgsCoordinateReferenceSystem(4326)  # WGS84
    crsDest = QgsCoordinateReferenceSystem(QgsProject.instance().crs())
    xform = QgsCoordinateTransform(crsSrc, crsDest, QgsProject.instance())
    # forward transformation: src -> dest
    center_point = xform.transform(center_point_in)
    iface.mapCanvas().setCenter(center_point)

    ### zoom
    if zoom is not None:
        # transform the zoom level to scale
        scale_value = 591657550.5 / 2 ** (zoom - 1)
        iface.mapCanvas().zoomScale(scale_value) 
Example #3
Source File: latLonTools.py    From qgis-latlontools-plugin with GNU General Public License v2.0 7 votes vote down vote up
def zoomTo(self, srcCrs, lat, lon):
        canvasCrs = self.canvas.mapSettings().destinationCrs()
        transform = QgsCoordinateTransform(srcCrs, canvasCrs, QgsProject.instance())
        x, y = transform.transform(float(lon), float(lat))

        rect = QgsRectangle(x, y, x, y)
        self.canvas.setExtent(rect)

        pt = QgsPointXY(x, y)
        self.highlight(pt)
        self.canvas.refresh()
        return pt 
Example #4
Source File: utm.py    From qgis-latlontools-plugin with GNU General Public License v2.0 7 votes vote down vote up
def utmString2Crs(utm, crs=epsg4326):
    parts = re.split(r'[\s]+', utm.upper())
    utmlen = len(parts)
    if utmlen == 3:
        m = re.findall(r'(\d+)([NS])', parts[0])
        if len(m) != 1 or len(m[0]) != 2:
            raise ValueError('Invalid UTM Coordinate')
        zone = int(m[0][0])
        hemisphere = m[0][1]
        easting = float(parts[1])
        northing = float(parts[2])
    elif utmlen == 4:
        if parts[1] != 'N' and parts[1] != 'S':
            raise ValueError('Invalid UTM Coordinate')
        zone = int(parts[0])
        easting = float(parts[2])
        northing = float(parts[3])
    else:
        raise ValueError('Invalid UTM Coordinate')
    if zone < 1 or zone > 60:
        raise ValueError('Invalid UTM Coordinate')

    utmcrs = QgsCoordinateReferenceSystem(utm_epsg_codes['{}{}'.format(zone, hemisphere)])
    pt = QgsPointXY(easting, northing)
    utmtrans = QgsCoordinateTransform(utmcrs, crs, QgsProject.instance())
    return(utmtrans.transform(pt)) 
Example #5
Source File: utils.py    From qgis-earthengine-plugin with MIT License 7 votes vote down vote up
def geom_to_geo(geom):
    crs_src = QgsCoordinateReferenceSystem(QgsProject.instance().crs())
    crs_dst = QgsCoordinateReferenceSystem(4326)
    proj2geo = QgsCoordinateTransform(crs_src, crs_dst, QgsProject.instance())

    if isinstance(geom, QgsPointXY):
        return proj2geo.transform(geom)
    elif isinstance(geom, QgsRectangle):
        return proj2geo.transformBoundingBox(geom)
    else:
        return geom.transform(proj2geo) 
Example #6
Source File: virtual_raster.py    From DsgTools with GNU General Public License v2.0 6 votes vote down vote up
def createReprojectedLayer(layer, crs):
    """
    Creates a reprojected layer
    layer: layer used
    crs: crs used
    """
    temp = QgsVectorLayer('%s?crs=%s'% ('Multipolygon', crs.authid()), 'temp', 'memory')
    if not layer.isValid():
        raise GeoAlgorithmExecutionException('Problema ao criar camada reprojetada!')
        return None
    
    provider = temp.dataProvider()
    provider.addAttributes(layer.dataProvider().fields().toList())
    temp.updateFields()
    
    coordinateTransformer = QgsCoordinateTransform(layer.crs(), crs)
    features = []
    for feature in layer.getFeatures():
        feat = QgsFeature(feature)
        geom = feat.geometry()
        geom.transform(coordinateTransformer)
        feat.setGeometry(geom)
        features.append(feat)
        
    provider.addFeatures(features)
    
    return temp 
Example #7
Source File: captureCoordinate.py    From qgis-latlontools-plugin with GNU General Public License v2.0 6 votes vote down vote up
def canvasReleaseEvent(self, event):
        '''Capture the coordinate when the mouse button has been released,
        format it, and copy it to the clipboard. pt is QgsPointXY'''
        pt = self.snappoint(event.originalPixelPoint())
        self.removeVertexMarker()

        try:
            canvasCRS = self.canvas.mapSettings().destinationCrs()
            transform = QgsCoordinateTransform(canvasCRS, epsg4326, QgsProject.instance())
            pt4326 = transform.transform(pt.x(), pt.y())
            self.capturePoint.emit(pt4326)
        except Exception as e:
            pass 
Example #8
Source File: mapillary_image_info.py    From go2mapillary with GNU General Public License v3.0 6 votes vote down vote up
def panToAction(self):
        crsCanvas = self.module.iface.mapCanvas().mapSettings().destinationCrs() # get current crs
        crsWGS84 = QgsCoordinateReferenceSystem(4326)  # WGS 84
        xform = QgsCoordinateTransform(crsWGS84, crsCanvas, QgsProject.instance())
        sourcePoint = QgsPointXY(float(self.field_longitude.text()),float(self.field_latitude.text()))
        self.module.iface.mapCanvas().setCenter(xform.transform(sourcePoint))
        self.module.iface.mapCanvas().refresh() 
Example #9
Source File: inspectFeatures.py    From DsgTools with GNU General Public License v2.0 6 votes vote down vote up
def zoomToLayer(self, layer, zoom = None):
        box = layer.boundingBoxOfSelected()
        if zoom is not None:
            box.grow(100-zoom)
        # Defining the crs from src and destiny
        epsg = self.iface.mapCanvas().mapSettings().destinationCrs().authid()
        crsDest = QgsCoordinateReferenceSystem(epsg)
        #getting srid from something like 'EPSG:31983'
        if not layer:
            layer = self.iface.mapCanvas().currentLayer()
        srid = layer.crs().authid()
        crsSrc = QgsCoordinateReferenceSystem(srid) #here we have to put authid, not srid
        # Creating a transformer
        coordinateTransformer = QgsCoordinateTransform(crsSrc, crsDest, QgsProject.instance())
        newBox = coordinateTransformer.transform(box)

        self.iface.mapCanvas().setExtent(newBox)
        self.iface.mapCanvas().refresh() 
Example #10
Source File: lineDigitizer.py    From qgis-shapetools-plugin with GNU General Public License v2.0 6 votes vote down vote up
def canvasPressEvent(self, event):
        '''Capture the coordinate when the mouse button has been released.'''
        pt = self.snappoint(event.originalPixelPoint())
        self.removeVertexMarker()
        layer = self.iface.activeLayer()
        if layer is None:
            return
        if self.lineDigitizerDialog is None:
            from .lineDigitizer import LineDigitizerWidget
            self.lineDigitizerDialog = LineDigitizerWidget(self.iface, self.iface.mainWindow())

        if layer.geometryType() == QgsWkbTypes.LineGeometry:
            self.lineDigitizerDialog.closeLineCheckBox.setEnabled(True)
        else:
            self.lineDigitizerDialog.closeLineCheckBox.setEnabled(False)
        try:
            canvasCRS = self.canvas.mapSettings().destinationCrs()
            transform = QgsCoordinateTransform(canvasCRS, epsg4326, QgsProject.instance())
            pt4326 = transform.transform(pt.x(), pt.y())
            self.lineDigitizerDialog.setPoint(pt4326)
            self.lineDigitizerDialog.valuesTextEdit.clear()
            self.lineDigitizerDialog.show()
        except Exception:
            self.iface.messageBar().pushMessage("", tr("Clicked location is invalid"), level=Qgis.Warning, duration=4) 
Example #11
Source File: compat2qgis.py    From quickmapservices with GNU General Public License v2.0 5 votes vote down vote up
def setDestinationCrs(self, dst_crs):
        if QGis.QGIS_VERSION_INT >= 30000:
            super(QgsCoordinateTransform, self).setDestinationCrs(dst_crs)
        else:
            self.setDestCRS(dst_crs) 
Example #12
Source File: reverseGeocode.py    From qgis-bulk-nominatim with GNU General Public License v2.0 5 votes vote down vote up
def addMarker(self, lat, lon):
        if self.marker:
            self.removeMarker()
        canvasCrs = self.canvas.mapSettings().destinationCrs()
        transform = QgsCoordinateTransform(self.epsg4326, canvasCrs, QgsProject.instance())
        center = transform.transform(lon, lat)
        self.marker = QgsVertexMarker(self.canvas)
        self.marker.setCenter(center)
        self.marker.setColor(QColor(255, 70, 0))
        self.marker.setIconSize(15)
        self.marker.setIconType(QgsVertexMarker.ICON_X)
        self.marker.setPenWidth(3)
        self.marker.show() 
Example #13
Source File: compat2qgis.py    From quickmapservices with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, src_crs, dst_crs):
        super(QgsCoordinateTransform, self).__init__()
        
        self.setSourceCrs(src_crs)
        self.setDestinationCrs(dst_crs) 
Example #14
Source File: acquisitionFreeController.py    From DsgTools with GNU General Public License v2.0 5 votes vote down vote up
def reprojectGeometry(self, geom):
        # Defining the crs from src and destiny
        iface = self.getIface()
        canvas = iface.mapCanvas()
        epsg = canvas.mapSettings().destinationCrs().authid()
        crsSrc = core.QgsCoordinateReferenceSystem(epsg)
        #getting srid from something like 'EPSG:31983'
        layer = canvas.currentLayer()
        srid = layer.crs().authid()
        crsDest = core.QgsCoordinateReferenceSystem(srid) #here we have to put authid, not srid
        if srid != epsg:
            # Creating a transformer
            coordinateTransformer = core.QgsCoordinateTransform(crsSrc, crsDest, QgsProject.instance())
            geomType =  geom.type()
            # Transforming the points
            if geomType == core.QgsWkbTypes.LineGeometry:
                geomList = geom.asPolyline()
            elif geomType == core.QgsWkbTypes.PolygonGeometry:
                geomList = geom.asPolygon()
            newGeom = []
            for j in range(len(geomList)):
                if geomType == core.QgsWkbTypes.LineGeometry:
                    newGeom.append(coordinateTransformer.transform(geomList[j]))
                elif geomType == core.QgsWkbTypes.PolygonGeometry:
                    line = geomList[j]
                    for i in range(len(line)):
                        point = line[i]
                        newGeom.append(coordinateTransformer.transform(point))
            if geomType == core.QgsWkbTypes.LineGeometry:
                return core.QgsGeometry.fromPolylineXY(newGeom)
            elif geomType == core.QgsWkbTypes.PolygonGeometry:
                return core.QgsGeometry.fromPolygonXY([newGeom])
        return geom 
Example #15
Source File: acquisitionFreeController.py    From DsgTools with GNU General Public License v2.0 5 votes vote down vote up
def simplifyGeometry(self, geom, tolerance):
        #Método para simplificar geometria
        #Parâmetro de entrada: geom (Geometria adquirida), tolerance (Tolerância para simplificação)
        #Parâmetro de retorno: sGeom (Geometria simplificada)
        parameters = self.getParametersFromConfig()
        sGeom = geom
        source_crs = self.iface.activeLayer().crs()
        dest_crs = core.QgsCoordinateReferenceSystem(3857)
        tr = core.QgsCoordinateTransform(source_crs, dest_crs, core.QgsCoordinateTransformContext())
        sGeom.transform(tr)
        for x in range(int(parameters[u'algIterations'])):
            sGeom = sGeom.simplify(float(tolerance))
            try:
                sGeom = sGeom.smooth(
                    int(parameters[u'freeHandSmoothIterations']),
                    float(parameters[u'freeHandSmoothOffset'])
                )
            except:
                msg = QMessageBox().tr('Probably too many smoothing iteration, try reducing it (3 usually is enough). Geometry was not smoothened.')
                QMessageBox.warning(
                    self.iface.mainWindow(),
                    QMessageBox().tr('Error!'),
                    msg
                )
                QgsMessageLog.logMessage(msg, 'DSGTools Plugin', Qgis.Critical)
                return geom
        tr = core.QgsCoordinateTransform(dest_crs, source_crs, core.QgsCoordinateTransformContext())
        sGeom.transform(tr)
        return sGeom 
Example #16
Source File: contour_tool.py    From DsgTools with GNU General Public License v2.0 5 votes vote down vote up
def reproject(self, geom, canvasCrs):
        """
        Reprojects geom to the reference layer crs
        """
        destCrs = self.reference.crs()
        if canvasCrs.authid() != destCrs.authid():
            coordinateTransformer = QgsCoordinateTransform(canvasCrs, destCrs)
            geom.transform(coordinateTransformer) 
Example #17
Source File: Map.py    From qgis-earthengine-plugin with MIT License 5 votes vote down vote up
def centerObject(feature, zoom=None):
    """
        Centers the map view on a given object.

        https://developers.google.com/earth-engine/api_docs#map.centerobject

        Uses:
            >>> from ee_plugin import Map
            >>> Map.centerObject(feature)
    """


    feature = ee.Feature(feature)

    if not zoom:
        # make sure our geometry is in geo
        rect = feature.geometry().transform(ee.Projection('EPSG:4326'), 1)

        # get coordinates
        coords = rect.bounds().getInfo()['coordinates'][0]
        xmin = coords[0][0]
        ymin = coords[0][1]
        xmax = coords[2][0]
        ymax = coords[2][1]

        # construct QGIS geometry
        rect = QgsRectangle(xmin, ymin, xmax, ymax)

        # transform rect to a crs used by current project
        crs_src = QgsCoordinateReferenceSystem(4326)
        crs_dst = QgsCoordinateReferenceSystem(QgsProject.instance().crs())
        geo2proj = QgsCoordinateTransform(crs_src, crs_dst, QgsProject.instance())
        rect_proj = geo2proj.transform(rect)

        # center geometry
        iface.mapCanvas().zoomToFeatureExtent(rect_proj)
    else:
        # set map center to feature centroid at a specified zoom
        center = feature.geometry().centroid().coordinates().getInfo()
        setCenter(center[0], center[1], zoom) 
Example #18
Source File: mapillary_coverage.py    From go2mapillary with GNU General Public License v3.0 5 votes vote down vote up
def transformToWGS84(self, pPoint):
        # transformation from the current SRS to WGS84
        crcMappaCorrente = self.iface.mapCanvas().mapSettings().destinationCrs() # get current crs
        crsSrc = crcMappaCorrente
        crsDest = QgsCoordinateReferenceSystem(4326)  # WGS 84
        xform = QgsCoordinateTransform(crsSrc, crsDest, QgsProject.instance())
        return xform.transform(pPoint) # forward transformation: src -> dest 
Example #19
Source File: mapillary_filter.py    From go2mapillary with GNU General Public License v3.0 5 votes vote down vote up
def clickedOnCanvasAction(self,clickedPoint):
        self.iface.mapCanvas().setMapTool(self.module.mapSelectionTool)
        crsCanvas = self.module.iface.mapCanvas().mapSettings().destinationCrs() # get current crs
        crsWGS84 = QgsCoordinateReferenceSystem(4326)  # WGS 84
        xform = QgsCoordinateTransform(crsCanvas, crsWGS84, QgsProject.instance())
        wgs84point = xform.transform(clickedPoint)
        self.lon_widget.setText(str(wgs84point.x()))
        self.lat_widget.setText(str(wgs84point.y()))
        super(mapillaryFilter, self).show()
        self.raise_() 
Example #20
Source File: utm.py    From qgis-latlontools-plugin with GNU General Public License v2.0 5 votes vote down vote up
def latLon2UtmString(lat, lon, precision):
    zone = int((lon + 180) / 6) + 1
    if lon >= 0:
        zonestr = '{}N'.format(zone)
    else:
        zonestr = '{}S'.format(zone)
    try:
        utmcrs = QgsCoordinateReferenceSystem(utm_epsg_codes[zonestr])
        utmtrans = QgsCoordinateTransform(epsg4326, utmcrs, QgsProject.instance())
        pt = QgsPointXY(lon, lat)
        utmpt = utmtrans.transform(pt)
        msg = '{} {:.{prec}f} {:.{prec}f}'.format(zonestr, utmpt.x(), utmpt.y(), prec=precision)
    except Exception:
        msg = ''
    return(msg) 
Example #21
Source File: latLonTools.py    From qgis-latlontools-plugin with GNU General Public License v2.0 5 votes vote down vote up
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) 
Example #22
Source File: reverseGeocode.py    From qgis-bulk-nominatim with GNU General Public License v2.0 5 votes vote down vote up
def transform_geom(self, geometry):
        canvasCrs = self.canvas.mapSettings().destinationCrs()
        geom = QgsGeometry(geometry)
        geom.transform(QgsCoordinateTransform(self.epsg4326, canvasCrs, QgsProject.instance()))
        return geom 
Example #23
Source File: idlbreakline.py    From qgis-shapetools-plugin with GNU General Public License v2.0 4 votes vote down vote up
def processAlgorithm(self, parameters, context, feedback):
        source = self.parameterAsSource(parameters, self.PrmInputLayer, context)
        srcCRS = source.sourceCrs()

        (sink, dest_id) = self.parameterAsSink(
            parameters, self.PrmOutputLayer, context, source.fields(),
            QgsWkbTypes.MultiLineString, srcCRS)

        # Set up CRS transformations
        if srcCRS != epsg4326:
            geomTo4326 = QgsCoordinateTransform(srcCRS, epsg4326, QgsProject.instance())
            toSinkCrs = QgsCoordinateTransform(epsg4326, srcCRS, QgsProject.instance())

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

        iterator = source.getFeatures()
        for cnt, feature in enumerate(iterator):
            if feedback.isCanceled():
                break
            try:
                if feature.geometry().isMultipart():
                    seg = feature.geometry().asMultiPolyline()
                else:
                    seg = [feature.geometry().asPolyline()]
                numseg = len(seg)
                if numseg < 1 or len(seg[0]) < 2:
                    continue

                outseg = []
                for pts in seg:
                    if srcCRS != epsg4326:
                        for x, pt in enumerate(pts):
                            pts[x] = geomTo4326.transform(pt)
                    normalizeLongitude(pts)
                    newseg = checkIdlCrossings(pts)
                    outseg.extend(newseg)
                if srcCRS != epsg4326:  # Convert each point to the output CRS
                    for y in range(len(outseg)):
                        for x, pt in enumerate(outseg[y]):
                            outseg[y][x] = toSinkCrs.transform(pt)

                f = QgsFeature()
                f.setGeometry(QgsGeometry.fromMultiPolylineXY(outseg))
                f.setAttributes(feature.attributes())
                sink.addFeature(f)

            except Exception:
                '''s = traceback.format_exc()
                feedback.pushInfo(s)'''
                pass

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

        return {self.PrmOutputLayer: dest_id} 
Example #24
Source File: azDigitizer.py    From qgis-shapetools-plugin with GNU General Public License v2.0 4 votes vote down vote up
def accept(self):
        try:
            distance = float(self.distLineEdit.text())
            azimuth = float(self.azimuthLineEdit.text())
            units = self.unitsComboBox.currentIndex()  # 0 km, 1 m, 2 nm, 3 miles, 4 yards, 5 ft, 6 inches, 7 cm
            start = self.checkBox.isChecked()
        except Exception:
            self.iface.messageBar().pushMessage("", tr("Either distance or azimuth were invalid"), level=Qgis.Warning, duration=4)
            return
        layer = self.iface.activeLayer()
        if layer is None:
            self.iface.messageBar().pushMessage("", tr("No point or line layer selected"), level=Qgis.Warning, duration=4)
            return

        measureFactor = conversionToMeters(units)

        distance = distance * measureFactor
        pt = self.pt
        destCRS = layer.crs()
        transform = QgsCoordinateTransform(epsg4326, destCRS, QgsProject.instance())
        if layer.wkbType() == QgsWkbTypes.Point:
            g = geod.Direct(pt.y(), pt.x(), azimuth, distance, Geodesic.LATITUDE | Geodesic.LONGITUDE)
            if start:
                ptStart = transform.transform(self.pt.x(), self.pt.y())
                feat = QgsFeature(layer.fields())
                feat.setGeometry(QgsGeometry.fromPointXY(ptStart))
                layer.addFeature(feat)
            pt = transform.transform(g['lon2'], g['lat2'])
            feat = QgsFeature(layer.fields())
            feat.setGeometry(QgsGeometry.fromPointXY(pt))
            layer.addFeature(feat)
        else:  # It will either be a LineString or MultiLineString
            maxseglen = settings.maxSegLength * 1000.0  # Needs to be in meters
            maxSegments = settings.maxSegments
            gline = geod.Line(pt.y(), pt.x(), azimuth)
            n = int(math.ceil(distance / maxseglen))
            if n > maxSegments:
                n = maxSegments
            seglen = distance / n
            pts = []
            for i in range(0, n + 1):
                s = seglen * i
                g = gline.Position(s, Geodesic.LATITUDE | Geodesic.LONGITUDE | Geodesic.LONG_UNROLL)
                ptc = transform.transform(g['lon2'], g['lat2'])
                pts.append(ptc)
            feat = QgsFeature(layer.fields())
            if layer.wkbType() == QgsWkbTypes.LineString:
                feat.setGeometry(QgsGeometry.fromPolylineXY(pts))
            else:
                feat.setGeometry(QgsGeometry.fromMultiPolylineXY([pts]))
            layer.addFeatures([feat])

        layer.updateExtents()
        self.iface.mapCanvas().refresh()
        self.close() 
Example #25
Source File: showOnMapTool.py    From qgis-latlontools-plugin with GNU General Public License v2.0 4 votes vote down vote up
def canvasPressEvent(self, event):
        '''Capture the coordinate when the mouse button has been released,
        format it, and copy it to the clipboard.'''
        pt = self.snappoint(event.originalPixelPoint())
        self.removeVertexMarker()
        if settings.externalMapShowLocation:
            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()

        button = event.button()

        canvasCRS = self.canvas.mapSettings().destinationCrs()
        transform = QgsCoordinateTransform(canvasCRS, epsg4326, QgsProject.instance())
        pt4326 = transform.transform(pt.x(), pt.y())
        lat = pt4326.y()
        lon = pt4326.x()
        if settings.googleEarthMapProvider(button):
            f = tempfile.NamedTemporaryFile(mode='w', suffix=".kml", delete=False)
            f.write('<?xml version="1.0" encoding="UTF-8"?>')
            f.write('<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">')
            f.write('<Document>')
            f.write('   <name>QGIS Location</name>')
            f.write('   <description>{:.8f}, {:.8f}</description>'.format(lon, lat))
            f.write('   <Placemark>')
            f.write('       <name>QGIS Location</name>')
            f.write('       <Point>')
            f.write('           <coordinates>{:.8f},{:.8f},0</coordinates>'.format(lon, lat))
            f.write('       </Point>')
            f.write('   </Placemark>')
            f.write('</Document>')
            f.write('</kml>')
            f.close()
            if platform.system() == 'Windows':
                os.startfile(f.name)
            else:
                webbrowser.open(f.name)
            self.iface.messageBar().pushMessage("", "Viewing Coordinate %f,%f in Google Earth" % (lat, lon), level=Qgis.Info, duration=3)
        else:
            mapprovider = settings.getMapProviderString(lat, lon, button)
            url = QUrl(mapprovider).toString()
            webbrowser.open(url, new=2)
            self.iface.messageBar().pushMessage("", "Viewing Coordinate %f,%f in external map" % (lat, lon), level=Qgis.Info, duration=3) 
Example #26
Source File: reverseGeocode.py    From qgis-bulk-nominatim with GNU General Public License v2.0 4 votes vote down vote up
def canvasReleaseEvent(self, event):
        # Make sure the point is transfored to 4326
        self.clearSelection()
        pt = self.toMapCoordinates(event.pos())
        canvasCRS = self.canvas.mapSettings().destinationCrs()
        transform = QgsCoordinateTransform(canvasCRS, self.epsg4326, QgsProject.instance())
        pt = transform.transform(pt.x(), pt.y())
        url = '{}?format=json&lat={:f}&lon={:f}&zoom={:d}&addressdetails=0&polygon_text=1'.format(self.settings.reverseURL(), pt.y(), pt.x(), self.settings.levelOfDetail)
        # print( url )
        jsondata = self.request(url)

        try:
            jd = json.loads(jsondata)
            try:
                display_name = jd['display_name']
                self.setText(display_name)
            except KeyError:
                self.setText("[Could not find address]")
            try:
                wkt = jd['geotext']
                geometry = QgsGeometry.fromWkt(wkt)
                if geometry.wkbType() == QgsWkbTypes.Point:
                    pt = geometry.asPoint()
                    lon = pt.x()
                    lat = pt.y()
                    self.addMarker(lat, lon)
                else:
                    geometry = self.transform_geom(geometry)
                    self.rubber.addGeometry(geometry, None)
                    self.rubber.show()
            except KeyError:
                try:
                    lon = float(jd['lon'])
                    lat = float(jd['lat'])
                    self.addMarker(lat, lon)
                except:
                    pass
        except Exception:
            self.setText("Error: "+jsondata)


        if not self.reverseGeoCodeDialog.isVisible():
            self.show()