Monday 21 December 2020

How to find or calculating all nearest or given Distance locations from a coordinates (latitude,longitude) using sql server

 ///////////////// Method I

declare @lat decimal(18,4)=17.24880000
,@lng decimal(18,4)=76.40320000
,@Distance decimal(18,1)=20.0
 
------To search by kilometers instead of miles just multiply by 1.60934
 
select * from(SELECT locationname,locationcode,lat,long,(60 * 1.1515 * (180/pi()) *
acos(
cos(radians(@lat))*cos(radians(Lat)) * cos(radians(Long) - radians(@lng))+ sin (radians(@lat)) * sin(radians(lat))
)
) AS distance FROM mstlocation where SW_GW=2)dt
where distance < @Distance


 ///////////////// Method II


------ 1 miles= 1.60934 Kms and pi()==22/7 or 3.14159265358979323846, 180= degree
select * from(
SELECT locationname,locationcode,lat,long,(
(
acos(sin((@lat*pi()/180)) * sin((lat*pi()/180)) + cos((@lat*pi()/180)) * cos((lat*pi()/180)) * cos(((@lng- long) * pi()/180)))
)
 * (180/pi()) * 60 * 1.1515 *1.60934) as distance FROM mstlocation where SW_GW=2 and statecode='10')dt where distance<=@Distance



///////////// Indicators


----@lng       – this is the variable where passing the longitude of the point.
----@lat       – this is the variable where passing the longitude of the point.
----@Distance  – this is the distance that you would like to find all the markers.
----table      – this is the table… you’ll want to replace that with your table name.
----lat        – this is the field (latitude) of my table..
----long       – this is the field (longitude) of my table.



///////////// Result

lat                      long
17.230000000     76.553333000
17.168333000     76.610000000
17.335000000     76.568333000
17.341667000     76.596667000
17.225000000     76.481667000



No comments:

Post a Comment

Excel Sort values in ascending order using function TEXTJOIN

 Excel ::  Text ::  1,3,5,2,9,5,11 Result :: 1,2,3,5,5,9,11 Formula ::     TEXTJOIN ( ",",1,SORT(MID(SUBSTITUTE( A1 ,","...