Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get places in radius of a certain point using SQL geography

I have an SQL table column with the Geography type:

create table dbo.Events
(
  Id int identity not null 
    constraint PK_Events_Id primary key clustered (Id),
  Localization geography not null
);

How can I get all events in a radius of 40 km? Is this possible?

Thank You, Miguel

like image 885
Miguel Moura Avatar asked Mar 21 '14 13:03

Miguel Moura


2 Answers

Assuming you have latitude and longitude of the point from which you want to search:

DECLARE @Origin GEOGRAPHY,
        -- distance defined in meters
        @Distance INTEGER = 40000;        

-- center point
SET @Origin = GEOGRAPHY::STGeomFromText('POINT(-122.084039 37.42227)', 4326);

-- return all rows from events in 40km radius
SELECT * FROM dbo.Events WHERE @Origin.STDistance(Localizaton) <= @Distance;
like image 198
Bryan Avatar answered Sep 21 '22 12:09

Bryan


DECLARE @h geography;
SET @h = geography::STGeomFromText('POINT(-122.34900 47.65100)', 4326); --set here GPS from where you want to search 40 km
SELECT Localization.STDistance(@h) from dbo.events

The result of STDistance() will be in meters.

like image 22
MikkaRin Avatar answered Sep 21 '22 12:09

MikkaRin