Forum Discussion

Shailesh2thakur's avatar
Shailesh2thakur
Frequent Visitor
2 years ago
Solved

Need Help: Calculating nearest location distance and location ID

I have two  tables, i.e. Parking & SiteMaster. The Columns in the Parking Table are as follows: VehicleNo, Start time, End time, lat, long. The Columns in the SiteMaster are as follows: SiteID, La...
  • AlienSx's avatar
    AlienSx
    2 years ago

    Shailesh2thakur distance is in km. To switch to miles change Earth radius parameter in code accordingly. 

    let
        sites = your_SiteMaster_table,
        vehicles = your_Parking_table,
    // add geo record into vehicles table
        v_geo = Table.AddColumn(vehicles, "geo", each GeographyPoint.From(Number.From([long]), Number.From([lat]))),
    // transform sites table into list of records with geo coordinates
        sg = List.Buffer(
            Table.ToList(
                sites,
                (x) => GeographyPoint.From(Number.From(x{2}), Number.From(x{1})) & [site = x{0}]
            )
        ),
    // distance calculation function
        distance = (parking) => (site) =>
            [r = 6371, // this is Earth radius in km. Change to miles if you like
            p = Number.PI / 180,
            a = 0.5 - 
                Number.Cos( (site[Latitude] - parking[Latitude]) * p) / 2 +
                Number.Cos(parking[Latitude] * p) * 
                    Number.Cos(site[Latitude] * p) *
                        (1 - Number.Cos( (site[Longitude] - parking[Longitude]) * p)) / 2,
            d = 2 * r * Number.Asin(Number.Sqrt(a))][d],
    // this function finds closest site and distance to it
        closest = (v) =>
            [f = distance(v),
            m = List.Min(sg, null, f),
            dist = m & [distance = distance(v)(m)]][dist],
    // now we apply closest function to "geo" column with locations
        find_closest_sites = Table.TransformColumns(v_geo, {"geo", (x) => closest(x)}),
    // and finally expand site ID and distance to it
        expand_site_info = Table.ExpandRecordColumn(find_closest_sites, "geo", {"site", "distance"})
    in
        expand_site_info