gistools/util/interpolation/
nearest.rs

1use super::{Interpolatable, get_distance};
2use crate::util::GetInterpolateValue;
3use s2json::{GetM, GetXY, GetZ};
4
5/// # Nearest Neighbor Interpolation
6///
7/// ## Description
8/// Finds the nearest point in the reference data to the given point and returns its value.
9///
10/// ## Usage
11pub fn nearest_interpolation<
12    M: Clone,
13    P: GetXY + GetZ,
14    R: GetM<M> + GetXY + GetZ,
15    V: Interpolatable,
16>(
17    point: &P,
18    ref_data: &[R],
19    get_value: GetInterpolateValue<R, V>,
20) -> V {
21    // Find the nearest point
22    let mut nearest_point: Option<&R> = None;
23    let mut min_distance = f64::INFINITY;
24
25    for ref_point in ref_data {
26        let dist = get_distance(point, ref_point);
27        if dist < min_distance || nearest_point.is_none() {
28            min_distance = dist;
29            nearest_point = Some(ref_point);
30        }
31    }
32
33    // Return the value of the nearest point
34    if let Some(nearest_point) = nearest_point { get_value(nearest_point) } else { V::default() }
35}