代码之家  ›  专栏  ›  技术社区  ›  bbusdriver

根据数据库中保存的经纬度显示附近的位置。angular6+sql server

  •  0
  • bbusdriver  · 技术社区  · 7 年前

    当应用程序启动时,我想显示距离我所在位置10公里的附近餐馆,这些餐馆以经度和纬度的形式保存在数据库(SQL Server)中。

    例:餐厅餐桌

    restaurantId , name , longitude , latitude

    1 Greek Restaurant , -72.374984 , 41.274672

    2 Italian Restaurant , -73.483947 40.739283

    ...

    假设我的位置是

    : -74.009056

    : 40.713744

    @myLongitude , @myLatitude , @km ).

    这些是我的基本假设,但不确定是否可行。 如何根据数据库中保存的lng和lat检索附近的餐厅(10公里)?

    不需要地图,我只想把它列成一张单子。最好知道每家餐厅离我的位置有多远(以公里为单位)。

    感谢您的帮助,非常感谢代码片段!

    1 回复  |  直到 7 年前
        1
  •  1
  •   Paweł Dyl    7 年前

    我建议使用 Geography data type

    --this is your table
    CREATE TABLE Landmark (
        Id int,
        Name VARCHAR(100),
        Latitude FLOAT,
        Longitude FLOAT
    )
    
    INSERT Landmark VALUES
    (1, 'Greek Restaurant', -72.374984, 41.274672),
    (2, 'Italian Restaurant', -73.483947, 40.739283)
    
    --this is better table to query
    WITH GeographyLandmark AS
    (
        SELECT Id, Name, geography::STPointFromText('POINT(' + CAST(Latitude AS VARCHAR(20)) + ' ' + CAST(Longitude AS VARCHAR(20)) + ')', 4326) Location
        FROM LandMark
    )
    --this query calculates distance between point and localizations in meters
    SELECT Id, Name,
        geography::STPointFromText('POINT(' + CAST(-74.009056 AS VARCHAR(20)) + ' ' + CAST(40.713744 AS VARCHAR(20)) + ')', 4326).STDistance(Location) Distance
    FROM GeographyLandmark
    

    结果:

    Id    Name                 Distance
    ----- -------------------- ----------------
    1     Greek Restaurant     150944,610588657
    2     Italian Restaurant   44456,82536079
    

    参考文献: STDistance , STPointFromText