Question

How to write a LINQ query for nearest points calculation?

I have Lat and Lng in a table saved as string in a SQL Server database.

Found one solution on stackoverflow the query look like this

var coord = DbGeography.FromText(String.Format("POINT({0} {1})", latitude.ToString().Replace(",", "."), longitude.ToString().Replace(",", ".")));
var nearest = (from h in db.hotels
               where h.location != null
               orderby h.location.Distance(coord)
               select h).Take(limit);
return nearest;

trying to implement this but the location.distance is not understandable. Can somebody please guide me?

Was it helpful?

Solution

Use the right tool(s) for the job. Latitude & Longitude are not strings - they should be floats. SQL Server 2005+ has geospatial features baked in and if you use the appropriate data types, it can perform your distance calculations for you. By default, distance will be calculated in meters.

I tried to use SQLFiddle for this but it didn't like it.

create table #locations  (
        Locationname varchar(20) not null unique,
        LocationGeo geography not null
        );

insert into #locations values (
        'Seattle',
        geography::STGeomFromText('POINT(-122.33365 47.612033)',4326)
);
insert into #locations values (
        'San Francisco',
        geography::STGeomFromText('POINT(-122.41667 37.78333)',4326)
);
insert into #locations values (
        'London',
        geography::STGeomFromText('POINT(0 0)',4326)
);

declare @p1 geography;
SELECT @p1 = Locationgeo from #locations where locationname='London';
SELECT locationname, @p1.STDistance(locationgeo)/1000 as [Distance from London] from #locations order by [Distance from London];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top