Wednesday 29 April 2015

qgis - Get median distance from a bunch of points from a assigned location and draw buffer accordingly



I have 2 point layers, say layer A and Layer B


Layer A with a bunch of points, Layer B with a single point.


I first need to measure all the distances between every single point in layer A and the point in layer B, Then draw a buffer of median distance, 20 percentile distance, 30 percentile distance etc.


How do I achieve this in bulk in QGIS?


The output will be like: enter image description here



Answer



You could create a Virtual Layer with the following query:


WITH distances AS(
SELECT
b.fid b_fid,

a.fid a_fid,
ST_Distance(b.geometry,a.geometry) dist
FROM layer_B b
CROSS JOIN layer_A a
),
percentiles AS(
SELECT
b_fid,
a_fid,
dist,

NTILE(10) OVER(
PARTITION BY b_fid
ORDER BY dist)*10 percentile
FROM distances
),
radii AS(
SELECT
b_fid,
percentile,
MAX(dist) radius

FROM percentiles
GROUP BY b_fid, percentile
)
--SELECT * FROM distances;
--SELECT * FROM percentiles;
--SELECT * FROM radii;
-- to debug, comment the following lines and uncomment the previous clause of interest
SELECT
r.b_fid,
r.percentile,

r.radius,
ST_Buffer(b.geometry,r.radius) geom
FROM layer_B b
INNER JOIN radii r
ON b.fid = r.b_fid
WHERE
(r.percentile = 20
OR r.percentile = 30
OR r.percentile = 50);




The previous query will work for one or more features in layer_B.


We are creating a table (distances) with all distances from all points in layer B to all points in layer A.


Then, we are creating a table (percentiles) with 10 groups of distances for each point in layer B.


Next, we are creatting the radii table selecting the maximum distance from each group of percentiles.


Finally, we are creating a buffer for each point in layer B and each radius of radii table, but filtering them to only those with percentiles 20, 30 and 50.




Notes:





  • I am assuming the layer_A and layer_B names of the source layers. Also, I am assuming fid and geometry field names (GeoPackage defaults). Replace that names in the query to match your layer and field names.




  • A virtual layer is stored in the project and is dinamically updated every time a source layer change. Export it to a file if features in source layers will not change.




No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...