Lucas's profileLucas Souza [MCP | MCTS ...PhotosBlogListsMore Tools Help

Blog


    August 08

    Utilizando dados espaciais no SQL Server 2008 (Parte 03)

    Continuação...
    STWithin, STContains
    Dois métodos que seguem também o padrão OGC retornando 1 ou 0 e indica se todos ‘Points’ da instância existe totalmente ao lado de outra instância
    STContains() testa se o parâmetro instância está do lado da instância base
    STWithin() testa se a instância base está do lado da instância parâmetro, retorna verdadeiro se dado o valor geometric estiver juntamente á outro, de outra forma, retorna falso. Este método irá retorna NULL se todos SRID da instância não possuír o valor adequado ao SRID da outra instância;

    -- Results: 1     0

    --                0     1

    DECLARE @g geometry = 'POLYGON ((10 10, 13 30, 30 30, 30 15,10 10))'

    DECLARE @h geometry = 'LINESTRING (16 16, 16 24, 25 18)'

     

    SELECT @g.STContains(@h), @g.STWithin(@h)

    SELECT @h.STContains(@g), @h.STWithin(@g)

     


    Figura 1.7 (Function - STContains)

     

    STPointOnSurface
    Este método irá retornar de certa forma um ponto aleatório o qual nos garante a localização dentro da instância base.

    -- Results: POINT (23 25)
    DECLARE @g geometry = 'POLYGON((10 10, 14 15, 50 12, 45 30,10 30, 10 10))'

    SELECT @g.STPointOnSurface().ToString()


    Figura 1.8 (Function - STPointOnSurface)

    STGeometryType
    Retorna o tipo Open Geospatial Consortium (OGC) o qual representa a instância geometry

    -- Results: Polygon

    DECLARE @g geometry;

    SET @g = geometry::STGeomFromText('POLYGON((0 0, 3 0, 3 3, 0 3, 0 0))', 0);

    SELECT @g.STGeometryType();

    STGeomFromText
    Retorna uma instância geometry da representação Open Geospatial Consortium (OGC) Well-Known Text(WKT) representando assim o argumento de elevações (Z) e medidas (M).

    -- Results: LINESTRING (100 100, 20 180, 180 180)

    DECLARE @g geometry;

    SET @g = geometry::ST

    GeomFromText('LINESTRING (100 100, 20 180, 180 180)', 0);

    SELECT @g.ToString();

    STTouches
    Retorna verdadeiro se dado o valor geometric faz parte de outro, de outra forma, retorna falso. Este método retorna null se todos SRID (Spatial Reference Identifier) da instância não possuír o valor adequado SRID da outra instância;

    STDistance
    Retorna a distância entre os valores do tipo específico Point geometric. Este método irá retorna null se SRID(Spatial Reference Identifier) da instância não possuír o valor adequado ao SRID da outra instância;


    Figura 1.9 (Geography Methods)

    Aos termos analisado algumas funções e formatos existentes nos dados espaciais, o que nos resta agora é apenas aplicar-los, os tipos específicos podem ser usados ambos em definições de tabela e tipos variáveis. Dependendo de sua manipulação dos dados espaciais sendo plano ou ellipso pode-se usar ambos os tipo de dados geometry e geography, iremos neste momento ao exemplo prático.

    USE master

    GO

     

    IF EXISTS(SELECT Name FROM sys.databases WHERE name = N'SpatialDatabase')

          DROP DATABASE SpatialDatabase

     

    CREATE DATABASE SpatialDatabase

     ON PRIMARY

      (NAME = SpatialDatabase_data,

       FILENAME = 'C:\DatabaseSpatial\SpatialDatabase.mdf'),

     FILEGROUP SpatialGroup1

      (NAME = SpatialGroup2,

       FILENAME = 'C:\DatabaseSpatial\SpatialDatabase.ndf')

     LOG ON

      (NAME = Spatial_log,

       FILENAME = 'C:\DatabaseSpatial\SpatialDatabase.ldf')

     GO

     

    USE SpatialDatabase;

     

    CREATE TABLE #GeometrySpatial

    (

          LocationID   INT PRIMARY KEY CLUSTERED NOT NULL,

          LocationName NVARCHAR(30),

        Position      GEOGRAPHY

    );

     

    INSERT INTO #GeometrySpatial (LocationID,LocationName,Position)

          VALUES (1,'Nova York', geography::Parse('POLYGON((

     -75.17031 39.95601, -75.16786 39.95778, -75.17921 39.96874,

     -75.18441 39.96512, -75.17031 39.95601 ))'))

     

     

    INSERT INTO #GeometrySpatial (LocationID,LocationName,Position)

          VALUES (2,'Chicago', geography::Parse('POLYGON((

     -75.17031 39.95601, -75.16786 39.95778, -75.18870 39.97789, -75.18521 39.99237,

     -75.18603 40.00677, -75.19922 40.01136, -75.21746 40.03142, -75.22534 40.02586,

     -75.21052 40.01430, -75.19192 40.00634, -75.19248 39.99570, -75.20526 39.98374,

     -75.19437 39.97704, -75.19087 39.96920, -75.17031 39.95601))'))

         

    INSERT INTO #GeometrySpatial (LocationID,LocationName,Position)

          VALUES (3,'Miami', geography::Parse('POLYGON((

     -75.22280 40.02387, -75.21442 40.02810, -75.21746 40.03142,

     -75.22534 40.02586, -75.22280 40.02387))'))

     

    -- Trazendo os valores de forma compreensivel.

    SELECT

      LocationID,LocationName,Position.ToString() as WKT,

      Position.STLength() as longitude

    FROM #GeometrySpatial

     

    Figura 2.0 (Results – measures and longitude)
         

    -- Visualizando o Spatial Results

    SELECT * FROM #GeometrySpatial

     


    Figura 2.1 (Spatial Results - Map)

     

    OBS: Se por acaso quisermos obter a lista de todos SRIDs suportados pelo SQL Server, podemos executar a instrução:
     SELECT * FROM sys.spatial_reference_systems
    , para mais informações relacionado aos SRIDs,
    visite:
    http://msdn.microsoft.com/en-us/library/bb964707.aspx


    Figura 1.2 (Results - SRIDs)

     

    Ótimo, agora que conhecemos o que são os dados espacias, quando devemos utilizar, quais são as diferença dentre os tipos de dados geometry e geography, quais são os formatos e tipos existentes suportados pelo SQL Server e o exemplo prático, o que resta neste momento é apenas implementar-los em nossa aplicação e assim termos a convicção de que possuímos uma aplicação pelo qual possui ótimas vantagens quando o assunto se relata em buscas (mundialmente).

     

    []´s

     

    Lucas Souza

    Comments

    Please wait...
    Sorry, the comment you entered is too long. Please shorten it.
    You didn't enter anything. Please try again.
    Sorry, we can't add your comment right now. Please try again later.
    To add a comment, you need permission from your parent. Ask for permission
    Your parent has turned off comments.
    Sorry, we can't delete your comment right now. Please try again later.
    You've exceeded the maximum number of comments that can be left in one day. Please try again in 24 hours.
    Your account has had the ability to leave comments disabled because our systems indicate that you may be spamming other users. If you believe that your account has been disabled in error please contact Windows Live support.
    Complete the security check below to finish leaving your comment.
    The characters you type in the security check must match the characters in the picture or audio.

    To add a comment, sign in with your Windows Live ID (if you use Hotmail, Messenger, or Xbox LIVE, you have a Windows Live ID). Sign in


    Don't have a Windows Live ID? Sign up

    Trackbacks

    The trackback URL for this entry is:
    http://souzalucas.spaces.live.com/blog/cns!289B02192542DA52!539.trak
    Weblogs that reference this entry
    • None