Python qgis.core.QgsCoordinateReferenceSystem() Examples
The following are 20
code examples of qgis.core.QgsCoordinateReferenceSystem().
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: Map.py From qgis-earthengine-plugin with MIT License | 8 votes |
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 #2
Source File: mgrstogeom.py From qgis-latlontools-plugin with GNU General Public License v2.0 | 7 votes |
def processAlgorithm(self, parameters, context, feedback): source = self.parameterAsSource(parameters, self.PrmInputLayer, context) mgrsfieldname = self.parameterAsString(parameters, self.PrmMgrsField, context) if not mgrsfieldname: msg = 'Select an MGRS field to process' feedback.reportError(msg) raise QgsProcessingException(msg) epsg4326 = QgsCoordinateReferenceSystem("EPSG:4326") (sink, dest_id) = self.parameterAsSink( parameters, self.PrmOutputLayer, context, source.fields(), QgsWkbTypes.Point, epsg4326) featureCount = source.featureCount() total = 100.0 / featureCount if featureCount else 0 badFeatures = 0 iterator = source.getFeatures() for cnt, feature in enumerate(iterator): if feedback.isCanceled(): break m = feature[mgrsfieldname] try: m = re.sub(r'\s+', '', str(m)) # Remove all white space lat, lon = mgrs.toWgs(m) except Exception: # traceback.print_exc() badFeatures += 1 continue f = QgsFeature() f.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(lon, lat))) f.setAttributes(feature.attributes()) sink.addFeature(f) if cnt % 100 == 0: feedback.setProgress(int(cnt * total)) if badFeatures > 0: msg = "{} out of {} features contained MGRS coordinates".format(featureCount - badFeatures, featureCount) feedback.pushInfo(msg) return {self.PrmOutputLayer: dest_id}
Example #3
Source File: utm.py From qgis-latlontools-plugin with GNU General Public License v2.0 | 7 votes |
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 #4
Source File: utils.py From qgis-earthengine-plugin with MIT License | 7 votes |
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 #5
Source File: rb_result_renderer.py From quickmapservices with GNU General Public License v2.0 | 6 votes |
def __init__(self): self.iface = iface self.srs_wgs84 = QgsCoordinateReferenceSystem(4326) self.transform_decorator = QgsCoordinateTransform(self.srs_wgs84, self.srs_wgs84) self.rb = QgsRubberBand(self.iface.mapCanvas(), QGisGeometryType.Point) self.rb.setColor(QColor('magenta')) self.rb.setIconSize(12) self.features_rb = QgsRubberBand(self.iface.mapCanvas(), QGisGeometryType.Point) magenta_transp = QColor('#3388ff') magenta_transp.setAlpha(120) self.features_rb.setColor(magenta_transp) self.features_rb.setIconSize(12) self.features_rb.setWidth(2)
Example #6
Source File: spatialiteDb.py From DsgTools with GNU General Public License v2.0 | 6 votes |
def insertFrame(self, scale, mi, inom, frame): self.checkAndOpenDb() srid = self.findEPSG() geoSrid = QgsCoordinateReferenceSystem(int(srid)).geographicCRSAuthId().split(':')[-1] ogr.UseExceptions() outputDS = self.buildOgrDatabase() outputLayer=outputDS.GetLayerByName('public_aux_moldura_a') newFeat=ogr.Feature(outputLayer.GetLayerDefn()) auxGeom = ogr.CreateGeometryFromWkb(frame) #set geographic srid from frame geoSrs = ogr.osr.SpatialReference() geoSrs.ImportFromEPSG(int(geoSrid)) auxGeom.AssignSpatialReference(geoSrs) #reproject geom outSpatialRef = outputLayer.GetSpatialRef() coordTrans = osr.CoordinateTransformation(geoSrs, outSpatialRef) auxGeom.Transform(coordTrans) newFeat.SetGeometry(auxGeom) newFeat.SetField('mi', mi) newFeat.SetField('inom', inom) newFeat.SetField('escala', str(scale)) out=outputLayer.CreateFeature(newFeat) outputDS.Destroy()
Example #7
Source File: inspectFeatures.py From DsgTools with GNU General Public License v2.0 | 6 votes |
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 #8
Source File: mapillary_image_info.py From go2mapillary with GNU General Public License v3.0 | 6 votes |
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: mapillary_filter.py From go2mapillary with GNU General Public License v3.0 | 5 votes |
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 #10
Source File: mapillary_coverage.py From go2mapillary with GNU General Public License v3.0 | 5 votes |
def setDefaultLayers(self): defaultContent = '{"type": "FeatureCollection", "features": []}' for ld in LAYER_LEVELS: with open(os.path.join(self.cache_dir, 'mapillary_%s.geojson' % ld), 'w') as f: f.write(defaultContent) defLyr = QgsVectorLayer(os.path.join(self.cache_dir, 'mapillary_%s.geojson' % ld),"Mapillary "+ld, "ogr") defLyr.setCrs(QgsCoordinateReferenceSystem(4326)) setattr(self, ld+'Layer', defLyr)
Example #11
Source File: mapillary_coverage.py From go2mapillary with GNU General Public License v3.0 | 5 votes |
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 #12
Source File: Map.py From qgis-earthengine-plugin with MIT License | 5 votes |
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 #13
Source File: digitizer.py From qgis-latlontools-plugin with GNU General Public License v2.0 | 5 votes |
def crsTriggered(self, action): self.crsButton.setDefaultAction(action) self.inputProjection = action.data() if self.inputProjection == 3: selector = QgsProjectionSelectionDialog() selector.setCrs(QgsCoordinateReferenceSystem(self.inputCustomCRS)) if selector.exec(): self.inputCustomCRS = selector.crs().authid() else: self.inputCustomCRS = 'EPSG:4326' self.saveSettings()
Example #14
Source File: acquisitionFreeController.py From DsgTools with GNU General Public License v2.0 | 5 votes |
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 #15
Source File: acquisitionFreeController.py From DsgTools with GNU General Public License v2.0 | 5 votes |
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 #16
Source File: abstractDb.py From DsgTools with GNU General Public License v2.0 | 5 votes |
def insertFrame(self, scale, mi, inom, frame, paramDict = dict()): self.checkAndOpenDb() srid = self.findEPSG() geoSrid = QgsCoordinateReferenceSystem(int(srid)).geographicCrsAuthId().split(':')[-1] sql = self.gen.insertFrame(scale, mi, inom, frame, srid, geoSrid, paramDict = paramDict) self.db.transaction() query = QSqlQuery(self.db) if not query.exec_(sql): self.db.rollback() self.db.close() raise Exception(self.tr('Problem inserting frame: ') + query.lastError().text()) self.db.commit() # self.db.close()
Example #17
Source File: utm.py From qgis-latlontools-plugin with GNU General Public License v2.0 | 5 votes |
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 #18
Source File: reverseGeocode.py From qgis-bulk-nominatim with GNU General Public License v2.0 | 5 votes |
def __init__(self, iface, settings): self.canvas = iface.mapCanvas() QgsMapTool.__init__(self, self.canvas) self.iface = iface self.settings = settings self.reverseGeoCodeDialog = ReverseGeocodeDialog(self, self.iface, self.iface.mainWindow()) self.iface.addDockWidget(Qt.TopDockWidgetArea, self.reverseGeoCodeDialog) self.reverseGeoCodeDialog.hide() self.epsg4326 = QgsCoordinateReferenceSystem('EPSG:4326') self.marker = None # Set up a polygon/line rubber band self.rubber = QgsRubberBand(self.canvas) self.rubber.setColor(QColor(255, 70, 0, 200)) self.rubber.setWidth(5) self.rubber.setBrushStyle(Qt.NoBrush)
Example #19
Source File: settings.py From qgis-latlontools-plugin with GNU General Public License v2.0 | 4 votes |
def readSettings(self): '''Load the user selected settings. The settings are retained even when the user quits QGIS. This just loads the saved information into varialbles, but does not update the widgets. The widgets are updated with showEvent.''' qset = QSettings() ### CAPTURE SETTINGS ### self.captureProjection = int(qset.value('/LatLonTools/CaptureProjection', self.ProjectionTypeWgs84)) self.delimiter = qset.value('/LatLonTools/Delimiter', ', ') self.dmsPrecision = int(qset.value('/LatLonTools/DMSPrecision', 0)) self.coordOrder = int(qset.value('/LatLonTools/CoordOrder', self.OrderYX)) self.wgs84NumberFormat = int(qset.value('/LatLonTools/WGS84NumberFormat', 0)) self.otherNumberFormat = int(qset.value('/LatLonTools/OtherNumberFormat', 0)) self.plusCodesLength = int(qset.value('/LatLonTools/PlusCodesLength', 10)) self.decimalDigits = int(qset.value('/LatLonTools/DecimalDigits', 8)) self.capturePrefix = qset.value('/LatLonTools/CapturePrefix', '') self.captureSuffix = qset.value('/LatLonTools/CaptureSuffix', '') ### ZOOM TO SETTINGS ### self.zoomToCoordOrder = int(qset.value('/LatLonTools/ZoomToCoordOrder', self.OrderYX)) self.zoomToProjection = int(qset.value('/LatLonTools/ZoomToCoordType', 0)) self.persistentMarker = int(qset.value('/LatLonTools/PersistentMarker', Qt.Checked)) self.zoomToCustomCrsAuthId = qset.value('/LatLonTools/ZoomToCustomCrsId', 'EPSG:4326') self.zoomToProjectionSelectionWidget.setCrs(QgsCoordinateReferenceSystem(self.zoomToCustomCrsAuthId)) ### MULTI-ZOOM CUSTOM QML STYLE ### self.multiZoomToProjection = int(qset.value('/LatLonTools/MultiZoomToProjection', 0)) self.multiCoordOrder = int(qset.value('/LatLonTools/MultiCoordOrder', self.OrderYX)) self.multiZoomNumCol = int(qset.value('/LatLonTools/MultiZoomExtraData', 0)) self.multiZoomStyleID = int(qset.value('/LatLonTools/MultiZoomStyleID', 0)) self.qmlStyle = qset.value('/LatLonTools/QmlStyle', '') if (self.multiZoomStyleID == 2) and (self.qmlStyle == '' or self.qmlStyle is None or not os.path.isfile(self.qmlStyle)): # If the file is invalid then set to an emply string qset.setValue('/LatLonTools/QmlStyle', '') qset.setValue('/LatLonTools/MultiZoomStyleID', 0) self.qmlStyle = '' self.multiZoomStyleID = 0 ### BBOX & EXTERNAL MAP SETTINGS ### settings.readSettings() self.setEnabled()
Example #20
Source File: settings.py From qgis-latlontools-plugin with GNU General Public License v2.0 | 4 votes |
def __init__(self, lltools, iface, parent): super(SettingsWidget, self).__init__(parent) self.setupUi(self) self.lltools = lltools self.iface = iface self.canvas = iface.mapCanvas() self.buttonBox.button(QDialogButtonBox.RestoreDefaults).clicked.connect(self.restoreDefaults) ### CAPTURE SETTINGS ### self.captureProjectionComboBox.addItems(['WGS 84 (Latitude & Longitude)', 'Project CRS', 'Custom CRS', 'MGRS', 'Plus Codes', 'Standard UTM','Geohash','Maidenhead Grid Locator']) self.captureProjectionSelectionWidget.setCrs(epsg4326) self.wgs84NumberFormatComboBox.addItems(['Decimal Degrees', 'D°M\'S"', 'DDMMSS', 'D°M.MM\'', 'WKT POINT', 'GeoJSON']) self.otherNumberFormatComboBox.addItems(['Normal Coordinate', 'WKT POINT']) self.coordOrderComboBox.addItems(['Lat, Lon (Y,X) - Google Map Order', 'Lon, Lat (X,Y) Order']) self.delimComboBox.addItems(['Comma', 'Comma Space', 'Space', 'Tab', 'Other']) self.captureProjectionComboBox.activated.connect(self.setEnabled) ### ZOOM TO SETTINGS ### self.zoomToProjectionComboBox.addItems(['WGS 84 (Latitude & Longitude) / Auto Detect Format', 'Project CRS', 'Custom CRS', 'MGRS', 'Plus Codes', 'Standard UTM','Geohash','Maidenhead Grid']) self.zoomToProjectionSelectionWidget.setCrs(epsg4326) self.zoomToCoordOrderComboBox.addItems(['Lat, Lon (Y,X) - Google Map Order', 'Lon, Lat (X,Y) Order']) self.zoomToProjectionComboBox.activated.connect(self.setEnabled) ### EXTERNAL MAP ### self.addProviderButton.clicked.connect(self.addUserProvider) self.deleteProviderButton.clicked.connect(self.deleteUserProvider) ### MULTI-ZOOM ### self.multiZoomToProjectionComboBox.addItems(['WGS 84 (Latitude & Longitude)', 'Project CRS', 'Custom CRS', 'MGRS', 'Plus Codes', 'Standard UTM']) self.multiZoomToProjectionComboBox.activated.connect(self.setEnabled) self.multiZoomToProjectionSelectionWidget.setCrs(epsg4326) self.qmlBrowseButton.clicked.connect(self.qmlOpenDialog) self.markerStyleComboBox.addItems(['Default', 'Labeled', 'Custom']) self.multiCoordOrderComboBox.addItems(['Lat, Lon (Y,X) - Google Map Order', 'Lon, Lat (X,Y) Order']) self.qmlStyle = '' ### BBOX CAPTURE SETTINGS ### self.bBoxCrsComboBox.addItems(['WGS 84 (Latitude & Longitude)', 'Project CRS']) self.bBoxFormatComboBox.addItems([ '"xmin,ymin,xmax,ymax" - Using the selected delimiter', '"xmin,xmax,ymin,ymax" - Using the selected delimiter', '"x1 y1,x2 y2,x3 y3,x4 y4,x1 y1" - Polygon format', '"x1,y1 x2,y2 x3,y3 x4,y4 x1,y1" - Alternate polgyon format', 'WKT Polygon', '"bbox: [xmin, ymin, xmax, ymax]" - MapProxy', '"bbox=xmin,ymin,xmax,ymax" - GeoServer WFS, WMS']) self.bBoxDelimiterComboBox.addItems(['Comma', 'Comma Space', 'Space', 'Tab', 'Other']) ### COORDINATE CONVERSION SETTINGS ### self.converterCoordOrderComboBox.addItems(['Lat, Lon (Y,X) - Google Map Order', 'Lon, Lat (X,Y) Order']) self.converterProjectionSelectionWidget.setCrs(epsg4326) self.readSettings() # This has been added because the coordinate capture uses it self.captureProjectionSelectionWidget.setCrs(QgsCoordinateReferenceSystem(settings.captureCustomCrsAuthId))