14

What is the C# equivalent of this geospatial T-SQL code?

DECLARE @g geography;
DECLARE @h geography;
SET @g = geography::STGeomFromText('POLYGON((-122.358 47.653, -122.348 47.649, -122.348 47.658, -122.358 47.658, -122.358 47.653))', 4326);
SET @h = geography::Point(47.653, -122.358, 4326)

SELECT @g.STIntersects(@h)

I am trying to find a point in a polygon using the SqlGeometry data type -- and can with the above T-SQL; but I do not understand how to achieve equivalent C# code.

J0e3gan
  • 8,287
  • 9
  • 48
  • 76
Unforgiven
  • 1,719
  • 5
  • 18
  • 18
  • possible duplicate of [Geo functions from SQL Server 2008 to C# (latitude and longitude points inside or outside polygon/map area)](http://stackoverflow.com/questions/9448054/geo-functions-from-sql-server-2008-to-c-sharp-latitude-and-longitude-points-ins) – Damith May 09 '13 at 07:22

1 Answers1

12

Try this:

public bool OneOffSTIntersect()
{
    var g =
        Microsoft.SqlServer.Types.SqlGeography.STGeomFromText(
            new System.Data.SqlTypes.SqlChars(
                "POLYGON((-122.358 47.653, -122.348 47.649, -122.348 47.658, -122.358 47.658, -122.358 47.653))"), 4326);
    // suffix "d" on literals below optional but explicit
    var h = Microsoft.SqlServer.Types.SqlGeography.Point(47.653d, -122.358d, 4326);

    // rough equivalent to SELECT
    System.Console.WriteLine(g.STIntersects(h));

    // Alternatively return from a C# method or property (get).
    return g.STIntersects(h);
}

MSDN's SqlGeography Methods page links to info on each of the C# equivalents to the critical calls in your T-SQL - e.g. STIntersects.

J0e3gan
  • 8,287
  • 9
  • 48
  • 76
  • 4
    `// rough equivalent to SELECT` :-) – Tim May 09 '13 at 11:16
  • 1
    @Tim: Funny, last night this just came out the way I thought it not knowing the OP's general level of C# knowledge or context to use the translated code; but today this strikes me as pretty funny too. :) Thanks for pointing it out. – J0e3gan May 10 '13 at 01:57