本文整理汇总了C++中OGRLayer::CreateField方法的典型用法代码示例。如果您正苦于以下问题:C++ OGRLayer::CreateField方法的具体用法?C++ OGRLayer::CreateField怎么用?C++ OGRLayer::CreateField使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类OGRLayer
的用法示例。
在下文中一共展示了OGRLayer::CreateField方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: init_layer
OGRLayer* init_layer(const std::string& name, const stringv& fields, const OGRwkbGeometryType type) {
std::cerr << "Creating layer: " << name << "\n";
OGRLayer* layer = m_data_source->CreateLayer(name.c_str(), &m_srs_out, type, NULL);
if (layer == NULL) {
std::cerr << "Layer creation failed (" << name << ").\n";
exit(1);
}
std::cerr << " Creating field: osm_id\n";
OGRFieldDefn field_osm_id("osm_id", OFTString);
field_osm_id.SetWidth(11);
if (layer->CreateField(&field_osm_id) != OGRERR_NONE ) {
std::cerr << "Creating field 'osm_id' failed.\n";
exit(1);
}
std::cerr << " Creating field: z_order\n";
OGRFieldDefn field_z_order("z_order", OFTInteger);
field_z_order.SetWidth(4);
if (layer->CreateField(&field_z_order) != OGRERR_NONE ) {
std::cerr << "Creating field 'z_order' failed.\n";
exit(1);
}
std::cerr << " Creating field: way_area\n";
OGRFieldDefn field_way_area("way_area", OFTReal);
field_way_area.SetWidth(10);
if (layer->CreateField(&field_way_area) != OGRERR_NONE ) {
std::cerr << "Creating field 'way_area' failed.\n";
exit(1);
}
stringv::const_iterator it;
for (it = fields.begin(); it != fields.end(); ++it) {
std::cerr << " Creating field: " << *it << "\n";
OGRFieldDefn field_tag((*it).c_str(), OFTString);
field_tag.SetWidth(255);
if (layer->CreateField(&field_tag) != OGRERR_NONE ) {
std::cerr << "Creating field '" << *it << "' failed.\n";
exit(1);
}
}
return layer;
}
示例2: oSpaRef
OGRLayer *GNMDatabaseNetwork::ICreateLayer(const char *pszName,
CPL_UNUSED OGRSpatialReference *poSpatialRef,
OGRwkbGeometryType eGType, char **papszOptions)
{
//check if layer with such name exist
for(int i = 0; i < GetLayerCount(); ++i)
{
OGRLayer* pLayer = GetLayer(i);
if(NULL == pLayer)
continue;
if(EQUAL(pLayer->GetName(), pszName))
{
CPLError( CE_Failure, CPLE_IllegalArg,
"The network layer '%s' already exist.", pszName );
return NULL;
}
}
OGRSpatialReference oSpaRef(m_soSRS);
OGRLayer *poLayer = m_poDS->CreateLayer( pszName, &oSpaRef, eGType, papszOptions );
if( poLayer == NULL )
{
CPLError( CE_Failure, CPLE_FileIO, "Layer creation failed." );
return NULL;
}
OGRFieldDefn oField( GNM_SYSFIELD_GFID, GNMGFIDInt );
if( poLayer->CreateField( &oField ) != OGRERR_NONE )
{
CPLError( CE_Failure, CPLE_FileIO, "Creating global identificator field failed." );
return NULL;
}
OGRFieldDefn oFieldBlock(GNM_SYSFIELD_BLOCKED, OFTInteger);
if( poLayer->CreateField( &oFieldBlock ) != OGRERR_NONE )
{
CPLError( CE_Failure, CPLE_FileIO, "Creating is blocking field failed." );
return NULL;
}
GNMGenericLayer* pGNMLayer = new GNMGenericLayer(poLayer, this);
m_apoLayers.push_back(pGNMLayer);
return pGNMLayer;
}
示例3: ProblemReporterOGR
explicit ProblemReporterOGR(OGRDataSource* data_source) :
m_data_source(data_source) {
OGRSpatialReference sparef;
sparef.SetWellKnownGeogCS("WGS84");
m_layer_perror = m_data_source->CreateLayer("perrors", &sparef, wkbPoint, nullptr);
if (!m_layer_perror) {
std::runtime_error("Layer creation failed for layer 'perrors'");
}
OGRFieldDefn layer_perror_field_id1("id1", OFTReal);
layer_perror_field_id1.SetWidth(10);
if (m_layer_perror->CreateField(&layer_perror_field_id1) != OGRERR_NONE) {
std::runtime_error("Creating field 'id1' failed for layer 'perrors'");
}
OGRFieldDefn layer_perror_field_id2("id2", OFTReal);
layer_perror_field_id2.SetWidth(10);
if (m_layer_perror->CreateField(&layer_perror_field_id2) != OGRERR_NONE) {
std::runtime_error("Creating field 'id2' failed for layer 'perrors'");
}
OGRFieldDefn layer_perror_field_problem_type("problem_type", OFTString);
layer_perror_field_problem_type.SetWidth(30);
if (m_layer_perror->CreateField(&layer_perror_field_problem_type) != OGRERR_NONE) {
std::runtime_error("Creating field 'problem_type' failed for layer 'perrors'");
}
/**************/
m_layer_lerror = m_data_source->CreateLayer("lerrors", &sparef, wkbLineString, nullptr);
if (!m_layer_lerror) {
std::runtime_error("Layer creation failed for layer 'lerrors'");
}
OGRFieldDefn layer_lerror_field_id1("id1", OFTReal);
layer_lerror_field_id1.SetWidth(10);
if (m_layer_lerror->CreateField(&layer_lerror_field_id1) != OGRERR_NONE) {
std::runtime_error("Creating field 'id1' failed for layer 'lerrors'");
}
OGRFieldDefn layer_lerror_field_id2("id2", OFTReal);
layer_lerror_field_id2.SetWidth(10);
if (m_layer_lerror->CreateField(&layer_lerror_field_id2) != OGRERR_NONE) {
std::runtime_error("Creating field 'id2' failed for layer 'lerrors'");
}
OGRFieldDefn layer_lerror_field_problem_type("problem_type", OFTString);
layer_lerror_field_problem_type.SetWidth(30);
if (m_layer_lerror->CreateField(&layer_lerror_field_problem_type) != OGRERR_NONE) {
std::runtime_error("Creating field 'problem_type' failed for layer 'lerrors'");
}
}
示例4: SaveGeometry
void SaveGeometry(const CPLString &path, const OGRPolygon &polygon, const OGRSpatialReference &spaRef)
{
const char *pszDriverName = "ESRI Shapefile";
GDALDriver *poDriver = GetGDALDriverManager()->GetDriverByName(pszDriverName );
if( poDriver == NULL )
{
printf( "%s driver not available.\n", pszDriverName );
exit( 1 );
}
GDALDataset *poDS = poDriver->Create( path, 0, 0, 0, GDT_Unknown, NULL );
if( poDS == NULL )
{
printf( "Creation of output file failed.\n" );
exit( 1 );
}
const char* pszLayerName = CPLGetBasename(path);
OGRLayer *poLayer = poDS->CreateLayer( pszLayerName, spaRef.Clone(), wkbPolygon, NULL );
if( poLayer == NULL )
{
printf( "Layer creation failed.\n" );
exit( 1 );
}
OGRFieldDefn oField( "Name", OFTString );
oField.SetWidth(32);
if( poLayer->CreateField( &oField ) != OGRERR_NONE )
{
printf( "Creating Name field failed.\n" );
exit( 1 );
}
OGRFeature *poFeature = OGRFeature::CreateFeature( poLayer->GetLayerDefn() );
//poFeature->SetField( "Name", szName );
poFeature->SetGeometry( polygon.clone() );
if( poLayer->CreateFeature( poFeature ) != OGRERR_NONE )
{
printf( "Failed to create feature in shapefile.\n" );
exit( 1 );
}
OGRFeature::DestroyFeature( poFeature );
GDALClose( poDS );
}
示例5: CPLError
OGRLayer *OGRDataSource::CopyLayer( OGRLayer *poSrcLayer,
const char *pszNewName,
char **papszOptions )
{
OGRFeatureDefn *poSrcDefn = poSrcLayer->GetLayerDefn();
OGRLayer *poDstLayer = NULL;
/* -------------------------------------------------------------------- */
/* Create the layer. */
/* -------------------------------------------------------------------- */
if( !TestCapability( ODsCCreateLayer ) )
{
CPLError( CE_Failure, CPLE_NotSupported,
"This datasource does not support creation of layers." );
return NULL;
}
CPLErrorReset();
poDstLayer = CreateLayer( pszNewName, poSrcLayer->GetSpatialRef(),
poSrcDefn->GetGeomType(), papszOptions );
if( poDstLayer == NULL )
return NULL;
/* -------------------------------------------------------------------- */
/* Add fields. Default to copy all field. */
/* If only a subset of all fields requested, then output only */
/* the selected fields, and in the order that they were */
/* selected. */
/* -------------------------------------------------------------------- */
int iField;
for( iField = 0; iField < poSrcDefn->GetFieldCount(); iField++ )
poDstLayer->CreateField( poSrcDefn->GetFieldDefn(iField) );
/* -------------------------------------------------------------------- */
/* Transfer features. */
/* -------------------------------------------------------------------- */
OGRFeature *poFeature;
poSrcLayer->ResetReading();
while( TRUE )
{
OGRFeature *poDstFeature = NULL;
poFeature = poSrcLayer->GetNextFeature();
if( poFeature == NULL )
break;
CPLErrorReset();
poDstFeature = OGRFeature::CreateFeature( poDstLayer->GetLayerDefn() );
if( poDstFeature->SetFrom( poFeature, TRUE ) != OGRERR_NONE )
{
delete poFeature;
CPLError( CE_Failure, CPLE_AppDefined,
"Unable to translate feature %d from layer %s.\n",
poFeature->GetFID(), poSrcDefn->GetName() );
return poDstLayer;
}
poDstFeature->SetFID( poFeature->GetFID() );
OGRFeature::DestroyFeature( poFeature );
CPLErrorReset();
if( poDstLayer->CreateFeature( poDstFeature ) != OGRERR_NONE )
{
OGRFeature::DestroyFeature( poDstFeature );
return poDstLayer;
}
OGRFeature::DestroyFeature( poDstFeature );
}
return poDstLayer;
}
示例6: layer_point_field_id
TestHandler(OGRDataSource* data_source) :
m_data_source(data_source),
m_out("multipolygon-tests.json") {
OGRSpatialReference sparef;
sparef.SetWellKnownGeogCS("WGS84");
/**************/
m_layer_point = m_data_source->CreateLayer("points", &sparef, wkbPoint, nullptr);
if (!m_layer_point) {
std::cerr << "Layer creation failed.\n";
exit(1);
}
OGRFieldDefn layer_point_field_id("id", OFTReal);
layer_point_field_id.SetWidth(10);
if (m_layer_point->CreateField(&layer_point_field_id) != OGRERR_NONE) {
std::cerr << "Creating id field failed.\n";
exit(1);
}
OGRFieldDefn layer_point_field_type("type", OFTString);
layer_point_field_type.SetWidth(30);
if (m_layer_point->CreateField(&layer_point_field_type) != OGRERR_NONE) {
std::cerr << "Creating type field failed.\n";
exit(1);
}
/**************/
m_layer_linestring = m_data_source->CreateLayer("lines", &sparef, wkbLineString, nullptr);
if (!m_layer_linestring) {
std::cerr << "Layer creation failed.\n";
exit(1);
}
OGRFieldDefn layer_linestring_field_id("id", OFTReal);
layer_linestring_field_id.SetWidth(10);
if (m_layer_linestring->CreateField(&layer_linestring_field_id) != OGRERR_NONE) {
std::cerr << "Creating id field failed.\n";
exit(1);
}
OGRFieldDefn layer_linestring_field_type("type", OFTString);
layer_linestring_field_type.SetWidth(30);
if (m_layer_linestring->CreateField(&layer_linestring_field_type) != OGRERR_NONE) {
std::cerr << "Creating type field failed.\n";
exit(1);
}
/**************/
m_layer_polygon = m_data_source->CreateLayer("multipolygons", &sparef, wkbMultiPolygon, nullptr);
if (!m_layer_polygon) {
std::cerr << "Layer creation failed.\n";
exit(1);
}
OGRFieldDefn layer_polygon_field_id("id", OFTInteger);
layer_polygon_field_id.SetWidth(10);
if (m_layer_polygon->CreateField(&layer_polygon_field_id) != OGRERR_NONE) {
std::cerr << "Creating id field failed.\n";
exit(1);
}
OGRFieldDefn layer_polygon_field_from_type("from_type", OFTString);
layer_polygon_field_from_type.SetWidth(1);
if (m_layer_polygon->CreateField(&layer_polygon_field_from_type) != OGRERR_NONE) {
std::cerr << "Creating from_type field failed.\n";
exit(1);
}
}
示例7: writePolygons
void writePolygons(RegionMap* regionMap)
{
char* driverName = (char *)ogrDriver->c_str();
char* outFilePath = (char *)outFile->c_str();
cout << "Creating output file \"" << outFilePath << "\" (\"" << driverName << "\" format)...";
OGRSFDriver* driver = (OGRSFDriver*)OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(ogrDriver->c_str());
if (driver == NULL) {
localExit(new string(string("FATAL: OGR driver \"") + string(driverName) + string("\" is not available.\n")), 1);
}
char* dataSourceName = NULL;
bool cleanupDataSource = false;
if (ogrDriver->compare("KML") == 0 && kmlStyleFile != NULL) {
dataSourceName = tmpnam(NULL);
//mkstemp(dataSourceName);
cleanupDataSource = true;
}
else if (ogrDriver->compare("ESRI Shapefile") == 0) {
string* dsStr = removeFromLastOccurrence(outFilePath, '/');
dsStr = removeFromLastOccurrence((char *)dsStr->c_str(), '\\');
dataSourceName = (char *)dsStr->c_str();
} else {
dataSourceName = outFilePath;
}
OGRDataSource* ds = driver->CreateDataSource(dataSourceName);
if(ds == NULL) {
localExit(new string(string("FATAL: Unable to create output file \"") + string(outFilePath) + string("\"\n")), 1);
}
cout << "[ok]\n";
OGRCoordinateTransformation* transform = NULL;
const string* rmSpatialRefStr = regionMap->getSpatialRef();
if (rmSpatialRefStr != NULL && rmSpatialRefStr->compare("") != 0) {
OGRSpatialReference* spatialRef = new OGRSpatialReference(rmSpatialRefStr->c_str());
transform = OGRCreateCoordinateTransformation(spatialRef, outSpatialRef);
}
char* layerName = (char *)pointToFilename(outFilePath, true)->c_str();
OGRLayer* layer = ds->CreateLayer(layerName, outSpatialRef, wkbPolygon);
layer->CreateField(new OGRFieldDefn("RegionID", OFTInteger), 0);
layer->CreateField(new OGRFieldDefn("Category", OFTString), 0);
layer->CreateField(new OGRFieldDefn("Threshold", OFTReal), 0);
cout << "Writing polygon data to file...";
int count = 0;
int currRegionID = 0;
int numRegions = regionMap->getNumRegions();
while (currRegionID < numRegions) {
Region *currRegion = regionMap->getRegion(currRegionID);
Polygon* poly = currRegion->toPolygon();
if(poly == NULL) {
currRegionID += 1;
continue;
}
count++;
OGRFeature* feature = new OGRFeature(layer->GetLayerDefn());
feature->SetField(feature->GetFieldIndex("RegionID"), currRegionID);
feature->SetField(feature->GetFieldIndex("Category"), currRegion->getCategory()->getName()->c_str());
feature->SetField(feature->GetFieldIndex("Threshold"), currRegion->getCategory()->minThreshold());
OGRGeometry* geom = BuildOgrPolygon(poly, transform);
feature->SetGeometry(geom);
if (layer->CreateFeature(feature) != OGRERR_NONE)
localExit(new string("ERROR: Unable to create feature for region #\n"), 2);
//OGRFeature::DestroyFeature(feature);
currRegionID += 1;
if (currRegionID % 100 == 0)
cout << ".";
}
//CPLFree(transform);
//CPLFree(layer);
OGRDataSource::DestroyDataSource(ds);
cout << "[ok] Wrote "<< count << " polygons\n";
if(kmlStyleFile != NULL) {
#ifdef USE_XALAN
XALAN_USING_XERCES(XMLPlatformUtils)
XALAN_USING_XALAN(XalanTransformer)
XMLPlatformUtils::Initialize();
XalanTransformer::initialize();
XalanTransformer theXalanTransformer;
cout << "Transforing KML file ..." << outFile->c_str();
if(theXalanTransformer.transform(dataSourceName, kmlStyleFile->c_str(), outFile->c_str()) != 0) {
cout << "[!!]\n";
cout << "ERROR doing XSLT transform using " << kmlStyleFile->c_str() << "\n";
} else {
cout << "...[ok]\n";
}
#endif /* USE_XALAN */
#ifdef USE_LIBXSLT
xsltStylesheetPtr cur = NULL;
xmlDocPtr doc, res;
//.........这里部分代码省略.........
示例8: layer_nodes_field_id
TestOverviewHandler(const std::string& driver_name, const std::string& filename) {
OGRRegisterAll();
OGRSFDriver* driver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(driver_name.c_str());
if (!driver) {
std::cerr << driver_name << " driver not available.\n";
exit(1);
}
CPLSetConfigOption("OGR_SQLITE_SYNCHRONOUS", "FALSE");
const char* options[] = { "SPATIALITE=TRUE", nullptr };
m_data_source = driver->CreateDataSource(filename.c_str(), const_cast<char**>(options));
if (!m_data_source) {
std::cerr << "Creation of output file failed.\n";
exit(1);
}
OGRSpatialReference sparef;
sparef.SetWellKnownGeogCS("WGS84");
// nodes layer
m_layer_nodes = m_data_source->CreateLayer("nodes", &sparef, wkbPoint, nullptr);
if (!m_layer_nodes) {
std::cerr << "Layer creation failed.\n";
exit(1);
}
OGRFieldDefn layer_nodes_field_id("id", OFTReal);
layer_nodes_field_id.SetWidth(10);
if (m_layer_nodes->CreateField(&layer_nodes_field_id) != OGRERR_NONE) {
std::cerr << "Creating id field failed.\n";
exit(1);
}
// labels layer
m_layer_labels = m_data_source->CreateLayer("labels", &sparef, wkbPoint, nullptr);
if (!m_layer_labels) {
std::cerr << "Layer creation failed.\n";
exit(1);
}
OGRFieldDefn layer_labels_field_id("id", OFTReal);
layer_labels_field_id.SetWidth(10);
if (m_layer_labels->CreateField(&layer_labels_field_id) != OGRERR_NONE) {
std::cerr << "Creating id field failed.\n";
exit(1);
}
OGRFieldDefn layer_labels_field_label("label", OFTString);
layer_labels_field_label.SetWidth(30);
if (m_layer_labels->CreateField(&layer_labels_field_label) != OGRERR_NONE) {
std::cerr << "Creating label field failed.\n";
exit(1);
}
// ways layer
m_layer_ways = m_data_source->CreateLayer("ways", &sparef, wkbLineString, nullptr);
if (!m_layer_ways) {
std::cerr << "Layer creation failed.\n";
exit(1);
}
OGRFieldDefn layer_way_field_id("id", OFTReal);
layer_way_field_id.SetWidth(10);
if (m_layer_ways->CreateField(&layer_way_field_id) != OGRERR_NONE) {
std::cerr << "Creating id field failed.\n";
exit(1);
}
OGRFieldDefn layer_way_field_test("test", OFTInteger);
layer_way_field_test.SetWidth(3);
if (m_layer_ways->CreateField(&layer_way_field_test) != OGRERR_NONE) {
std::cerr << "Creating test field failed.\n";
exit(1);
}
}
示例9: _createLayer
//.........这里部分代码省略.........
case GEOS_POLYGON:
gtype = wkbPolygon;
break;
default:
throw HootException("Unexpected geometry type.");
}
OgrOptions options;
if (_ds->GetDriver())
{
// if this is a CSV file
if (_ds->GetDriver()->GetName() == QString("CSV"))
{
// if we're exporting point data, then export with x/y at the front
if (gtype == wkbPoint)
{
options["GEOMETRY"] = "AS_XY";
}
// if we're exporting other geometries then export w/ WKT at the front.
else
{
options["GEOMETRY"] = "AS_WKT";
}
options["CREATE_CSVT"] = "YES";
}
if (_ds->GetDriver()->GetName() == QString("ESRI Shapefile"))
{
options["ENCODING"] = "UTF-8";
}
// Add a Feature Dataset to a ESRI File GeoDatabase if requested
if (_ds->GetDriver()->GetName() == QString("FileGDB"))
{
if (layer->getFdName() != "")
{
options["FEATURE_DATASET"] = layer->getFdName();
// speed up bulk inserts.
options["FGDB_BULK_LOAD"] = "YES";
}
}
}
QString layerName = _prependLayerName + layer->getName();
// Check if the layer exists in the output.
poLayer = _ds->GetLayerByName(layerName.toAscii());
// We only want to add to a layer IFF the config option "ogr.append.data" set
if (poLayer != NULL && _appendData)
{
// Layer exists
_layers[layer->getName()] = poLayer;
// Loop through the fields making sure that they exist in the output. Print a warning if
// they don't exist
OGRFeatureDefn *poFDefn = poLayer->GetLayerDefn();
shared_ptr<const FeatureDefinition> fd = layer->getFeatureDefinition();
for (size_t i = 0; i < fd->getFieldCount(); i++)
{
shared_ptr<const FieldDefinition> f = fd->getFieldDefinition(i);
if (poFDefn->GetFieldIndex(f->getName().toAscii()) == -1)
{
// throw HootException(QString("Error: Unable to find output field: %1 in layer %2.").arg(f->getName()).arg(layerName));
LOG_WARN("Unable to find field: " << QString(f->getName()) << " in layer " << layerName);
}
}
}
else
{
// Layer does not exist
poLayer = _ds->CreateLayer(layerName.toAscii(),
MapReprojector::createWgs84Projection()->Clone(), gtype, options.getCrypticOptions());
if( poLayer == NULL )
{
throw HootException(QString("Layer creation failed. %1").arg(layerName));
}
_layers[layer->getName()] = poLayer;
shared_ptr<const FeatureDefinition> fd = layer->getFeatureDefinition();
for (size_t i = 0; i < fd->getFieldCount(); i++)
{
shared_ptr<const FieldDefinition> f = fd->getFieldDefinition(i);
OGRFieldDefn oField(f->getName().toAscii(), toOgrFieldType(f->getType()));
if (f->getWidth() > 0)
{
oField.SetWidth(f->getWidth());
}
int errCode = poLayer->CreateField(&oField);
if (errCode != OGRERR_NONE)
{
throw HootException(
QString("Error creating field (%1) OGR Error Code: (%2).").arg(f->getName()).arg(QString::number(errCode)));
}
}
} // End layer does not exist
}
示例10: writePolygons
void ShapefileWriter::writePolygons(shared_ptr<const OsmMap> map, const QString& path)
{
OGRRegisterAll();
_removeShapefile(path);
const char *pszDriverName = "ESRI Shapefile";
OGRSFDriver *poDriver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(pszDriverName);
if( poDriver == NULL )
{
throw HootException(QString("%1 driver not available.").arg(pszDriverName));
}
OGRDataSource* poDS = poDriver->CreateDataSource(path.toAscii(), NULL );
if( poDS == NULL )
{
throw HootException(QString("Data source creation failed. %1").arg(path));
}
OgrOptions options;
options["ENCODING"] = "UTF-8";
OGRLayer *poLayer;
QString layerName;
layerName = QFileInfo(path).baseName();
poLayer = poDS->CreateLayer(layerName.toAscii(),
map->getProjection().get(), wkbMultiPolygon,
options.getCrypticOptions());
if( poLayer == NULL )
{
throw HootException(QString("Layer creation failed. %1").arg(path));
}
QStringList shpColumns;
QStringList columns = getColumns(map, ElementType::Unknown);
for (int i = 0; i < columns.size(); i++)
{
OGRFieldDefn oField(columns[i].toAscii(), OFTString);
oField.SetWidth(64);
if( poLayer->CreateField( &oField ) != OGRERR_NONE )
{
throw HootException(QString("Error creating field (%1).").arg(columns[i]));
}
shpColumns.append(poLayer->GetLayerDefn()->GetFieldDefn(i)->GetNameRef());
}
if (_includeInfo)
{
OGRFieldDefn oField("error_circ", OFTReal);
if( poLayer->CreateField( &oField ) != OGRERR_NONE )
{
throw HootException(QString("Error creating field (error:circular)."));
}
_circularErrorIndex = poLayer->GetLayerDefn()->GetFieldCount() - 1;
}
const WayMap& ways = map->getWays();
for (WayMap::const_iterator it = ways.begin(); it != ways.end(); it++)
{
shared_ptr<Way> way = it->second;
if (OsmSchema::getInstance().isArea(way))
{
_writeWayPolygon(map, way, poLayer, columns, shpColumns);
}
}
const RelationMap& relations = map->getRelationMap();
for (RelationMap::const_iterator it = relations.begin(); it != relations.end(); it++)
{
shared_ptr<Relation> relation = it->second;
if (relation->isMultiPolygon())
{
_writeRelationPolygon(map, relation, poLayer, columns, shpColumns);
}
}
OGRDataSource::DestroyDataSource(poDS);
}
示例11: ExportToGISFile
void CDlg_GISDataExchange::ExportToGISFile(LPCTSTR lpszCSVFileName,LPCTSTR lpszShapeFileName, CString GISTypeString )
{
#ifndef _WIN64
m_MessageList.ResetContent ();
CWaitCursor wait;
CCSVParser parser;
int i= 0;
// open csv file
if (parser.OpenCSVFile(lpszCSVFileName))
{
CString message_str;
OGRSFDriver *poDriver;
OGRRegisterAll();
poDriver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(GISTypeString );
if( poDriver == NULL )
{
message_str.Format ( "%s driver not available.", GISTypeString );
m_MessageList.AddString (message_str);
return;
}
OGRDataSource *poDS;
poDS = poDriver->CreateDataSource(lpszShapeFileName, NULL );
if( poDS == NULL )
{
message_str.Format ( "Creation of GIS output file %s failed.\nPlease do not overwrite the exiting file and please select a new file name.",
lpszShapeFileName );
m_MessageList.AddString (message_str);
return;
}
///// export to link layer
// link layer
OGRLayer *poLayer;
poLayer = poDS->CreateLayer( "link", NULL, wkbLineString, NULL );
if( poLayer == NULL )
{
m_MessageList.AddString ("link Layer creation failed");
return;
}
vector<string> HeaderVector = parser.GetHeaderVector();
std::vector <CString> LongFieldVector;
for(unsigned int i = 0; i < HeaderVector.size(); i++)
{
if(HeaderVector[i].find ("geometry") != string::npos|| HeaderVector[i].find ("name") != string::npos || HeaderVector[i].find ("code") != string::npos)
{
OGRFieldDefn oField (HeaderVector[i].c_str (), OFTString);
CString str;
if( poLayer->CreateField( &oField ) != OGRERR_NONE )
{
str.Format("Creating field %s failed", oField.GetNameRef());
m_MessageList.AddString (str);
return;
}
}else
{
CString field_string = HeaderVector[i].c_str ();
OGRFieldDefn oField (field_string, OFTReal);
CString str;
if( poLayer->CreateField( &oField ) != OGRERR_NONE )
{
str.Format("Creating field %s failed", oField.GetNameRef());
m_MessageList.AddString (str);
return;
}
}
if(HeaderVector[i].size()>=11)
{
LongFieldVector.push_back (HeaderVector[i].c_str ());
}
}
message_str.Format ("%d fields have been created.",HeaderVector.size());
m_MessageList.AddString (message_str);
//.........这里部分代码省略.........
示例12: createLayer
bool NgwGdalIo::createLayer (int &new_layer_id, const NgwLayerInfo &layer_info, QString base_url,
int resource_group_id, QString base_url_copy_features, int layer_id_copy_features)
{
GDALDatasetPtr dataset_p;
u_openDataset(dataset_p, base_url, resource_group_id, false);
if (dataset_p.data() == NULL)
{
error = QObject::tr("Unable to open NGW dataset via GDAL");
return false;
}
QByteArray ba_name(layer_info.name.toUtf8());
OGRwkbGeometryType geom_type = Core::g_findGeomTypeGdal(layer_info.geom_type);
OGRSpatialReference *srs = new OGRSpatialReference();
srs->importFromEPSG(3857);
char **papszOptions = NULL;
papszOptions = CSLAddString(papszOptions, "OVERWRITE=NO");
OGRLayer *layer = dataset_p.data()->CreateLayer(ba_name.data(), srs, geom_type, papszOptions);
CSLDestroy(papszOptions);
OSRRelease(srs);
if (layer == NULL)
{
error = QObject::tr("Unable to create NGW layer via GDAL");
error += QString("\nGDAL error: %1").arg(CPLGetLastErrorMsg());
return false;
}
for (int i = 0; i < layer_info.fields.size(); i++)
{
QByteArray ba_field_name = std::get<0>(layer_info.fields[i]).toUtf8();
OGRFieldType field_type = Core::g_findFieldTypeGdal(std::get<2>(layer_info.fields[i]));
OGRFieldDefn field_defn(ba_field_name.data(), field_type);
layer->CreateField(&field_defn);
// TEMP. There may be another way to create field aliases via GDAL in future.
QString s_field_alias = QString("FIELD_%1_ALIAS").arg(i);
layer->SetMetadataItem(s_field_alias.toUtf8().data(),
std::get<1>(layer_info.fields[i]).toUtf8().data());
// TODO: delete layer if the creation of field was not successfull? What if at the time
// between creation and this deletion some other layer have been created outside? How to
// remove layer in GDAL not by layer index & how to properly get index of a layer in
// GDALDataset?
}
layer->SyncToDisk(); // otherwise NGW id of created resource will not be assigned to the new layer
auto metadata = layer->GetMetadata("");
QString s_new_layer_id = {CSLFetchNameValue(metadata, "id")};
new_layer_id = s_new_layer_id.toInt();
if (base_url_copy_features != "" && layer_id_copy_features != -1)
{
// TODO (important): here we need own credentioals for dataset_p2 !
GDALDatasetPtr dataset_p2;
u_openDataset(dataset_p2, base_url_copy_features.toUtf8().data(), layer_id_copy_features, true);
if (dataset_p2.data() == NULL)
{
// TODO: warning
error = QObject::tr("Unable to open NGW dataset to copy features from");
//return false;
}
else
{
OGRLayer *layer2 = dataset_p2.data()->GetLayer(0);
if (layer2 == NULL)
{
// TODO: warning
error = QObject::tr("Unable to open NGW layer to copy features from");
//return false;
}
else
{
layer2->ResetReading();
OGRFeature *feature;
while ((feature = layer2->GetNextFeature()) != NULL)
{
layer->CreateFeature(feature);
OGRFeature::DestroyFeature(feature);
}
layer->SyncToDisk();
}
}
}
return true;
}
示例13: processSerie
void processSerie(GeoVectorSerie& Serie)
{
QString IndexStr = "init";
openfluid::base::SimulationStatus::SimulationStage CurrentStage =
OPENFLUID_GetCurrentStage();
bool OKToWrite = false;
if (CurrentStage == openfluid::base::SimulationStatus::INITIALIZERUN)
{
OKToWrite = Serie.WhenMode == GeoVectorSerie::WHENINIT ||
Serie.WhenMode == GeoVectorSerie::WHENCONTINUOUS;
}
else if (CurrentStage == openfluid::base::SimulationStatus::RUNSTEP)
{
if (Serie.WhenMode == GeoVectorSerie::WHENCONTINUOUS)
{
openfluid::core::TimeIndex_t CurrentIndex = OPENFLUID_GetCurrentTimeIndex();
IndexStr = QString("%1").arg(CurrentIndex);
if (Serie.LatestContinuousIndex + Serie.WhenContinuousDelay < CurrentIndex)
{
OKToWrite = true;
Serie.LatestContinuousIndex = CurrentIndex;
}
}
}
else if (CurrentStage == openfluid::base::SimulationStatus::FINALIZERUN)
{
IndexStr = "final";
OKToWrite = Serie.WhenMode == GeoVectorSerie::WHENCONTINUOUS ||
Serie.WhenMode == GeoVectorSerie::WHENFINAL;
}
else
{
OPENFLUID_LogWarning("Internal stage error when processing geographic series");
return;
}
if (OKToWrite)
{
std::string FullFilePath =
m_OutputPath + "/" + QString(QString::fromStdString(Serie.OutfilePattern).arg(IndexStr)).toStdString();
GDALDriver_COMPAT* Driver = GDALGetDriverByName_COMPAT(m_GDALFormat.c_str());
if (openfluid::tools::Filesystem::isFile(FullFilePath))
{
// deletion of an existing file or files set
GDALDelete_COMPAT(Driver,FullFilePath.c_str());
}
GDALDataset_COMPAT* CreatedFile = GDALCreate_COMPAT(Driver,FullFilePath.c_str());
std::string CreatedLayerName = QFileInfo(QString::fromStdString(FullFilePath)).completeBaseName().toStdString();
OGRLayer* CreatedLayer = CreatedFile->CreateLayer(CreatedLayerName.c_str(),nullptr,
Serie.GeoLayer->GetLayerDefn()->GetGeomType(),
nullptr);
OGRFieldDefn IDField("OFLD_ID",OFTInteger);
CreatedLayer->CreateField(&IDField);
GeoVectorSerie::VariablesSet_t::const_iterator itV;
GeoVectorSerie::VariablesSet_t::const_iterator itVb = Serie.VariablesSet.begin();
GeoVectorSerie::VariablesSet_t::const_iterator itVe = Serie.VariablesSet.end();
for (itV = itVb; itV != itVe; ++itV)
{
std::string FieldName = (*itV).second;
OGRFieldDefn VarField(FieldName.c_str(),OFTReal);
VarField.SetWidth(24);
VarField.SetPrecision(15);
CreatedLayer->CreateField(&VarField);
}
OGRFeature* SourceFeature;
openfluid::core::SpatialUnit* UU;
Serie.GeoLayer->ResetReading();
while ((SourceFeature = Serie.GeoLayer->GetNextFeature()) != nullptr)
{
int SourceID = SourceFeature->GetFieldAsInteger(Serie.OFLDIDFieldIndex);
UU = OPENFLUID_GetUnit(Serie.UnitsClass,SourceID);
if (UU)
{
CreatedLayer->GetLayerDefn();
OGRFeature* CreatedFeature = OGRFeature::CreateFeature(CreatedLayer->GetLayerDefn());
//.........这里部分代码省略.........
示例14: CacheLayer
bool GdaCache::CacheLayer(std::string ext_ds_name,
OGRLayerProxy* ext_layer_proxy)
{
OGRLayer* poSrcLayer = ext_layer_proxy->layer;
// get information from current layer: geomtype, layer_name
// (NOTE: we don't consider coodinator system and translation here)
OGRFeatureDefn *poSrcFDefn = poSrcLayer->GetLayerDefn();
int eGType = poSrcFDefn->GetGeomType();
const char* pszNewLayerName = poSrcLayer->GetName();
int bForceToPolygon = FALSE;
int bForceToMultiPolygon = FALSE;
int bForceToMultiLineString = FALSE;
if( wkbFlatten(eGType) == wkbPolygon )
bForceToPolygon = TRUE;
else if( wkbFlatten(eGType) == wkbMultiPolygon )
bForceToMultiPolygon = TRUE;
else if( wkbFlatten(eGType) == wkbMultiLineString )
bForceToMultiLineString = TRUE;
//Setup coordinate transformation if we need it.
OGRCoordinateTransformation *poCT = NULL;
bool bTransform = FALSE;
OGRSpatialReference *poSourceSRS = NULL;
// todo
OGRSpatialReference *poOutputSRS = new OGRSpatialReference("EPSG:4326");
// Cache
char *papszLCO[] = {"OVERWRITE=yes","FORMAT=Spatialite"};
std::string cache_layer_name = ext_ds_name + "_"+ext_layer_proxy->name;
OGRDataSource *poDstDS = cach_ds_proxy->ds;
OGRLayer *poDstLayer = poDstDS->CreateLayer(cache_layer_name.c_str(),
poOutputSRS,
(OGRwkbGeometryType)eGType,
papszLCO);
if (poDstLayer == NULL) {
// raise create cache failed.
return false;
}
// Process Layer style table
poDstLayer->SetStyleTable( poSrcLayer->GetStyleTable () );
// Add fields. here to copy all field.
int nSrcFieldCount = poSrcFDefn->GetFieldCount();
int iField;
OGRFeatureDefn *poDstFDefn = poDstLayer->GetLayerDefn();
for( iField = 0; iField < nSrcFieldCount; iField++ )
{
OGRFieldDefn* poSrcFieldDefn = poSrcFDefn->GetFieldDefn(iField);
OGRFieldDefn oFieldDefn( poSrcFieldDefn );
// The field may have been already created at layer creation
if (poDstLayer->CreateField( &oFieldDefn ) == OGRERR_NONE)
{
// now that we've created a field, GetLayerDefn() won't return NULL
if (poDstFDefn == NULL)
poDstFDefn = poDstLayer->GetLayerDefn();
}
}
// Transfer feature from Source Layer to Dest Layer
OGRFeature *poFeature;
GIntBig nFeaturesWritten = 0;
poSrcLayer->ResetReading();
while (poFeature = poSrcLayer->GetNextFeature())
{
OGRFeature *poDstFeature = OGRFeature::CreateFeature(
poDstLayer->GetLayerDefn() );
poDstFeature->SetFrom(poFeature);
OGRGeometry *poDstGeometry = poDstFeature->GetGeometryRef();
if (poDstGeometry != NULL)
{
if( bForceToPolygon )
{
poDstFeature->SetGeometryDirectly(
OGRGeometryFactory::forceToPolygon(
poDstFeature->StealGeometry()));
}
else if( bForceToMultiPolygon )
{
poDstFeature->SetGeometryDirectly(
OGRGeometryFactory::forceToMultiPolygon(
poDstFeature->StealGeometry() ) );
}
else if ( bForceToMultiLineString )
{
poDstFeature->SetGeometryDirectly(
OGRGeometryFactory::forceToMultiLineString(
poDstFeature->StealGeometry() ) );
}
}
if( poDstLayer->CreateFeature( poDstFeature ) == OGRERR_NONE )
{
nFeaturesWritten ++;
}
OGRFeature::DestroyFeature( poDstFeature );
//.........这里部分代码省略.........
示例15: main
int main(int argc, char **argv)
{
// Get data from ogr
OGRRegisterAll();
std::cout << "Opening: " << argv[1] << std::endl;
OGRDataSource *shp = OGRSFDriverRegistrar::Open(argv[1], FALSE);
IsValid(shp, "Error opening file.");
std::cout << "Shape contains " << shp->GetLayerCount() << " layers." << std::endl;
OGRLayer *layer = shp->GetLayerByName(argv[2]);
IsValid(layer, "Couldn't grab layer");
OGRSpatialReference *srcSRS = NULL;
srcSRS = layer->GetSpatialRef();
// Set up writing
const char *kDriverName = "ESRI Shapefile";
OGRSFDriver *shpDriver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(kDriverName);
IsValid(shpDriver, "Couldn't grab the shapefile driver.");
IsValid(argv[3], "Please provide a output shp.");
std::cout << "Writing to: " << argv[3] << std::endl;
OGRDataSource *shpOut = shpDriver->CreateDataSource(argv[3], NULL);
IsValid(shpOut, "Couldn't open output file");
OGRLayer *outLayer = shpOut->CreateLayer(layer->GetName(), srcSRS, wkbMultiLineString, NULL);
IsValid(outLayer, "Couldn't create an output layer");
// copy over the fields from the source file
OGRFeatureDefn *source = layer->GetLayerDefn();
for(int i=0; i < source->GetFieldCount(); i++){
OGRFieldDefn *field = source->GetFieldDefn(i);
if(outLayer->CreateField(field) != OGRERR_NONE) {
std::cout << "Couldn't make layer" << std::endl; exit(1);
};
}
// Loop through features and grab the hull and put it into CGAL then
// skeletonize the points
OGRFeature *feature;
int count = 0;
while((feature = layer->GetNextFeature()) != NULL)
{
OGRMultiPolygon *geometry = dynamic_cast<OGRMultiPolygon *>(OGRGeometryFactory::forceToMultiPolygon(feature->GetGeometryRef()));
IsValid(geometry, "No geometry.");
OGRFeature *outFeature = OGRFeature::CreateFeature(outLayer->GetLayerDefn());
IsValid(outFeature, "Couldn't make a feature.");
for(int i=0; i < source->GetFieldCount(); i++){
OGRField *field = feature->GetRawFieldRef(i);
outFeature->SetField(i, field);
}
OGRGeometry* line = NULL;
for(int i=0; i < geometry->getNumGeometries(); i++){
OGRGeometry* segment = BuildMultiLine(geometry->getGeometryRef(i));
if(segment != NULL){
if(line == NULL) { line = new OGRLineString; }
OGRGeometry* tmp = line->Union(segment);
if(tmp != NULL){
delete line;
line = tmp;
}
delete segment;
}
}
outFeature->SetGeometry(line);
if(outLayer->CreateFeature(outFeature) != OGRERR_NONE){
std::cout << "Couldn't create feature." << std::endl;
exit(1);
}
// clean up
OGRFeature::DestroyFeature(outFeature);
std::cout << std::endl << ++count << std::endl;
}
// cleanup
OGRDataSource::DestroyDataSource(shp);
OGRDataSource::DestroyDataSource(shpOut);
return 0;
}