locked
How can I get the extents of a polygon? RRS feed

  • Question

  • How can I get the rectangular extents of a polygon?

    I was hoping for something like:

    DECLARE @g geography;

    SET @g = (select geog from ZipCode where ZipCodeId = '20232')

    SELECT @g.minx, @g.miny, @g.maxx, @g.maxy

    Monday, November 8, 2010 2:21 AM

Answers

  • To get a "rectangular" extent you need to use the STEnvelope() method of the geometry datatype. This should work:

     

    DECLARE @g geography;
    
    SET @g = (select geog from ZipCode where ZipCodeId = '20232')
    
    -- Convert to geometry
    DECLARE @geom geometry = geometry::STGeomFromWKB(@g.STAsBinary(), @g.STSrid);
    
    -- Calculate axis-aligned bounding box
    DECLARE @bbox geometry = @geom.STEnvelope();
    
    -- Select min/max coordinates
    SELECT
     @bbox.STPointN(1).STX AS minx,
     @bbox.STPointN(1).STY AS miny,
     @bbox.STPointN(3).STX AS maxx,
     @bbox.STPointN(3).STY AS maxy
    


    Beginning Spatial with SQL Server http://www.apress.com/book/view/1430218290
    • Proposed as answer by Tom Li - MSFT Monday, November 8, 2010 8:56 AM
    • Marked as answer by Tom Li - MSFT Wednesday, November 17, 2010 9:53 AM
    Monday, November 8, 2010 8:35 AM
    Answerer