在PyQGIS中定义层CRS并避免CRS对话框?


Answers:


8

我用这种方式解决了类似的问题:

from qgis.core import *
from qgis.gui import *

layer = QgsVectorLayer(self.shpFilePath, "Track", "ogr")
crs = layer.crs()
crs.createFromId(4326)
layer.setCrs(crs)
QgsMapLayerRegistry.instance().addMapLayer(layer)

4
但是它仍然问我对话框中的CRS吗?
MustafaUçar18年

出现“ CRS”对话框!
罗伯托·马佐奇


6

基于此博客文章和答案,如何在pyqgis中指定栅格图层的CRS?,您可以通过这种方式实现您想要的:

settings = QSettings()
# Take the "CRS for new layers" config, overwrite it while loading layers and...
oldProjValue = settings.value( "/Projections/defaultBehavior", "prompt", type=str )
settings.setValue( "/Projections/defaultBehavior", "useProject" )

# YOUR CODE TO LOAD THE LAYER GOES HERE

# ... then set the "CRS for new layers" back
settings.setValue( "/Projections/defaultBehavior", oldProjValue )

注意:如果仍在使用QGIS v2.x(顺便说一句,您不应该:P),请改用变量名“ / Projections / defaultBehaviour”。


5

以下代码应允许您添加一个矢量层,而不会出现CRS弹出窗口(至少对我而言不会出现):

from qgis import *
from qgis.utils import *

#replace "shapefile_path" with your layer's path; replace "Layer_name" with whatever name you want to give the layer in the TOC
qgis.utils.iface.addVectorLayer("shapefile_path", "Layer_name", "ogr")

#Use loaded layer as active layer to set the CRS
myLayer = qgis.utils.iface.activeLayer()
myLayer.setCrs(QgsCoordinateReferenceSystem(4326, QgsCoordinateReferenceSystem.EpsgCrsId))

#Sets canvas CRS
my_crs = core.QgsCoordinateReferenceSystem(4326, core.QgsCoordinateReferenceSystem.EpsgCrsId)
iface.mapCanvas().mapRenderer().setDestinationCrs(my_crs)

只需将4326两种情况下的CRS值更改为您选择的授权机构ID,如图所示:

CRS选项


1
感谢您的回答!但是主要的问题是,当我加载图层时,会出现一个对话框,供我选择crs。是否可以隐藏或禁用它?
Hinne123

编辑我的帖子,当我运行命令时,我没有收到对话窗口。希望你也不会!
约瑟夫

2
仅当未在代码中设置CRS时,才会显示CRS窗口。只要您设置它,您就会很好。
BritishSteel

@BritishSteel-感谢您提及!我不知道是这种情况。
约瑟夫

3

几个月后,我找到了解决方案。您应该在脚本的开头和结尾添加两行,该脚本来自@Domokos Endre:

import os

iface.mainWindow().blockSignals(True)

layer = QgsVectorLayer(path, "My Layer",  "ogr")
crs = layer.crs()
crs.createFromId(32637)  # Whatever CRS you want
layer.setCrs(crs)

QgsProject.instance().addMapLayer(layer)
iface.mainWindow().blockSignals(False)

1

对我来说,以上任何解决方案都行不通。也许是因为我正在将csv加载为矢量层,而不是形状文件。使它起作用的唯一方法是:

crs = QgsCoordinateReferenceSystem(2180)
self.iface.mapCanvas().mapRenderer().setDestinationCrs(crs)
vlayer = QgsVectorLayer(filePath, "layer name", "ogr")
vlayer.setCrs(QgsCoordinateReferenceSystem(2180))

0

此答案描述了如何通过首先在URL中指定CRS来避免此对话框,该URL用于将文件加载到内存中。因此addVectorLayer()QgsVectorLayer与其直接传递Shapefile路径,不如创建具有适当URL的,然后调用addMapLayer()

import urlparse
import urllib

baseuri = urlparse.urljoin('file:', urllib.pathname2url(self.shpFilePath))
uri = baseuri + "?crs=EPSG:4326"
vlayer = QgsVectorLayer(uri, "result", "memory")
QgsMapLayerRegistry.instance().addMapLayer(vlayer)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.