[gdal-dev] Help on creating polygon shapefile

Frank Warmerdam warmerdam at pobox.com
Fri Feb 8 21:06:44 EST 2008


Limei Ran wrote:
> 
> Hi:
> 
> I am new in using OGR.  I tried to create a polygon shapefile using the 
> following codes:
> 
> ===============
> .......
> OGRPolygon *poG = new OGRPolygon();
>        printf ("Declared OGRPolygon.\n");
> 
>        char mesg[256];
>        unsigned char *geom;
>        sprintf(mesg, 
> "POLYGON(%f,%f,%f,%f,%f,%f,%f,%f,%f,%f)\0",x1,y1,x2,y2,x3,y3,x4,y4,x1,y1);
>        geom = (unsigned char *) mesg;
>        printf("POLYGON: %s\n",geom);
> 
>        printf ("Import Wkb.\n");
> 
>        if ( poG->importFromWkb(geom,0) != OGRERR_NONE )
>        {
>           printf( "Importing a Wkb polygon failed.\n" );
>           exit( 1 );
>        }

Limei,

Two major problems.

1) You are assembling WKT format geometry, but using importFromWkb().
Instead you need to use importFromWkt().

2) The format of the WKT is wrong.  This is an example WKT polygon
with one ring.  Note the two layers of brackets and that the x and
y values are separated by a space, while there is only a comma
between point pairs.  Its programming - details matter!

POLYGON ((479750.6875 4764702.0,479658.59375 4764670.0,479640.09375 
4764721.0,479735.90625 4764752.0,479750.6875 4764702.0))

Incidentally, assembling the polygon without going through WKT would
be more efficient.  This is a reasonably clear example of creating
a polygon for a rectangle:

void OGRLayer::SetSpatialFilterRect( double dfMinX, double dfMinY,
                                      double dfMaxX, double dfMaxY )

{
     OGRLinearRing  oRing;
     OGRPolygon oPoly;

     oRing.addPoint( dfMinX, dfMinY );
     oRing.addPoint( dfMinX, dfMaxY );
     oRing.addPoint( dfMaxX, dfMaxY );
     oRing.addPoint( dfMaxX, dfMinY );
     oRing.addPoint( dfMinX, dfMinY );

     oPoly.addRing( &oRing );

     SetSpatialFilter( &oPoly );
}

Best regards,
-- 
---------------------------------------+--------------------------------------
I set the clouds in motion - turn up   | Frank Warmerdam, warmerdam at pobox.com
light and sound - activate the windows | http://pobox.com/~warmerdam
and watch the world go round - Rush    | President OSGeo, http://osgeo.org



More information about the gdal-dev mailing list