[gdal-dev] Writing interior rings is not working

Heiko Thiel heiko.thiel at hpi.de
Fri Apr 10 08:37:38 PDT 2015


Hello,

I currently trying to save Polygons in a ShapeFile with Gdal 1.11.2. It 
works so far - except interior rings are not stored. Anyone any idea?

My Code:

#include <ogrsf_frmts.h>
#include <iostream>
#include <vector>
#include <cassert>

int main(int argc, char *argv[])
{
     OGRRegisterAll();

     OGRSFDriver *poDriver = 
OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName("ESRI Shapefile");
     if (poDriver == nullptr)
     {
         std::cout << "ESRI Shapefile driver not available." << std::endl;
         return 0;
     }

     OGRDataSource *poDS = poDriver->CreateDataSource("gdaltest.shp", 
nullptr);
     if (poDS == nullptr)
     {
         std::cout << "Creation of output file failed." << std::endl;
         return 0;
     }

     OGRLayer *poLayer = poDS->CreateLayer("polygons", nullptr, 
wkbPolygon, nullptr);
     if (poLayer == nullptr)
     {
         std::cout << "Layer creation failed." << std::endl;
         OGRDataSource::DestroyDataSource(poDS);
         return 0;
     }

     //write 1 polygon with with 1 exterior and 2 exterior rings

     OGRFeature *poFeature = 
OGRFeature::CreateFeature(poLayer->GetLayerDefn());

     OGRPolygon polygon;

     auto outerRing = std::vector<std::pair<int, int>>({ { 0, 0 }, { 0, 
5 }, { 5, 5 }, { 5, 0 } });

     OGRLinearRing ring;
     for (auto &p : outerRing)
     {
         OGRPoint pt;

         pt.setX(p.first);
         pt.setY(p.second);
         ring.addPoint(&pt);
     }
     polygon.addRing(&ring);

     auto innerRingBase = std::vector<std::pair<int, int>>({ { 1, 1 }, { 
1, 2 }, { 2, 2 }, { 2, 1 } });
     //auto innerRingBase = std::vector<std::pair<int, int>>({ { 2, 1 }, 
{ 2, 2 }, { 1, 2 }, { 1, 1 } }); //reverse order don't work too
     const int innerRingOffsetX = 2;

     for (int i = 0; i < 2; i++)
     {
         OGRLinearRing innerRing;
         for (auto &p : innerRingBase)
         {
             OGRPoint pt;

             pt.setX(p.first + i*innerRingOffsetX);
             pt.setY(p.second);
             ring.addPoint(&pt);
         }

         polygon.addRing(&innerRing);
     }
     assert(polygon.getNumInteriorRings() == 2); //this don't throw, so 
gdal detected interior rings

     polygon.closeRings();
     poFeature->SetGeometry(&polygon);

     if (poLayer->CreateFeature(poFeature) != OGRERR_NONE)
     {
         std::cout << "Failed to create feature in shapefile." << std::endl;
     }

     OGRFeature::DestroyFeature(poFeature);

     OGRDataSource::DestroyDataSource(poDS);

     return 0;
}

Regards


More information about the gdal-dev mailing list