By using STContains function of SQL geography it was possible to calculate if a set of coordinates is within an area , however this revealed that if last received coordinates were just outside the area than these coordinates do not match any location.
What would be an efficient way to display how many and which devices (out of 4000) are present in which location (out of 600) based on smallest distance between a static set of location coordinates and dynamic coordinates of devices?
Location table:
loc_name | loc_lat | loc_long | loc_geo_polygon | loc_geo_point
Device table:
dev_name | dev_lat | dev_long | dev_geo_point
Obvious solution is to query both tables for all data and loop through 4000 devices and measure distance to 600 locations returning smallest distance, but that creates 2.4 mil calculations every time I want to view data. Even if I remove from the list a device with already matched location, it is still quite a few calculations with limited potential for future growth.
Another way is to add a location_name column to Devices table and calculate the nearest location every time I receive coordinates from a device, that would be 100 devices x 600 locations calcs every minute, better than before, as it is a steady load rather than a burst.
Maybe there is a better way to approach this logically or with use of functions that I am not aware of?