In QGIS 3.10.4, I have two shapefiles (polyline and polygon, layer name
'lines' respectively), look like below:
My goal is to calculate the perpendicular distance from the centroid of each region to each of the lines. I've tried the two methods in this thread: Creating dummy variables between layers based on their geometries in QGIS, which are: using NNJoin, or using query in a Virtual Layer.
However, I met some problems with both of the methods:
- NNJoin (I selected the option
"Approximate geometries by centroids"): the distances are in decimal degrees because the join layer (polyline layer) uses Geographic CRS. It's hard to interpret the distances and I wasn't able to figure out how to convert Geographic CRS to Projected CRS. Any idea how can I solve this problem?
- Then I tried the following query (provided by @Taras) in
Add Layer -> Add/Edit Virtual Layer, it successfully generates a Virtual Layer with a "distance" column, with one distance associated with one region:
SELECT "boundaries".*, ROUND(ST_Length(ST_ShortestLine("boundaries".geometry, "lines".geometry)),2) AS distance FROM "boundaries", "lines" GROUP BY "boundaries".id ORDER BY MIN(ST_Length(ST_ShortestLine("boundaries".geometry, "lines".geometry)))
So my ultimate question is: how can I calculate the perpendicular distance (in km or mile) from the centroids of each region on the polygon to each line of the polyline?