6

I have a series of polygons (lakes) in Kansas, Oklahoma and a few in Texas. I created centroids for each lake, which I needed 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 several 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 x,y coordinates to Attribute table in QGIS), 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
    Commented 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
2

A possible solution using PyQGIS.

An Extension to the answer provided in this thread Adding x,y coordinates to Attribute table in QGIS. The above solution is primarily based on the QgsCoordinateTransform class.

Use this script:

# imports
from qgis.core import QgsProject, QgsCoordinateReferenceSystem, QgsCoordinateTransform, QgsField
from PyQt5.QtCore import QVariant

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

# 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())

# accessing point layer's provider
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 cars

    # accessing new geometry as a point
    geom_pt = feature.geometry().asPoint()

    attrs = {
        fields.indexFromName("lat"): round(geom_pt[1], 6),
        fields.indexFromName("lon"): round(geom_pt[0], 6)
    }

    layer_provider.changeAttributeValues({feature.id(): attrs})

layer.commitChanges()

to get the following output:

result


References:

0

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.