Skip to content

Instantly share code, notes, and snippets.

@tohka
Last active November 13, 2018 14:45
Show Gist options
  • Save tohka/ac80011db4d451b3d82cfd7b5765c7f9 to your computer and use it in GitHub Desktop.
Save tohka/ac80011db4d451b3d82cfd7b5765c7f9 to your computer and use it in GitHub Desktop.
def transformLayer(layer = None, crs = None, addToCanvas = False):
"""
QGIS 3.x で、参照系を変換した一時レイヤを作成する。
Parameters
----------
layer : None, str or QgsVectorLayer, default None
変換もとのレイヤ。 None だとアクティブレイヤが選択される。
文字列を指定すると、レイヤ名あるいはソース名で検索し
最初にみつかったレイヤが選択される。
QgsVectorLayer オブジェクトを指定することもできる。
crs : None, str or QgsCoordinateReferenceSystem, default None
新しく作る一時レイヤの CRS 。
None だと現在のプロジェクトの CRS を利用する。
文字列を指定する場合 "EPSG:6677" 等の形式で指定する。形式について
詳しくは QgsCoordinateReferenceSystem::createFromString を参照。
QgsCoordinateReferenceSystem オブジェクトを指定することもできる。
addToCanvas : bool, default True
一時レイヤをキャンバスに追加するか、
Returns
-------
tempLayer : QgsVectorLayer or None
作成した一時レイヤ
"""
if layer is None:
layer = iface.activeLayer()
if not isinstance(layer, QgsVectorLayer):
return None
elif isinstance(layer, QgsVectorLayer):
None
elif isinstance(layer, str):
for l in QgsProject.instance().mapLayers().values():
if isinstance(l, QgsVectorLayer) and (l.name() == layer or l.source() == layer):
layer = l
break
if not isinstance(layer, QgsVectorLayer):
return None
else:
return None
if crs is None:
crs = QgsProject.instance().crs()
elif isinstance(crs, QgsCoordinateReferenceSystem):
None
elif isinstance(crs, str):
crs = QgsCoordinateReferenceSystem(crs)
else:
return None
if not crs.isValid():
return None
authid = crs.authid()
srsid = crs.srsid()
proj4 = crs.toProj4()
if authid is not None and len(authid) > 0:
crsstr = "?crs=" + authid
elif srsid is not None and srsid > 0:
crsstr = "?crs=INTERNAL:" + str(srsid)
elif proj4 is not None and len(proj4) > 0:
crsstr = "?crs=PROJ4:" + proj4
else:
return None
tempLayer = QgsVectorLayer(QgsWkbTypes.displayString(layer.wkbType()) + crsstr, "__" + layer.name(), "memory")
tempLayer.setProviderEncoding(layer.dataProvider().encoding())
ct = QgsCoordinateTransform(layer.crs(), crs, QgsProject.instance())
tempLayer.startEditing()
for f in layer.fields():
tempLayer.addAttribute(QgsField(f))
tempLayer.commitChanges()
tempLayer.startEditing()
for f in layer.getFeatures():
dstf = QgsFeature(f)
geom = dstf.geometry()
geom.transform(ct)
dstf.setGeometry(geom)
tempLayer.dataProvider().addFeatures([dstf])
tempLayer.commitChanges()
if addToCanvas:
QgsProject.instance().addMapLayer(tempLayer)
return tempLayer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment