2

I have a point layer in EPSG:23700, but I want to save coordinates into the attribute table in a different CRS (EPSG: 4326), without transforming/changing the layer (I want to keep it in EPSG:23700).

I would do this in Field Calculator:

x(transform($geometry, layer_property(@layer_id, 'crs'), 'EPSG:4326'))

Is there a way to do this with Python?

Btw. I am saving the original coordinates with this simple code (I want to extend this):

layer = iface.activeLayer()  
selected_feature = layer.selectedFeatures()  
layer.startEditing()  

for feature in selected_feature:  
    feature["EOV_X"] = feature.geometry().asPoint()[0]  
    feature["EOV_Y"] = feature.geometry().asPoint()[1]  
    layer.updateFeature(feature)  

layer.commitChanges()
1

1 Answer 1

4

Add two fields for "Latitude" and "Longitude" and use the following script. It utilizes pyproj.

from pyproj import CRS, Transformer

layer = iface.activeLayer()  
selected_features = layer.selectedFeatures()

layer.startEditing()

tr = Transformer.from_crs(CRS.from_epsg(23700), CRS.from_epsg(4326))

for feature in selected_features:
    
    x = feature.geometry().asPoint()[0]
    y = feature.geometry().asPoint()[1]
    feature["X"] = x
    feature["Y"] = y
    
    lat, lon = tr.transform(x, y)
    feature["Latitude"] = lat
    feature["Longitude"] = lon
       
    layer.updateFeature(feature)  

layer.commitChanges()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.