I have a polyline shapefile with 166 different line features. How would one populate the attribute table with x and y values of the start and end points of each line?
2 Answers
You have your four columns: X-start; Y-start; X-end; Y-end. Using the field calculator for each column update using:
$x_at(0)
$x_at(-1)
$y_at(0)
$y_at(-1)
This asks for the coordinate at the start of the line (the zero) and the end of the line (the negative one). This will provide you with a decimal latitude and longitude, so ensure the columns are floats.
EDIT: Thanks to the_darkside's comments please note this won't work on multi lines, due to the multiple beginnings and ends.
-
When I input these expressions, I get the error: expression is invalid. Any possible reason? Commented Jun 24, 2016 at 11:04
-
And when I use the expression
xat(0)
I get the following error:An error occurred while evaluating the calculation string: Index is out of range
Commented Jun 24, 2016 at 11:07 -
index being out of range sounds like you don't have anything for the expression to work on. I've not had this problem before. A couple of things you could check: your using the expression on a line? the columns being updated are the right data type? projection(??) is in metres? Commented Jun 24, 2016 at 11:15
-
Oh I understand why, it's because its a multipart feature so there are multiple start and end points Commented Jun 24, 2016 at 11:16
In the attribute view create your new columns as decimal (floats).
Then enable editing, and use expressions to update the columns.
To get the latitude (x-coordinate) of the start of a line feature, use the expression x_at(0)
. To get the end of a line feature use x_at(-1)
. Repeat for your longitudes (y-coordinates). You select the column, type in the expression, and hit "Update All".
This assumes your data is in lat-long (ESPG:4326 most likely). If not, transform to that and save, or transform within the expression. Here my data is in EPSG:27700 and I want lat-long (EPSG:4326):
x(
start_point(
transform( $geometry, 'EPSG:27700', 'EPSG:4326' )
)
)
Replace x
with y
and start_point
with end_point
for your four columns.