Search code examples
c#asp.netlinq-to-entities

How to search by radius based on latitude and longitude?


I want to show data based on latitude and longitude with specified radius.

Example:

I have a record with latitude 55.0628 and longitude -162.3056 without specified state.

How can I show only records that within one state, using entity to linq?

If I have state Florida to show just records that within Florida.

Table Data

id            item             latitude                 longitude
1             townhome          55.0628                 -162.3056


Table postal codes

id               state                 city            latitude            longitude
1                alaska                Akutan          54.143              -165.7854
2                Alabama               Huntsville      34.7448             -86.6704

Solution

  • I would execute the query as close to the actual data as possible (which probably means circumventing LINQ and calling a stored procedure).

    Here is a SQL user defined function that I use to calculate the distance between two locations. It leverages the new geography functionality introduced in SQL Server 2008.

    CREATE FUNCTION [dbo].[GetDistanceBetween]
    (
        @Lat1 float,
        @Long1 float,
        @Lat2 float,
        @Long2 float
    )
    RETURNS float
    AS
    BEGIN
    
        DECLARE @RetVal float;
        SET @RetVal = ( SELECT geography::Point(@Lat1, @Long1, 4326).STDistance(geography::Point(@Lat2, @Long2, 4326)) / 1609.344 );
    
    RETURN @RetVal;
    
    END
    

    Function returns distance in miles and is very fast in my experience (this will obviously depend on how many comparisons you need to make).

    You could call it using something like:

    DECLARE @StartingLatitude FLOAT, @StartingLongitude FLOAT;
    DECLARE @MaxDistance FLOAT = 50;
    
    SELECT * FROM PostalCodes 
    WHERE dbo.GetDistanceBetween(@StartingLatitude, @StartingLongitude, latitude, longitude) <= @MaxDistance;