find the nearest location in ms-sql

前端 未结 3 1025
故里飘歌
故里飘歌 2021-02-08 18:10

I send these paramaters my script : Latitude : 41.0186 Longitude : 28.964701 (it is sample). i want to find nearest location\'s name. how to do this? (query\'s where code\'s mus

3条回答
  •  悲&欢浪女
    2021-02-08 18:30

    Use this function

    CREATE FUNCTION dbo.DictanceKM(@lat1 FLOAT, @lat2 FLOAT, @lon1 FLOAT, @lon2 FLOAT)
    RETURNS FLOAT 
    AS
    BEGIN
    
        RETURN ACOS(SIN(PI()*@lat1/180.0)*SIN(PI()*@lat2/180.0)+COS(PI()*@lat1/180.0)*COS(PI()*@lat2/180.0)*COS(PI()*@lon2/180.0-PI()*@lon1/180.0))*6371
    END
    

    You may order by this function, BUT on large datasets it will be very slow, so try to prefilter the recordset

    UPD:

    Using @chopikadze's test data:

    declare @lat float, @lng float
    select @lat = 41.0186, @lng = 28.964701
    
    declare @Location table(Latitude float, Longtitude float, Name nvarchar(50))
    insert into @Location(Latitude, Longtitude, Name) values (41.0200500000, 40.5234490000, 'a')
    insert into @Location(Latitude, Longtitude, Name) values (41.0185714000, 37.0975924000, 'b')
    insert into @Location(Latitude, Longtitude, Name) values (41.0184913000, 34.0373739000, 'c')
    insert into @Location(Latitude, Longtitude, Name) values (41.0166667000, 39.5833333000, 'd')
    insert into @Location(Latitude, Longtitude, Name) values (41.0166667000, 28.9333333000, 'e')
    
    SELECT ABS(dbo.DictanceKM(@lat, Latitude, @lng, Longtitude)) DistanceKm, * FROM @Location
    ORDER BY ABS(dbo.DictanceKM(@lat, Latitude, @lng, Longtitude))
    

    Assuming that the Earth is NOT a geoid, but the round ball, if you need under 1m exact formula - I can find it, don't have it with me

提交回复
热议问题