[GIS] Measure the distance between 2 points

csvdistancepointqgis

This is my first time using QGIS(2.14.18), I construct this map, but I don't know how to measure the distances (D1, D2, D3, Dx …) between the circles and the stars. So I have 2 layers (based in 2 CSV files), with thousands and thousands of lines, the image below is just a test.

The distances I need are only between stars and circles, never between star to star or circle to circle. One star can have infinite circles, but a circle can only have one star link. In the two CSV files exist a key ID that stars and circles share with each other, but I don't know how to use it in QGIS to solve this problem.

test 33

I have tried using the distance matrix in QGIS, but I don't know if I'm doing this right. I think the distance matrix is giving redundant results, like 2 times the same distance or calculating the distances between stars and circles with no link between them.

I need these distances in meters or kilometers, not degrees.

Best Answer

You can do this directly in QGIS using a join and the field calculator.

Do your tables have X/Y information in them? Yes, then go to step 2 else do step 1 first.

  1. Create two new fields in each table and populate with the X and Y coordinates of each point. You can use the field calculator in QGIS and the $x and $y functions to calculate the values.

enter image description here

  1. Join your stars table to the circles table using the keyID. This will give you pairs of points with a structure like circle_id, circle_x, circle_y, stars_star_id, stars_star_x, stars_star_y. Each circle will have a star. (in the image below the distance field has already been calculated. See step 3 below.)

joined tables with all fields

  1. Now you can create a new virtual field in the table called distance and type double and use the field calculator to populate it with the distance to the star from each circle:sqrt(abs(to_int(stars_star_x) - to_int(circle_x))^2 + abs(to_int(stars_star_x) - to_int(circle_y))^2)

virtual field calculator

If you want the lines on the map as well as the distance then the MMQGIS plugin mentioned above has the hub tool.

Or you could do it in PostGIS as answered here: How to create spider diagrams (hub lines) in PostGIS?