6

If I use the 'Add coordinates to point' it adds the coordinates to in the file, however splits the data into the amount of objects in the original file. If I try to add separate columns in the attribute file calling them 'Coordinate X' or 'Y', then using the $x or $y expression, the output is just NULL. I need to coordinates but all in one file.

Taras
  • 32,823
  • 4
  • 66
  • 137
David Peacock
  • 79
  • 1
  • 1
  • 3

3 Answers3

12

Use a built-in tool "Add X/Y fields to layer"

There you can choose a coordinate system in which you want your coordinates and add an optional field prefix.

enter image description here

Taras
  • 32,823
  • 4
  • 66
  • 137
Trnovstyle
  • 436
  • 3
  • 3
10

Under assumption that you have some kind of a vector layer (such as GeoJSON or something similar) I provide an explanation on the example of a GeoJSON file that contains point features. You didn't provide information how did you calculate fields X and Y. You should use Field calculator. See hovered icon in the first figure.

First, right click on the vector layer and "Open attribute table" and it will open like this.

Attribute table

After you click on Field calculator icon another window will appear. I've put all parameters that you would need to create a new field with X coordinate (Note I named my field E -> easting instead of X). You can also edit existing attribute by ticking "Create new field" checkbox. This will enable the listbox on the right side of the form "Update existing field".

Creating a new field using field calculator

After you repeat the procedure for Y, you get attribute table with updated set of attributes as you can see in an image below.

Don't forget to save your edits. These edits will remain permanent in your file.

Saša Vranić
  • 634
  • 3
  • 13
7

A possible solution using PyQGIS.

Let's assume there is a point layer called 'points' with its attribute table, see image below.

input

Proceed with Plugins > Python Console > Show Editor (Ctrl+Alt+P) and paste the script below

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

getting point layer by its name

layer = QgsProject.instance().mapLayersByName('test')[0]

accessing point layer's provider

layer_provider = layer.dataProvider()

adding new fields

for attr in ["X_Coord", "Y_Coord"]: layer_provider.addAttributes([QgsField(attr, QVariant.Double)]) layer.updateFields()

layer.startEditing()

looping over each feature

for feature in layer.getFeatures(): # accessing layer fields fields = layer.fields()

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

attrs = {
    fields.indexFromName("X_Coord"): geom_pt[0],
    fields.indexFromName("Y_Coord"): geom_pt[1]
}

# changing attribute records
layer_provider.changeAttributeValues({feature.id(): attrs})

layer.commitChanges()

Press Run script run script and get the output that will look like

result


References:

Taras
  • 32,823
  • 4
  • 66
  • 137