I'm using QGIS and I would like to measure the distance between the centroid of King County in the US and the centroids of all other US counties. I have imported the shapefile and I have executed the "centroid" tool. However, I am not able to set "King County" as a starting point. When I do "Distance Matrix", there is no way to set King County as the starting point. I would like to have "King County" as the reference point and then measure the distance from it to all other counties.
1 Answer
The best way to calculate this is SQL Spatial, which you can access on a shapefile from the QGIS DB Manager SQL Panel, which treats your shapefile as a 'virtual layer' in which you can run SQLite spatial functions.
For my example, I want to find the distance from the centroid of Denver county to the centroid of all other counties in CO:
Here is the SQL:
select
d.name as "from "
, c.name as "to"
, ST_Distance(ST_Centroid(d.geometry), ST_Centroid(c.geometry)) as "dist_dd"
from co_counties as c
, co_counties as d
where 1=1
and d.name = 'Denver'
and c.name != 'Denver'
The SQL basically sets up the same layer twice: c, and d using commas to select both tables, rather than joining them.
I can then alias both tables, then set which features from which table I want to use:
- c is the state without denver
- d is just denver
Then use the ST_Distance function on both the geometries, while converting both to centroid points using ST_Centroid.
Note: my data is in WGS84, so the distance is fairly meaningless.
However, if your data is in a USA-level projected coordinate system, this will work.
PostGIS would be the ideal system if you had to do this more often.