TransWikia.com

Getting lat/long for centroids using QGIS

Geographic Information Systems Asked by gwfami on August 24, 2021

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.

2 Answers

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):

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

and

y(transform( make_point (x(centroid($geometry)),y(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. This expression should work without any changes with whatever vector layer you use:

x(transform( make_point (x(centroid($geometry)),y(centroid($geometry))),  @map_crs , 'EPSG:4326'))

and

y(transform( make_point (x(centroid($geometry)),y(centroid($geometry))),  @map_crs , 'EPSG:4326'))

Correct answer by Babel on August 24, 2021

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:

Answered by Taras on August 24, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP