简体   繁体   English

导入 csv 时 PyQGIS 更改底图 crs

[英]PyQGIS changing basemap crs when importing a csv

I am using PyQGIS to import a csv file with a lat and long, when doing this I am using the appropriate crs of EPSG:4326.我正在使用 PyQGIS 导入具有纬度和经度的 csv 文件,这样做时我使用的是 EPSG:4326 的适当 crs。 I'm plotting this onto Google Maps.我正在将其绘制到谷歌地图上。

I load my basemap, then import my CSV.我加载我的底图,然后导入我的 CSV。 The issue is that my basemap projection then changes to 4326 and I need it to remain on 3857.问题是我的底图投影然后更改为 4326,我需要它保持在 3857。

I've tried importing the basemap after the CSV and moving it down in the layers, however this still changes the projections.我尝试在 CSV 之后导入底图并将其向下移动到图层中,但这仍然会改变投影。

import requests
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from qgis.core import *
from qgis.utils import iface
from qgis import core

#Use Google Street Map as QGIS basemap.
service_url = "mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}" 
service_uri = "type=xyz&zmin=0&zmax=21&url=https://"+requests.utils.quote(service_url)
tms_layer = iface.addRasterLayer(service_uri, "GoogleSat", "wms")

#Import CSV and plot.
uri = 'file:///home/user/fred.csv?type=csv&xField=%s&yField=%s&crs=%s' % ("Site Longitude", "Site Latitude", "EPSG:4326")
layer_csv = QgsVectorLayer(uri, 'fred', 'delimitedtext')
layer_csv.isValid()
QgsProject.instance().addMapLayer(layer_csv)

I'll be the first to admit I'm a novice with QGIS!我将是第一个承认我是 QGIS 的新手的人!

It seems this has something to do with the application not refreshing properly as mentioned in this answer on gis stack.似乎这与应用程序没有正确刷新有关,如 gis 堆栈上的答案中所述。 You may want to look into it for details.您可能需要查看详细信息。

To answer your question in brief, you can add QApplication.instance().processEvents() after QgsProject.instance().addMapLayer(layer_csv) and then use setCrs() to set your basemap CRS to whatever value you need.为了简要回答您的问题,您可以在QgsProject.instance().addMapLayer(layer_csv)之后添加QApplication.instance().processEvents() ,然后使用setCrs()将底图 CRS 设置为您需要的任何值。 It will hold.它会举行。

proj = QgsProject.instance()
proj.addMapLayer(layer_csv)

# This line makes the difference
QApplication.instance().processEvents()

# This sets the project CRS back to 3857
proj.setCrs(QgsCoordinateReferenceSystem(3857))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM