6

I have a series of polygons (lakes) in Kansas, Oklahoma and a few in Texas. I created centroids of each lake, which I need for distance measurements.

These centroids have derived lat/long information when they are clicked, but I am unable to get the same information added to the attribute table.

After doing research, I see that a number of people have had similar problems with the lat/long. I did manage to get some sort of location in the attribute table, similar to this (Adding coordinates to attribute table), but I'm unable to get them converted to actual longitude/latitude.

1
  • 1
    you can use the processing toolbox and use Add X/Y Fields to Layer after reproject
    – Mapperz
    Jul 15, 2020 at 20:50

2 Answers 2

16

Inserting new fields with the field calculator and the expression $x and $y on the layer with your centroids should do the job. If you use the polygon layer of your lakes, you might include there lat/lon in the attribute table directly with x(centroid($geometry)) resp. y(centroid($geometry)).

If your layer is not in EPSG 4326, you can use this expression to reproject the coordinates and get lat/lon-coordinates (replace XXXX with the EPSG-code of your CRS). For latitude

y(transform(centroid($geometry), 'EPSG:XXXX', 'EPSG:4326'))

and for longitude

x(transform(centroid($geometry), 'EPSG:XXXX', 'EPSG:4326'))

Or even better: include the EPSG-code of your project with the corresponding variable, so you don't even have to know about what EPSG you are using and the result is always correct, even when changing the project CRS. These expressions should work without any changes with whatever vector layer you use:

x(transform(centroid($geometry), @layer_crs, 'EPSG:4326'))
y(transform(centroid($geometry), @layer_crs, 'EPSG:4326'))
0
1

Possible solution by means of PyQGIS. An Extension to the answer provided in this thread Adding coordinates to attribute table.

Use the following script instead

# imports
from PyQt5.QtCore import QVariant

# accessing point layer by name
layer = QgsProject.instance().mapLayersByName('test')[0]

if not layer.isValid():
    print("Layer failed to load!")

# specifying input/output crs and setting up constructor
crsSrc = QgsCoordinateReferenceSystem(layer.crs()) # source crs
crsDest = QgsCoordinateReferenceSystem(4326) # destination crs
transform = QgsCoordinateTransform(crsSrc, crsDest, QgsProject.instance()) 

layer_provider = layer.dataProvider()

# adding new fields
for attr in ["lat", "lon"]:
  layer_provider.addAttributes([QgsField(attr, QVariant.Double)])
layer.updateFields()

# starting layer editing
layer.startEditing()

for feature in layer.getFeatures():
    fields = layer.fields() # accessing layer's fields
   
    geom = feature.geometry() # accessing feature's geometry
    geom.transform(transform) # transforming feature's geometry
    feature.setGeometry(geom) # setting feature's geometry in a new crs
    
    attrs = {
            fields.indexFromName("lat"): round(feature.geometry().asPoint()[1],6),
            fields.indexFromName("lon"): round(feature.geometry().asPoint()[0],6)
            }
    layer_provider.changeAttributeValues({feature.id(): attrs})

layer.commitChanges()

Get the output that will look like

result


References:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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