# Nearest neighbor analysis to pick the next closest waypoint

I'm looking for a QGIS solution to do a nearest neighbor analysis on a set of waypoints that I have as X Y points. When the points are loaded into the planning software (loaded as waypoints) they draw in the order they are added to the CSV. What I want to do in QGIS is work out the next closest point in the dataset without going back to a point that has already been used.

Image below shows what is happening currently. The path for the waypoints wants to travel longer than needed when they could be going to closer waypoints first.

• Is there any column in the CSV file, which could allow grouping the points by pathes ? Sep 21, 2021 at 7:08

## Solution: basic idea

To create a line connecting points without any (attribute) information about the sequence, only based on spatial prosimity, draw a line from each point to its two closest neighbours.

In this way, you connect the points only based on spatial distribution, not on any attribute or other information. This works best if points are evenly distributed along the line you want to get.

Screenshot: red points, created in random order (as you can see from the label that represents `\$id`) and with no other attributes, but connected based on proximity with the expression - her using Geometry generator:

## Implementation

To do that, you can use QGIS expressions with either Geometry generator or Geometry by expression. Use this expression and replace `points` with the name of your points layer (if using Geometry generator, you can always use `@layer`, referring to the current layer, instead):

``````union (
make_line (\$geometry, array_get (overlay_nearest ('points', \$geometry,limit:=3),1)),
make_line (\$geometry, array_get (overlay_nearest ('points', \$geometry,limit:=3),2)))
``````

## Details to be aware of

If using Geometry generator, replace `1` and `2` at the end of line 2 and 3 by `0` and `1`. There are some steps to get a clean line if needed:

• Delete duplicate geometries
• Delete the two "wrong" line segments at the start and end point (from 1 to 5 on the bottom right in the screenshot).
• If you have other "wrong" lines (in case points are clustered and you get a mess of lines), remove them automatically: check if a point has more then three lines, then delete the longest one(s) and keep only the two shorter ones.
• Merge the line segments to one single line.