Pages Menu
Categories Menu

Posted by on Jun 28, 2013 in .Net, Development, SQL | 0 comments

Geography and the Nearest Neighbor Search

Performing searches on geographic coordinates (latitude and longitude) seems to be a requirement on many of the projects I have been doing lately. One of the most common is the nearest neighbor search which will find the location(s) nearest to the users current location. Most distance calculations involving geographic coordinates make use of the haversine formula.

Nearest Neighbor Search in MySQL

See the MySQL implementation below. For a great explanation of this code, refer to geo-search.pdf.

Nearest Neighbor Search in SQL Server 2012

If you are using SQL Server 2012, the Geography types make this search much easier (and more efficient). See here for more info.

Nearest Neighbor Search with Linq

From .Net, you can take advantage of this functionality with Linq as in the example below. A detailed explaination of the above example can be found here.

Further reference:

Convert Lat/Long to Geography Point
Creating High Performance Spatial Databases
Calculating the Bearing from One Point to Another