I have two shapefiles that I want to spatial join (closest match), however, in the second shapefile I have records that are split by attribute X.  I want the closest to records from each unique X record to shapefile nodes. i.e. the closest match usually pick the closest record from shapefile 2 to shapefile 1 nodes, but I want the closest from each X attribute value to each of shapefile 1 nodes.

An example would be: Shapefile 1: different schools around the city. Shapefile 2: Kids around the city Attribute X: Age category (1,2,3). I want the closest kid from each age category to every school.

How could this be done?


This example, using QGIS, requires four steps to go...

Before starting, please download and install refFunctions plugin.

enter image description here

Provided we have an example of three schools and nine children dataset like below:

  • school_layer: id (1,2,...) and school_id (School_A, ...)
  • kids_layer: id (1,2,...), kids_id (a, b, ...) and kid_age (1, 2, ...)

(1) Split kids_layer into three sublayers according to their age group.

QGIS Processing Toolbox | QGIS | Vector general tools | Split vector layer

enter image description here

I chose \GIS\temp\kids folder to save sublayers, but any place is fine.

(2) Load the sublayers (~.shp) into QGIS.

enter image description here

(3) Open the attribute table of school_layer and create a new field (age_1), by the following expression:

geomnearest('kids_layer_kid_age_1', 'kids_id')

enter image description here

(4) Repeat the above (3) for age_2 and age_3, too.

[age_2]field:  geomnearest('kids_layer_kid_age_2', 'kids_id')
[age_3]field:  geomnearest('kids_layer_kid_age_3', 'kids_id')

enter image description here

Your school_layer's attribute table will become like above.

As can be seen on the topmost picture, School_A is closest to a (Age 1= ping group), b (Age 2= green group) and i (Age 3= blue group).

  • Thanks, this actually works perfectly, however the issue here is that if the number of categories is higher than 3, (I have a case where I have 880 categories; not age categories of course but different categories) then it would be really painful to have 880 shapefiles and then repeating step 3 for 880 times! Are you aware of anyway around this? Many thanks – Mahmoud Nov 30 '17 at 17:01
  • @Mahmoud It seems your core part of your question. Will you edit and include that information in your post? Somebody can pick it up and offer you a solution. Thanks! – Kazuhito Nov 30 '17 at 22:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.