Generate Latitude/Longitude from Geometry Polygon using QGIS
In this post, we demonstrate the process of generating latitude and longitude coordinates using the $x and $y expressions in QGIS software. We assume that the geometry of the GeoPackage (.gpkg) file is based on polygon data rather than point data.
Verification
To verify that the geometry in your GeoPackage file is based on polygons, use the following Python code snippet.
import geopandas as gp
data = gp.read_file("/mnt/d/Data/20231101.gpkg")
#print top row
data.head()
Lat/Long Generation
Now, it’s time to generate latitude and longitude fields using the geometry of the given dataset.
Step 1. Open the .gpkg file in QGIS and wait for the data to load completely. Please make sure the correct layer is selected in the Layers window.
Step 2. Now, open the Field Calculator from the toolbar and create a new field called ‘Longitude’ with the following options, then click OK.
Create a new field: True
output field type: Decimal Number
Expression:x(transform(centroid($geometry), @layer_crs, 'EPSG:4326'))
Preview: It Should'nt be null or empty
Step 3. Now, open the Field Calculator again and create another field called ‘Latitude’ with the following options, then click OK.
Create a new field: True
output field type: Decimal Number
Expression:y(transform(centroid($geometry), @layer_crs, 'EPSG:4326'))
Preview: It Should'nt be null or empty
EPSG: 4326 uses a coordinate system on the surface of a sphere or ellipsoid of reference. (degrees 3D sphere)
EPSG: 3857 uses a coordinate system PROJECTED from the surface of the sphere or ellipsoid to a flat surface. (metres 2D projection)
Note:- Using the above two expressions, we are actually converting the coordinate system from a flat map to a globe (curved surface).
View & Export Lat/Long
To view the newly generated fields, right-click on the layer and select the ‘Open Attribute Table’ option.
To export the layer as a CSV file, choose the Export -> Save Features As option. If you’d like to extract latitude and longitude using Python code, please let me know.
I’m hoping this blog we save time and energy, Thanks !
Feel free to contact me:
→ https://www.linkedin.com/in/saqib-ullah-siddiqui/
→ saqibullah@gmail.com