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.
-
4Please state which CRS your using, which feature type you have and which field type your coordinate fields have when you try to create them. – Erik Apr 29 '20 at 10:54
-
2If you were using field calculator or created a new field in qgis make sure the length of the field is greater than 0 – she_weeds Apr 30 '20 at 22:57
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.
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".
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.
Possible solution by means of PyQGIS.
Let's assume there is a point layer called "points"
with it's attribute table, see image below.
Proceed with Plugins > Python Console > Show Editor
and paste the script below
# 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!")
layer_provider = layer.dataProvider()
# adding new fields
for attr in ["X_Coord", "Y_Coord"]:
layer_provider.addAttributes([QgsField(attr, QVariant.Double)])
layer.updateFields()
# starting layer editing
layer.startEditing()
for feature in layer.getFeatures():
fields = layer.fields() # accessing layer fields
attrs = {
fields.indexFromName("X_Coord"): feature.geometry().asPoint()[0],
fields.indexFromName("Y_Coord"): feature.geometry().asPoint()[1]
}
layer_provider.changeAttributeValues({feature.id(): attrs})
layer.commitChanges()
Press Run script
and get the output that will look like
References: