示例#1
0
void OGRFeature::SetField( int iField, double dfValue )

{
    OGRFieldDefn        *poFDefn = poDefn->GetFieldDefn( iField );

    CPLAssert( poFDefn != NULL || iField == -1 );
    if( poFDefn == NULL )
        return;
    
    if( poFDefn->GetType() == OFTReal )
    {
        pauFields[iField].Real = dfValue;
    }
    else if( poFDefn->GetType() == OFTInteger )
    {
        pauFields[iField].Integer = (int) dfValue;
        pauFields[iField].Set.nMarker2 = 0;
    }
    else if( poFDefn->GetType() == OFTString )
    {
        char    szTempBuffer[128];

        sprintf( szTempBuffer, "%.16g", dfValue );

        if( IsFieldSet( iField) )
            CPLFree( pauFields[iField].String );

        pauFields[iField].String = CPLStrdup( szTempBuffer );
    }
    else
        /* do nothing for other field types */;
}
示例#2
0
void OGRFeature::SetField( int iField, const char * pszValue )

{
    OGRFieldDefn        *poFDefn = poDefn->GetFieldDefn( iField );

    CPLAssert( poFDefn != NULL || iField == -1 );
    if( poFDefn == NULL )
        return;
    
    if( poFDefn->GetType() == OFTString )
    {
        if( IsFieldSet(iField) )
            CPLFree( pauFields[iField].String );
            
        pauFields[iField].String = CPLStrdup( pszValue );
    }
    else if( poFDefn->GetType() == OFTInteger )
    {
        pauFields[iField].Integer = atoi(pszValue);
        pauFields[iField].Set.nMarker2 = OGRUnsetMarker;
    }
    else if( poFDefn->GetType() == OFTReal )
    {
        pauFields[iField].Real = atof(pszValue);
    }
    else
        /* do nothing for other field types */;
}
示例#3
0
double OGRFeature::GetFieldAsDouble( int iField )

{
    OGRFieldDefn        *poFDefn = poDefn->GetFieldDefn( iField );
    
    CPLAssert( poFDefn != NULL || iField == -1 );
    if( poFDefn == NULL )
        return 0.0;

    if( !IsFieldSet(iField) )
        return 0.0;
    
    if( poFDefn->GetType() == OFTReal )
        return pauFields[iField].Real;
    else if( poFDefn->GetType() == OFTInteger )
        return pauFields[iField].Integer;
    else if( poFDefn->GetType() == OFTString )
    {
        if( pauFields[iField].String == NULL )
            return 0;
        else
            return atof(pauFields[iField].String);
    }
    else
        return 0.0;
}
示例#4
0
const double *OGRFeature::GetFieldAsDoubleList( int iField, int *pnCount )

{
    OGRFieldDefn        *poFDefn = poDefn->GetFieldDefn( iField );

    CPLAssert( poFDefn != NULL || iField == -1 );
    if( poFDefn == NULL )
        return NULL;
    
    if( !IsFieldSet(iField) )
        return NULL;
    
    if( poFDefn->GetType() == OFTRealList )
    {
        if( pnCount != NULL )
            *pnCount = pauFields[iField].RealList.nCount;

        return pauFields[iField].RealList.paList;
    }
    else
    {
        if( pnCount != NULL )
            *pnCount = 0;
        
        return NULL;
    }
}
示例#5
0
void OGRFeature::UnsetField( int iField )

{
    OGRFieldDefn        *poFDefn = poDefn->GetFieldDefn( iField );

    CPLAssert( poFDefn != NULL || iField == -1 );
    if( poFDefn == NULL || !IsFieldSet(iField) )
        return;
    
    switch( poFDefn->GetType() )
    {
      case OFTRealList:
      case OFTIntegerList:
        CPLFree( pauFields[iField].IntegerList.paList );
        break;

      case OFTStringList:
        CSLDestroy( pauFields[iField].StringList.paList );
        break;

      case OFTString:
        CPLFree( pauFields[iField].String );
        break;

      default:
        break;
    }

    pauFields[iField].Set.nMarker1 = OGRUnsetMarker;
    pauFields[iField].Set.nMarker2 = OGRUnsetMarker;
}
示例#6
0
//---------------------------------------------------------
CSG_Shapes * COGR_DataSource::Read_Shapes(int iLayer)
{
	OGRLayer	*pLayer	= Get_Layer(iLayer);

	//-----------------------------------------------------
	if( pLayer && Get_Type(iLayer) != SHAPE_TYPE_Undefined )
	{
		int				iField;
		OGRFeature		*pFeature;
		OGRFeatureDefn	*pDef		= pLayer->GetLayerDefn();
		CSG_Shapes		*pShapes	= SG_Create_Shapes(Get_Type(iLayer), CSG_String(pDef->GetName()));

		for(iField=0; iField<pDef->GetFieldCount(); iField++)
		{
			OGRFieldDefn	*pDefField	= pDef->GetFieldDefn(iField);

			pShapes->Add_Field(pDefField->GetNameRef(), COGR_Driver::Get_Type(pDefField->GetType()));
		}

		pLayer->ResetReading();

		//-------------------------------------------------
		while( (pFeature = pLayer->GetNextFeature()) != NULL && SG_UI_Process_Get_Okay(false) )
		{
			OGRGeometry	*pGeometry	= pFeature->GetGeometryRef();

			if( pGeometry != NULL )
			{
				CSG_Shape	*pShape	= pShapes->Add_Shape();

				for(iField=0; iField<pDef->GetFieldCount(); iField++)
				{
					OGRFieldDefn	*pDefField	= pDef->GetFieldDefn(iField);

					switch( pDefField->GetType() )
					{
					default:			pShape->Set_Value(iField, SG_STR_MBTOSG(pFeature->GetFieldAsString (iField)));	break;
					case OFTString:		pShape->Set_Value(iField, SG_STR_MBTOSG(pFeature->GetFieldAsString (iField)));	break;
					case OFTInteger:	pShape->Set_Value(iField, pFeature->GetFieldAsInteger(iField));	break;
					case OFTReal:		pShape->Set_Value(iField, pFeature->GetFieldAsDouble (iField));	break;
					}
				}

				//-----------------------------------------
				if( _Read_Geometry(pShape, pGeometry) == false )
				{
					pShapes->Del_Shape(pShape);
				}
			}

			OGRFeature::DestroyFeature(pFeature);
		}

		return( pShapes );
	}

	//-----------------------------------------------------
	return( NULL );
}
示例#7
0
OGRErr OGRILI2Layer::ICreateFeature( OGRFeature *poFeature ) {
    char szTempBuffer[80];
    const char* tid;
    int iField = 0;
    if( poFeatureDefn->GetFieldCount() &&
        EQUAL(poFeatureDefn->GetFieldDefn(iField)->GetNameRef(), "TID") )
    {
        tid = poFeature->GetFieldAsString(0);
        ++iField;
    }
    else
    {
        snprintf( szTempBuffer, sizeof(szTempBuffer), CPL_FRMT_GIB,
                  poFeature->GetFID() );
        tid = szTempBuffer;
    }

    VSILFILE* fp = poDS->GetOutputFP();
    if (fp == NULL)
        return OGRERR_FAILURE;

    VSIFPrintfL(fp, "<%s TID=\"%s\">\n", poFeatureDefn->GetName(), tid);

    // Write out Geometries
    for( int iGeomField = 0;
         iGeomField < poFeatureDefn->GetGeomFieldCount();
         iGeomField++ )
    {
        OGRGeomFieldDefn *poFieldDefn
            = poFeatureDefn->GetGeomFieldDefn(iGeomField);
        OGRGeometry* poGeom = poFeature->GetGeomFieldRef(iGeomField);
        if( poGeom != NULL )
        {
            CPLString iliGeomType = GetIliGeomType(poFieldDefn->GetNameRef());
            OGR2ILIGeometryAppend( poGeom, fp, poFieldDefn->GetNameRef(),
                                   iliGeomType );
        }
    }

    // Write all "set" fields.
    for( ; iField < poFeatureDefn->GetFieldCount(); iField++ )
    {

        OGRFieldDefn *poField = poFeatureDefn->GetFieldDefn( iField );

        if( poFeature->IsFieldSet( iField ) )
        {
            const char *pszRaw = poFeature->GetFieldAsString( iField );
            VSIFPrintfL(fp, "<%s>%s</%s>\n", poField->GetNameRef(), pszRaw, poField->GetNameRef());
        }
    }

    VSIFPrintfL(fp, "</%s>\n", poFeatureDefn->GetName());

    return OGRERR_NONE;
}
示例#8
0
文件: tableview.cpp 项目: jacklibj/r5
wxString wxGISTable::GetColLabelValue(int col)
{
    wxString label;
    OGRFieldDefn* pOGRFieldDefn = m_pOGRFeatureDefn->GetFieldDefn(col);
    label = wgMB2WX(pOGRFieldDefn->GetNameRef());
    if(!m_sFIDKeyName.IsEmpty())
    {
        if(label == m_sFIDKeyName);
        label += _(" [*]");
    }
    return label;
}
int main() {
    // Read in raster data for night time lights
    int band_number = 1; // only one band, starts with one
    Raster* raster = import_raster("raster.tif", band_number);

    // Read in shapefile data containing municipality administrative regions
    int layer_number = 0; // only one layer, starts with zero
    OGRLayer* shapelayer = import_shapefile("MEX_adm2.shp", layer_number);

    shapelayer->SetAttributeFilter("ID_1 = 1834");       // Filter for Yucatan
    const int idx_of_number_field = 5;             // Column number of municipality number
    const int idx_of_name_field = 6;               // Column number of municipality name

    OGRFeature* poFeature;
    int feature_ctr = 0;
    while( (poFeature = shapelayer->GetNextFeature()) != NULL ) {
        cerr << "Feature: " << feature_ctr++ << "\t";
        int feature_num = poFeature->GetFieldAsInteger(idx_of_number_field);
        string feature_name = poFeature->GetFieldAsString(idx_of_name_field);

        OGRFeatureDefn *poFDefn = shapelayer->GetLayerDefn();
        for( int iField = 0; iField < poFDefn->GetFieldCount(); iField++ ) {
            OGRFieldDefn *poFieldDefn = poFDefn->GetFieldDefn( iField );
            if( poFieldDefn->GetType() == OFTString )  cerr << poFeature->GetFieldAsString(iField) << ",";
        }

        OGRGeometry* poGeometry = poFeature->GetGeometryRef();
        if( poGeometry != NULL) {
            // For contiguous regions
            if ( wkbFlatten(poGeometry->getGeometryType()) == wkbPolygon ) {
                cerr << " polygon" << endl;
                report_raster_data_within_polygon(raster, (OGRPolygon *) poGeometry, feature_num, feature_name);
            // For disjoint regions
            } else if ( wkbFlatten(poGeometry->getGeometryType()) == wkbMultiPolygon ) {
                cerr << " multipolygon" << endl;
                OGRMultiPolygon *multipolygon = (OGRMultiPolygon *) poGeometry;
                for (int i = 0; i<multipolygon->getNumGeometries(); i++) {
                    report_raster_data_within_polygon(raster, (OGRPolygon*) multipolygon->getGeometryRef(i), feature_num, feature_name);
                }
            // Is this really the right shapefile?
            } else {
                cerr << "No polygon or multipolygon geometry for this feature: " << poGeometry->getGeometryName() << endl;
            }
        } else {
            cerr << "No geometry for this feature" << endl;
        }
    }
    OGRFeature::DestroyFeature( poFeature );
}
示例#10
0
GByte *OGRMIAttrIndex::BuildKey( OGRField *psKey )

{
    GByte* ret = nullptr;
    switch( poFldDefn->GetType() )
    {
      case OFTInteger:
        ret = poINDFile->BuildKey( iIndex, psKey->Integer );
        break;

      case OFTInteger64:
      {
        if( !CPL_INT64_FITS_ON_INT32(psKey->Integer64) )
        {
            CPLError(CE_Warning, CPLE_NotSupported,
                     "64bit integer value passed to OGRMIAttrIndex::BuildKey()");
        }
        ret = poINDFile->BuildKey( iIndex, static_cast<int>(psKey->Integer64) );
        break;
      }

      case OFTReal:
        ret = poINDFile->BuildKey( iIndex, psKey->Real );
        break;

      case OFTString:
        ret = poINDFile->BuildKey( iIndex, psKey->String );
        break;

      default:
        CPLAssert( false );
        break;
    }
    return ret;
}
示例#11
0
GByte *OGRMIAttrIndex::BuildKey( OGRField *psKey )

{
    switch( poFldDefn->GetType() )
    {
      case OFTInteger:
        return poINDFile->BuildKey( iIndex, psKey->Integer );
        break;

      case OFTInteger64:
      {
        if( !CPL_INT64_FITS_ON_INT32(psKey->Integer64) )
        {
            CPLError(CE_Warning, CPLE_NotSupported,
                     "64bit integer value passed to OGRMIAttrIndex::BuildKey()");
        }
        return poINDFile->BuildKey( iIndex, (int)psKey->Integer64 );
        break;
      }

      case OFTReal:
        return poINDFile->BuildKey( iIndex, psKey->Real );
        break;

      case OFTString:
        return poINDFile->BuildKey( iIndex, psKey->String );
        break;

      default:
        CPLAssert( FALSE );

        return NULL;
    }
}
示例#12
0
json_object* OGRGMEAttributesToGeoJSON( OGRFeature* poFeature )
{
    if ( NULL == poFeature )
        return NULL;
    json_object* pjoProperties = json_object_new_object();
    CPLAssert( NULL != pjoProperties );

    OGRFeatureDefn* poDefn = poFeature->GetDefnRef();
    for( int nField = 0; nField < poDefn->GetFieldCount(); ++nField ) {
        json_object* pjoProperty = NULL;
        OGRFieldDefn* poFieldDefn = poDefn->GetFieldDefn( nField );
        if ( NULL == poFieldDefn )
            continue;
        OGRFieldType eType = poFieldDefn->GetType();

        if( !poFeature->IsFieldSet(nField) )
            pjoProperty = NULL;

        // In GME integers are encoded as strings.
        else if( OFTInteger == eType )
            pjoProperty = json_object_new_string( poFeature->GetFieldAsString( nField ) );

        else if( OFTReal == eType )
            pjoProperty = json_object_new_gme_double( poFeature->GetFieldAsDouble(nField) );

        // Supported types are integer, double and string. So treating everything else as strings
        else
            pjoProperty = json_object_new_string( poFeature->GetFieldAsString(nField) );

        json_object_object_add( pjoProperties, poFieldDefn->GetNameRef(), pjoProperty );
    }
    int nGxId = poFeature->GetFieldIndex("gx_id");
    if (nGxId < 0) {
        json_object* pjoProperty = NULL;
        GIntBig nFID = poFeature->GetFID();

        char acGxId[128];
        snprintf(acGxId, 128, "GDAL-" CPL_FRMT_GIB, nFID);
        CPLDebug("GME", "gx_id is not set, so adding \"gx_id\": \"%s\" field.",
                 acGxId);

        pjoProperty = json_object_new_string( acGxId );
        json_object_object_add( pjoProperties, "gx_id", pjoProperty);
    }

    return pjoProperties;
}
示例#13
0
wxString wxGISGridTable::GetColLabelValue(int col)
{
    wxString label;
    OGRFeatureDefn* pOGRFeatureDefn = m_pGISDataset->GetDefinition();
    if(!pOGRFeatureDefn)
        return wxEmptyString;

	OGRFieldDefn* pOGRFieldDefn = pOGRFeatureDefn->GetFieldDefn(col);
	if(pOGRFieldDefn)
		label = wxString(pOGRFieldDefn->GetNameRef(), wxConvUTF8);

    if(label.IsSameAs(m_pGISDataset->GetFIDColumn(), false))
    {
        label.Append(_(" [*]"));
	}
    return label;
}
示例#14
0
OGRFeatureDefn * cvct2gdal::CVCT2GDALFeatureDefn ( VCTFeatureDefn * poVCTFeatDefn )
{
	OGRFeatureDefn * poOGRFeatDefn = new OGRFeatureDefn();

	for ( auto iVCTFieldDefn = poVCTFeatDefn->fielddefnlist.begin();
	        iVCTFieldDefn != poVCTFeatDefn->fielddefnlist.end(); ++iVCTFieldDefn )
	{
		OGRFieldDefn oOGRFieldDefn ( "", OFTInteger );
		oOGRFieldDefn.SetName ( iVCTFieldDefn->name.c_str() );
		oOGRFieldDefn.SetWidth ( iVCTFieldDefn->width );
		oOGRFieldDefn.SetPrecision ( iVCTFieldDefn->precision );
		oOGRFieldDefn.SetType ( CVCT2GDALFieldType ( iVCTFieldDefn->type ) );
		poOGRFeatDefn->AddFieldDefn ( &oOGRFieldDefn );
	}

	return poOGRFeatDefn;
}
示例#15
0
void OGRFeature::SetField( int iField, int nCount, double * padfValues )

{
    OGRFieldDefn        *poFDefn = poDefn->GetFieldDefn( iField );

    CPLAssert( poFDefn != NULL || iField == -1 );
    if( poFDefn == NULL )
        return;
    
    if( poFDefn->GetType() == OFTRealList )
    {
        OGRField        uField;
        
        uField.RealList.nCount = nCount;
        uField.RealList.paList = padfValues;
        
        SetField( iField, &uField );
    }
}
bool TeOGRDriver::createAttributeTable(TeTable &table)
{
	if(ogrLayer_ == 0)
		return false;

	TeAttributeList::iterator it;
	TeAttributeList list = table.attributeList();
	for(it = list.begin(); it != list.end(); ++it)
	{
		OGRFieldDefn oField = Convert2OGR(*it);
		
		if((*it).rep_.type_ == TeSTRING)
			oField.SetWidth((*it).rep_.numChar_);
		
		if(ogrLayer_->CreateField(&oField) != OGRERR_NONE)
			return false;
	}
	return true;
}
示例#17
0
void OGRFeature::SetField( int iField, char ** papszValues )

{
    OGRFieldDefn        *poFDefn = poDefn->GetFieldDefn( iField );

    CPLAssert( poFDefn != NULL || iField == -1 );
    if( poFDefn == NULL )
        return;
    
    if( poFDefn->GetType() == OFTStringList )
    {
        OGRField        uField;
        
        uField.StringList.nCount = CSLCount(papszValues);
        uField.StringList.paList = papszValues;
        
        SetField( iField, &uField );
    }
}
示例#18
0
QDebug operator<<(QDebug dbg, OGRLayer* layer)
{
    layer->ResetReading();
    OGRFeatureDefn* def = layer->GetLayerDefn();
    FeaturePtr feat;
    while ((feat = FeaturePtr(layer->GetNextFeature())) != nullptr)
    {
        for (int i = 0; i < def->GetFieldCount(); ++i)
        {
            OGRFieldDefn* fdef = def->GetFieldDefn(i);
            switch (fdef->GetType())
            {
            case OFTInteger:
                dbg << fdef->GetNameRef() << feat->GetFieldAsInteger(i);
                break;
            case OFTReal:
                dbg << fdef->GetNameRef() << feat->GetFieldAsDouble(i);
                break;
            case OFTString:
                dbg << fdef->GetNameRef() << feat->GetFieldAsString(i);
                break;
            default:
                dbg << "Unknown type:" << fdef->GetType();
            }
        }
        dbg << "-----";
    }

    return dbg;
}
示例#19
0
OGRFeature::~OGRFeature()

{
    poDefn->Dereference();

    if( poGeometry != NULL )
        delete poGeometry;

    for( int i = 0; i < poDefn->GetFieldCount(); i++ )
    {
        OGRFieldDefn    *poFDefn = poDefn->GetFieldDefn(i);
        
        if( !IsFieldSet(i) )
            continue;
    
        switch( poFDefn->GetType() )
        {
          case OFTString:
            if( pauFields[i].String != NULL )
                VSIFree( pauFields[i].String );
            break;

          case OFTStringList:
            CSLDestroy( pauFields[i].StringList.paList );
            break;

          case OFTIntegerList:
          case OFTRealList:
            CPLFree( pauFields[i].IntegerList.paList );
            break;

          default:
            // should add support for wide strings.
            break;
        }
    }
    
    CPLFree( pauFields );
}
示例#20
0
wxString wxGISFeatureDataset::GetAsString(int row, int col)
{
	if(m_poLayer->GetFeatureCount() <= row) 
		return wxString(); 
	else 
	{
		OGRFeature* pFeature = GetAt(row);
		OGRFieldDefn* pDef = pFeature->GetFieldDefnRef(col);
		switch(pDef->GetType())
		{
		case OFTDate:
			{
				int year, mon, day, hour, min, sec, flag;
				pFeature->GetFieldAsDateTime(col, &year, &mon, &day, &hour, &min, &sec, &flag);
				wxDateTime dt(day, wxDateTime::Month(mon - 1), year, hour, min, sec);
				return dt.Format(_("%d-%m-%Y"));//wxString::Format(_("%.2u-%.2u-%.4u"), day, mon, year );
			}
		case OFTTime:
			{
				int year, mon, day, hour, min, sec, flag;
				pFeature->GetFieldAsDateTime(col, &year, &mon, &day, &hour, &min, &sec, &flag);
				wxDateTime dt(day, wxDateTime::Month(mon - 1), year, hour, min, sec);
				return dt.Format(_("%H:%M:%S"));//wxString::Format(_("%.2u:%.2u:%.2u"), hour, min, sec);
			}
		case OFTDateTime:
			{
				int year, mon, day, hour, min, sec, flag;
				pFeature->GetFieldAsDateTime(col, &year, &mon, &day, &hour, &min, &sec, &flag);
				wxDateTime dt(day, wxDateTime::Month(mon - 1), year, hour, min, sec);
				return dt.Format(_("%d-%m-%Y %H:%M:%S"));//wxString::Format(_("%.2u-%.2u-%.4u %.2u:%.2u:%.2u"), day, mon, year, hour, min, sec);
			}
		case OFTReal:				
			return wxString::Format(_("%.6f"), pFeature->GetFieldAsDouble(col));
		default:
			return wgMB2WX(pFeature->GetFieldAsString(col));
		}
		//return wgMB2WX(GetAt(row)->GetFieldAsString(col));
	}
}
示例#21
0
void OGRBNALayer::WriteFeatureAttributes(VSILFILE* fp, OGRFeature *poFeature )
{
    int i;
    OGRFieldDefn *poFieldDefn;
    int nbOutID = poDS->GetNbOutId();
    if (nbOutID < 0)
        nbOutID = poFeatureDefn->GetFieldCount();
    for(i=0;i<nbOutID;i++)
    { 
        if (i < poFeatureDefn->GetFieldCount())
        {
            poFieldDefn = poFeatureDefn->GetFieldDefn( i );
            if( poFeature->IsFieldSet( i ) )
            {
                if (poFieldDefn->GetType() == OFTReal)
                {
                    char szBuffer[64];
                    OGRFormatDouble(szBuffer, sizeof(szBuffer),
                                    poFeature->GetFieldAsDouble(i), '.');
                    VSIFPrintfL( fp, "\"%s\",", szBuffer);
                }
                else
                {
                    const char *pszRaw = poFeature->GetFieldAsString( i );
                    VSIFPrintfL( fp, "\"%s\",", pszRaw);
                }
            }
            else
            {
                VSIFPrintfL( fp, "\"\",");
            }
        }
        else
        {
            VSIFPrintfL( fp, "\"\",");
        }
    }
}
OGRErr OGRGeoJSONWriteLayer::CreateField(OGRFieldDefn* poField, int bApproxOK)
{
    UNREFERENCED_PARAM(bApproxOK);

    for( int i = 0; i < poFeatureDefn_->GetFieldCount(); ++i )
    {
        OGRFieldDefn* poDefn = poFeatureDefn_->GetFieldDefn(i);
        CPLAssert( NULL != poDefn );

        if( EQUAL( poDefn->GetNameRef(), poField->GetNameRef() ) )
        {
            CPLDebug( "GeoJSON", "Field '%s' already present in schema",
                      poField->GetNameRef() );
            
            // TODO - mloskot: Is this return code correct?
            return OGRERR_NONE;
        }
    }

    poFeatureDefn_->AddFieldDefn( poField );

    return OGRERR_NONE;
}
示例#23
0
void OGRFeature::DumpReadable( FILE * fpOut )

{
    fprintf( fpOut, "OGRFeature(%s):%ld\n", poDefn->GetName(), GetFID() );
    for( int iField = 0; iField < GetFieldCount(); iField++ )
    {
        OGRFieldDefn    *poFDefn = poDefn->GetFieldDefn(iField);
        
        fprintf( fpOut, "  %s (%s) = ",
                 poFDefn->GetNameRef(),
                 OGRFieldDefn::GetFieldTypeName(poFDefn->GetType()) );

        if( IsFieldSet( iField ) )
            fprintf( fpOut, "%s\n", GetFieldAsString( iField ) );
        else
            fprintf( fpOut, "(null)\n" );
            
    }
    
    if( poGeometry != NULL )
        poGeometry->dumpReadable( fpOut, "  " );

    fprintf( fpOut, "\n" );
}
示例#24
0
GByte *OGRMIAttrIndex::BuildKey( OGRField *psKey )

{
    switch( poFldDefn->GetType() )
    {
      case OFTInteger:
        return poINDFile->BuildKey( iIndex, psKey->Integer );
        break;

      case OFTReal:
        return poINDFile->BuildKey( iIndex, psKey->Real );
        break;

      case OFTString:
        return poINDFile->BuildKey( iIndex, psKey->String );
        break;

      default:
        CPLAssert( FALSE );

        return NULL;
    }
}
示例#25
0
static void ReportOnLayer( OGRLayer * poLayer )

{
    OGRFeatureDefn      *poDefn = poLayer->GetLayerDefn();

    printf( "\n" );
    
    printf( "Layer name: %s\n", poDefn->GetName() );

    printf( "Feature Count: %d\n", poLayer->GetFeatureCount() );

    if( bVerbose )
    {
        char    *pszWKT;
        
        if( poLayer->GetSpatialRef() == NULL )
            pszWKT = CPLStrdup( "(NULL)" );
        else
            poLayer->GetSpatialRef()->exportToWkt( &pszWKT );

        printf( "Layer SRS WKT: %s\n", pszWKT );
        CPLFree( pszWKT );
    }
    
    for( int iAttr = 0; iAttr < poDefn->GetFieldCount(); iAttr++ )
    {
        OGRFieldDefn    *poField = poDefn->GetFieldDefn( iAttr );

        printf( "%s: %s (%d.%d)\n",
                poField->GetNameRef(),
                poField->GetFieldTypeName( poField->GetType() ),
                poField->GetWidth(),
                poField->GetPrecision() );
    }

/* -------------------------------------------------------------------- */
/*      Read, and dump features.                                        */
/* -------------------------------------------------------------------- */
    OGRFeature  *poFeature;
    while( (poFeature = poLayer->GetNextFeature()) != NULL )
    {
        poFeature->DumpReadable( stdout );
        delete poFeature;
    }
}
feature_ptr ogr_index_featureset<filterT>::next()
{
    if (itr_ != ids_.end())
    {
        int pos = *itr_++;
        layer_.SetNextByIndex (pos);

        ogr_feature_ptr feat (layer_.GetNextFeature());
        if ((*feat) != NULL)
        {
            // ogr feature ids start at 0, so add one to stay
            // consistent with other mapnik datasources that start at 1
            int feature_id = ((*feat)->GetFID() + 1);
            feature_ptr feature(feature_factory::create(feature_id));
            
            OGRGeometry* geom=(*feat)->GetGeometryRef();
            if (geom && !geom->IsEmpty())
            {
                ogr_converter::convert_geometry (geom, feature, multiple_geometries_);
            }
    #ifdef MAPNIK_DEBUG
            else
            {
                std::clog << "### Warning: feature with null geometry: " << (*feat)->GetFID() << "\n";
            }
    #endif
            
            int fld_count = layerdef_->GetFieldCount();
            for (int i = 0; i < fld_count; i++)
            {
                OGRFieldDefn* fld = layerdef_->GetFieldDefn (i);
                OGRFieldType type_oid = fld->GetType ();
                std::string fld_name = fld->GetNameRef ();
            
                switch (type_oid)
                {
                    case OFTInteger:
                    {
                       boost::put(*feature,fld_name,(*feat)->GetFieldAsInteger (i));
                       break;
                    }
                    
                    case OFTReal:
                    {
                       boost::put(*feature,fld_name,(*feat)->GetFieldAsDouble (i));
                       break;
                    }
                           
                    case OFTString:
                    case OFTWideString:     // deprecated !
                    {
                       UnicodeString ustr = tr_->transcode((*feat)->GetFieldAsString (i));
                       boost::put(*feature,fld_name,ustr);
                       break;
                    }
                    
                    case OFTIntegerList:
                    case OFTRealList:
                    case OFTStringList:
                    case OFTWideStringList: // deprecated !
                    {
                    #ifdef MAPNIK_DEBUG
                       std::clog << "OGR Plugin: unhandled type_oid=" << type_oid << std::endl;
                    #endif
                       break;
                    }
                    
                    case OFTBinary:
                    {
                    #ifdef MAPNIK_DEBUG
                       std::clog << "OGR Plugin: unhandled type_oid=" << type_oid << std::endl;
                    #endif
                       //boost::put(*feature,name,feat->GetFieldAsBinary (i, size));
                       break;
                    }
                       
                    case OFTDate:
                    case OFTTime:
                    case OFTDateTime:       // unhandled !
                    {
                    #ifdef MAPNIK_DEBUG
                       std::clog << "OGR Plugin: unhandled type_oid=" << type_oid << std::endl;
                    #endif
                       break;
                    }
                    
                    default: // unknown
                    {
                    #ifdef MAPNIK_DEBUG
                       std::clog << "OGR Plugin: unknown type_oid=" << type_oid << std::endl;
                    #endif
                       break;
                    }
                }
            }
            return feature;
        }
    }
    
    return feature_ptr();
}
示例#27
0
void GTMTrackLayer::WriteFeatureAttributes( OGRFeature *poFeature )
{
    char* psztrackname = nullptr;
    int type = 1;
    unsigned int color = 0;
    for (int i = 0; i < poFeatureDefn->GetFieldCount(); ++i)
    {
        OGRFieldDefn *poFieldDefn = poFeatureDefn->GetFieldDefn( i );
        if( poFeature->IsFieldSetAndNotNull( i ) )
        {
            const char* l_pszName = poFieldDefn->GetNameRef();
            /* track name */
            if (STARTS_WITH(l_pszName, "name"))
            {
                CPLFree(psztrackname);
                psztrackname = CPLStrdup( poFeature->GetFieldAsString( i ) );
            }
            /* track type */
            else if (STARTS_WITH(l_pszName, "type"))
            {
                type = poFeature->GetFieldAsInteger( i );
                // Check if it is a valid type
                if (type < 1 || type > 30)
                    type = 1;
            }
            /* track color */
            else if (STARTS_WITH(l_pszName, "color"))
            {
                color = (unsigned int) poFeature->GetFieldAsInteger( i );
                if (color > 0xFFFFFF)
                    color = 0xFFFFFFF;
            }
        }
    }

    if (psztrackname == nullptr)
        psztrackname = CPLStrdup( "" );

    const size_t trackNameLength = strlen(psztrackname);

    const size_t bufferSize = 14 + trackNameLength;
    void* pBuffer = CPLMalloc(bufferSize);
    void* pBufferAux = pBuffer;
    /* Write track string name size to buffer */
    appendUShort(pBufferAux, (unsigned short) trackNameLength);
    pBufferAux = (char*)pBufferAux + 2;

    /* Write track name */
    memcpy((char*)pBufferAux, psztrackname, trackNameLength);
    pBufferAux = (char*)pBufferAux + trackNameLength;

    /* Write track type */
    appendUChar(pBufferAux, (unsigned char) type);
    pBufferAux = (char*)pBufferAux + 1;

    /* Write track color */
    appendInt(pBufferAux, color);
    pBufferAux = (char*)pBufferAux + 4;

    /* Write track scale */
    appendFloat(pBufferAux, 0);
    pBufferAux = (char*)pBufferAux + 4;

    /* Write track label */
    appendUChar(pBufferAux, 0);
    pBufferAux = (char*)pBufferAux + 1;

    /* Write track layer */
    appendUShort(pBufferAux, 0);

    VSIFWriteL(pBuffer, bufferSize, 1, poDS->getTmpTracksFP());
    poDS->incNumTracks();

    CPLFree(psztrackname);
    CPLFree(pBuffer);
}
示例#28
0
OGRErr OGRMemLayer::AlterFieldDefn( int iField, OGRFieldDefn* poNewFieldDefn, int nFlags )
{
    if (!bUpdatable)
        return OGRERR_FAILURE;

    if (iField < 0 || iField >= poFeatureDefn->GetFieldCount())
    {
        CPLError( CE_Failure, CPLE_NotSupported,
                  "Invalid field index");
        return OGRERR_FAILURE;
    }

    OGRFieldDefn* poFieldDefn = poFeatureDefn->GetFieldDefn(iField);

    if ((nFlags & ALTER_TYPE_FLAG) &&
        poFieldDefn->GetType() != poNewFieldDefn->GetType())
    {
        if ((poNewFieldDefn->GetType() == OFTDate ||
             poNewFieldDefn->GetType() == OFTTime ||
             poNewFieldDefn->GetType() == OFTDateTime) &&
            (poFieldDefn->GetType() == OFTDate ||
             poFieldDefn->GetType() == OFTTime ||
             poFieldDefn->GetType() == OFTDateTime))
        {
            /* do nothing on features */
        }
        else if (poNewFieldDefn->GetType() == OFTInteger64 &&
                 poFieldDefn->GetType() == OFTInteger)
        {
    /* -------------------------------------------------------------------- */
    /*      Update all the internal features.  Hopefully there aren't any   */
    /*      external features referring to our OGRFeatureDefn!              */
    /* -------------------------------------------------------------------- */
            for( GIntBig i = 0; i < nMaxFeatureCount; i++ )
            {
                if( papoFeatures[i] == NULL )
                    continue;

                OGRField* poFieldRaw = papoFeatures[i]->GetRawFieldRef(iField);
                if( papoFeatures[i]->IsFieldSet(iField) )
                {
                    poFieldRaw->Integer64 = poFieldRaw->Integer;
                }
            }
        }
        else if (poNewFieldDefn->GetType() == OFTReal &&
                 poFieldDefn->GetType() == OFTInteger)
        {
    /* -------------------------------------------------------------------- */
    /*      Update all the internal features.  Hopefully there aren't any   */
    /*      external features referring to our OGRFeatureDefn!              */
    /* -------------------------------------------------------------------- */
            for( GIntBig i = 0; i < nMaxFeatureCount; i++ )
            {
                if( papoFeatures[i] == NULL )
                    continue;

                OGRField* poFieldRaw = papoFeatures[i]->GetRawFieldRef(iField);
                if( papoFeatures[i]->IsFieldSet(iField) )
                {
                    poFieldRaw->Real = poFieldRaw->Integer;
                }
            }
        }
        else if (poNewFieldDefn->GetType() == OFTReal &&
                 poFieldDefn->GetType() == OFTInteger64)
        {
    /* -------------------------------------------------------------------- */
    /*      Update all the internal features.  Hopefully there aren't any   */
    /*      external features referring to our OGRFeatureDefn!              */
    /* -------------------------------------------------------------------- */
            for( GIntBig i = 0; i < nMaxFeatureCount; i++ )
            {
                if( papoFeatures[i] == NULL )
                    continue;

                OGRField* poFieldRaw = papoFeatures[i]->GetRawFieldRef(iField);
                if( papoFeatures[i]->IsFieldSet(iField) )
                {
                    poFieldRaw->Real = (double) poFieldRaw->Integer64;
                }
            }
        }
        else
        {
            if (poNewFieldDefn->GetType() != OFTString)
            {
                CPLError( CE_Failure, CPLE_NotSupported,
                        "Can only convert from OFTInteger to OFTReal, or from anything to OFTString");
                return OGRERR_FAILURE;
            }

    /* -------------------------------------------------------------------- */
    /*      Update all the internal features.  Hopefully there aren't any   */
    /*      external features referring to our OGRFeatureDefn!              */
    /* -------------------------------------------------------------------- */
            for( GIntBig i = 0; i < nMaxFeatureCount; i++ )
            {
                if( papoFeatures[i] == NULL )
                    continue;

                OGRField* poFieldRaw = papoFeatures[i]->GetRawFieldRef(iField);
                if( papoFeatures[i]->IsFieldSet(iField) )
                {
                    char* pszVal = CPLStrdup(papoFeatures[i]->GetFieldAsString(iField));

                    /* Little trick to unallocate the field */
                    OGRField sField;
                    sField.Set.nMarker1 = OGRUnsetMarker;
                    sField.Set.nMarker2 = OGRUnsetMarker;
                    papoFeatures[i]->SetField(iField, &sField);

                    poFieldRaw->String = pszVal;
                }
            }
        }

        poFieldDefn->SetType(poNewFieldDefn->GetType());
    }

    if (nFlags & ALTER_NAME_FLAG)
        poFieldDefn->SetName(poNewFieldDefn->GetNameRef());
    if (nFlags & ALTER_WIDTH_PRECISION_FLAG)
    {
        poFieldDefn->SetWidth(poNewFieldDefn->GetWidth());
        poFieldDefn->SetPrecision(poNewFieldDefn->GetPrecision());
    }

    return OGRERR_NONE;
}
示例#29
0
void GTMWaypointLayer::WriteFeatureAttributes( OGRFeature *poFeature, float altitude )
{
    char psNameField[] = "          "; // 10 spaces
    char* pszcomment = nullptr;
    int icon = 48;
    int date = 0;
    for (int i = 0; i < poFeatureDefn->GetFieldCount(); ++i)
    {
        OGRFieldDefn *poFieldDefn = poFeatureDefn->GetFieldDefn( i );
        if( poFeature->IsFieldSetAndNotNull( i ) )
        {
            const char* l_pszName = poFieldDefn->GetNameRef();
            /* Waypoint name */
            if (STARTS_WITH(l_pszName, "name"))
            {
                strncpy (psNameField, poFeature->GetFieldAsString( i ), 10);
                CPLStrlcat (psNameField, "          ", sizeof(psNameField));
            }
            /* Waypoint comment */
            else if (STARTS_WITH(l_pszName, "comment"))
            {
                CPLFree(pszcomment);
                pszcomment = CPLStrdup( poFeature->GetFieldAsString( i ) );
            }
            /* Waypoint icon */
            else if (STARTS_WITH(l_pszName, "icon"))
            {
                icon = poFeature->GetFieldAsInteger( i );
                // Check if it is a valid icon
                if (icon < 1 || icon > 220)
                    icon = 48;
            }
            /* Waypoint date */
            else if (EQUAL(l_pszName, "time"))
            {
                struct tm brokendowndate;
                int year, month, day, hour, min, sec, TZFlag;
                if (poFeature->GetFieldAsDateTime( i, &year, &month, &day, &hour, &min, &sec, &TZFlag))
                {
                    brokendowndate.tm_year = year - 1900;
                    brokendowndate.tm_mon = month - 1;
                    brokendowndate.tm_mday = day;
                    brokendowndate.tm_hour = hour;
                    brokendowndate.tm_min = min;
                    brokendowndate.tm_sec = sec;
                    GIntBig unixTime = CPLYMDHMSToUnixTime(&brokendowndate);
                    if (TZFlag != 0)
                        unixTime -= (TZFlag - 100) * 15;
                    if (unixTime <= GTM_EPOCH || (unixTime - GTM_EPOCH) != (int)(unixTime - GTM_EPOCH))
                    {
                        CPLError(CE_Warning, CPLE_AppDefined,
                                  "%04d/%02d/%02d %02d:%02d:%02d is not a valid datetime for GTM",
                                  year, month, day, hour, min, sec);
                    }
                    else
                    {
                        date = (int)(unixTime - GTM_EPOCH);
                    }
                }
            }
        }
    }

    if (pszcomment == nullptr)
        pszcomment = CPLStrdup( "" );

    const size_t commentLength = strlen(pszcomment);

    const size_t bufferSize = 27 + commentLength;
    void* pBuffer = CPLMalloc(bufferSize);
    void* pBufferAux = pBuffer;
    /* Write waypoint name to buffer */
    memcpy((char*)pBufferAux, psNameField, 10);

    /* Write waypoint string comment size to buffer */
    pBufferAux = (char*)pBuffer+10;
    appendUShort(pBufferAux, (unsigned short) commentLength);

    /* Write waypoint string comment to buffer */
    memcpy((char*)pBuffer+12, pszcomment, commentLength);

    /* Write icon to buffer */
    pBufferAux = (char*)pBuffer+12+commentLength;
    appendUShort(pBufferAux, (unsigned short) icon);

    /* Write dslp to buffer */
    pBufferAux = (char*)pBufferAux + 2;
    appendUChar(pBufferAux, 3);

    /* Date */
    pBufferAux = (char*)pBufferAux + 1;
    appendInt(pBufferAux, date);

    /* wrot */
    pBufferAux = (char*)pBufferAux + 4;
    appendUShort(pBufferAux, 0);

    /* walt */
    pBufferAux = (char*)pBufferAux + 2;
    appendFloat(pBufferAux, altitude);

    /* wlayer */
    pBufferAux = (char*)pBufferAux + 4;
    appendUShort(pBufferAux, 0);

    VSIFWriteL(pBuffer, bufferSize, 1, poDS->getOutputFP());
    poDS->incNumWaypoints();

    CPLFree(pszcomment);
    CPLFree(pBuffer);
}
示例#30
0
int main( int nArgc, char ** papszArgv )

{
    int   nFirstSourceDataset = -1, bLayersWildcarded = TRUE, iArg;
    const char *pszFormat = "ESRI Shapefile";
    const char *pszTileIndexField = "LOCATION";
    const char *pszOutputName = NULL;
    int write_absolute_path = FALSE;
    int skip_different_projection = FALSE;
    char* current_path = NULL;
    int accept_different_schemas = FALSE;
    int bFirstWarningForNonMatchingAttributes = TRUE;
    
    /* Check strict compilation and runtime library version as we use C++ API */
    if (! GDAL_CHECK_VERSION(papszArgv[0]))
        exit(1);
/* -------------------------------------------------------------------- */
/*      Register format(s).                                             */
/* -------------------------------------------------------------------- */
    OGRRegisterAll();
    
/* -------------------------------------------------------------------- */
/*      Processing command line arguments.                              */
/* -------------------------------------------------------------------- */
    for( iArg = 1; iArg < nArgc; iArg++ )
    {
        if( EQUAL(papszArgv[iArg], "--utility_version") )
        {
            printf("%s was compiled against GDAL %s and is running against GDAL %s\n",
                   papszArgv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME"));
            return 0;
        }
        else if( EQUAL(papszArgv[iArg],"-f") && iArg < nArgc-1 )
        {
            pszFormat = papszArgv[++iArg];
        }
        else if( EQUAL(papszArgv[iArg],"-write_absolute_path"))
        {
            write_absolute_path = TRUE;
        }
        else if( EQUAL(papszArgv[iArg],"-skip_different_projection"))
        {
            skip_different_projection = TRUE;
        }
        else if( EQUAL(papszArgv[iArg],"-accept_different_schemas"))
        {
            accept_different_schemas = TRUE;
        }
        else if( EQUAL(papszArgv[iArg],"-tileindex") && iArg < nArgc-1 )
        {
            pszTileIndexField = papszArgv[++iArg];
        }
        else if( EQUAL(papszArgv[iArg],"-lnum") 
                 || EQUAL(papszArgv[iArg],"-lname") )
        {
            iArg++;
            bLayersWildcarded = FALSE;
        }
        else if( papszArgv[iArg][0] == '-' )
            Usage();
        else if( pszOutputName == NULL )
            pszOutputName = papszArgv[iArg];
        else if( nFirstSourceDataset == -1 )
            nFirstSourceDataset = iArg;
    }

    if( pszOutputName == NULL || nFirstSourceDataset == -1 )
        Usage();

/* -------------------------------------------------------------------- */
/*      Try to open as an existing dataset for update access.           */
/* -------------------------------------------------------------------- */
    OGRDataSource *poDstDS;
    OGRLayer *poDstLayer = NULL;

    poDstDS = OGRSFDriverRegistrar::Open( pszOutputName, TRUE );

/* -------------------------------------------------------------------- */
/*      If that failed, find the driver so we can create the tile index.*/
/* -------------------------------------------------------------------- */
    if( poDstDS == NULL )
    {
        OGRSFDriverRegistrar     *poR = OGRSFDriverRegistrar::GetRegistrar();
        OGRSFDriver              *poDriver = NULL;
        int                      iDriver;

        for( iDriver = 0;
             iDriver < poR->GetDriverCount() && poDriver == NULL;
             iDriver++ )
        {
            if( EQUAL(poR->GetDriver(iDriver)->GetName(),pszFormat) )
            {
                poDriver = poR->GetDriver(iDriver);
            }
        }

        if( poDriver == NULL )
        {
            fprintf( stderr, "Unable to find driver `%s'.\n", pszFormat );
            fprintf( stderr, "The following drivers are available:\n" );
        
            for( iDriver = 0; iDriver < poR->GetDriverCount(); iDriver++ )
            {
                fprintf( stderr, "  -> `%s'\n", poR->GetDriver(iDriver)->GetName() );
            }
            exit( 1 );
        }

        if( !poDriver->TestCapability( ODrCCreateDataSource ) )
        {
            fprintf( stderr, "%s driver does not support data source creation.\n",
                    pszFormat );
            exit( 1 );
        }

/* -------------------------------------------------------------------- */
/*      Now create it.                                                  */
/* -------------------------------------------------------------------- */
        
        poDstDS = poDriver->CreateDataSource( pszOutputName, NULL );
        if( poDstDS == NULL )
        {
            fprintf( stderr, "%s driver failed to create %s\n", 
                    pszFormat, pszOutputName );
            exit( 1 );
        }

        if( poDstDS->GetLayerCount() == 0 )
        {
            OGRFieldDefn oLocation( pszTileIndexField, OFTString );
            
            oLocation.SetWidth( 200 );
            
            if( nFirstSourceDataset < nArgc && papszArgv[nFirstSourceDataset][0] == '-' )
            {
                nFirstSourceDataset++;
            }
            
            OGRSpatialReference* poSrcSpatialRef = NULL;
            
            /* Fetches the SRS of the first layer and use it when creating the tileindex layer */
            if (nFirstSourceDataset < nArgc)
            {
                OGRDataSource* poDS = OGRSFDriverRegistrar::Open( papszArgv[nFirstSourceDataset], 
                                           FALSE );
                                           
                if (poDS)
                {
                    int iLayer;

                    for( iLayer = 0; iLayer < poDS->GetLayerCount(); iLayer++ )
                    {
                        int bRequested = bLayersWildcarded;
                        OGRLayer *poLayer = poDS->GetLayer(iLayer);

                        for( iArg = 1; iArg < nArgc && !bRequested; iArg++ )
                        {
                            if( EQUAL(papszArgv[iArg],"-lnum") 
                                && atoi(papszArgv[iArg+1]) == iLayer )
                                bRequested = TRUE;
                            else if( EQUAL(papszArgv[iArg],"-lname") 
                                     && EQUAL(papszArgv[iArg+1],
                                              poLayer->GetLayerDefn()->GetName()) )
                                bRequested = TRUE;
                        }

                        if( !bRequested )
                            continue;
                            
                        if ( poLayer->GetSpatialRef() )
                            poSrcSpatialRef = poLayer->GetSpatialRef()->Clone();
                        break;
                    }
                }
                
                OGRDataSource::DestroyDataSource( poDS );
            }

            poDstLayer = poDstDS->CreateLayer( "tileindex", poSrcSpatialRef );
            poDstLayer->CreateField( &oLocation, OFTString );
            
            OGRSpatialReference::DestroySpatialReference( poSrcSpatialRef );
        }
    }

/* -------------------------------------------------------------------- */
/*      Identify target layer and field.                                */
/* -------------------------------------------------------------------- */
    int   iTileIndexField;

    poDstLayer = poDstDS->GetLayer(0);
    if( poDstLayer == NULL )
    {
        fprintf( stderr, "Can't find any layer in output tileindex!\n" );
        exit( 1 );
    }

    iTileIndexField = 
        poDstLayer->GetLayerDefn()->GetFieldIndex( pszTileIndexField );
    if( iTileIndexField == -1 )
    {
        fprintf( stderr, "Can't find %s field in tile index dataset.\n", 
                pszTileIndexField );
        exit( 1 );
    }

    OGRFeatureDefn* poFeatureDefn = NULL;

    /* Load in memory existing file names in SHP */
    int nExistingLayers = 0;
    char** existingLayersTab = NULL;
    OGRSpatialReference* alreadyExistingSpatialRef = NULL;
    int alreadyExistingSpatialRefValid = FALSE;
    nExistingLayers = poDstLayer->GetFeatureCount();
    if (nExistingLayers)
    {
        int i;
        existingLayersTab = (char**)CPLMalloc(nExistingLayers * sizeof(char*));
        for(i=0;i<nExistingLayers;i++)
        {
            OGRFeature* feature = poDstLayer->GetNextFeature();
            existingLayersTab[i] = CPLStrdup(feature->GetFieldAsString( iTileIndexField));
            if (i == 0)
            {
                OGRDataSource       *poDS;
                char* filename = CPLStrdup(existingLayersTab[i]);
                int j;
                for(j=strlen(filename)-1;j>=0;j--)
                {
                    if (filename[j] == ',')
                        break;
                }
                if (j >= 0)
                {
                    int iLayer = atoi(filename + j + 1);
                    filename[j] = 0;
                    poDS = OGRSFDriverRegistrar::Open(filename, 
                                                    FALSE );
                    if (poDS)
                    {
                        OGRLayer *poLayer = poDS->GetLayer(iLayer);
                        if (poLayer)
                        {
                            alreadyExistingSpatialRefValid = TRUE;
                            alreadyExistingSpatialRef =
                                    (poLayer->GetSpatialRef()) ? poLayer->GetSpatialRef()->Clone() : NULL;
                                    
                            if (poFeatureDefn == NULL)
                                poFeatureDefn = poLayer->GetLayerDefn()->Clone();
                        }
                        OGRDataSource::DestroyDataSource( poDS );
                    }
                }
            }
        }
    }


    if (write_absolute_path)
    {
        current_path = CPLGetCurrentDir();
        if (current_path == NULL)
        {
            fprintf( stderr, "This system does not support the CPLGetCurrentDir call. "
                             "The option -write_absolute_path will have no effect\n");
            write_absolute_path = FALSE;
        }
    }
/* ==================================================================== */
/*      Process each input datasource in turn.                          */
/* ==================================================================== */

	for(; nFirstSourceDataset < nArgc; nFirstSourceDataset++ )
    {
        int i;
        OGRDataSource       *poDS;

        if( papszArgv[nFirstSourceDataset][0] == '-' )
        {
            nFirstSourceDataset++;
            continue;
        }
        
        char* fileNameToWrite;
        VSIStatBuf sStatBuf;

        if (write_absolute_path && CPLIsFilenameRelative( papszArgv[nFirstSourceDataset] ) &&
            VSIStat( papszArgv[nFirstSourceDataset], &sStatBuf ) == 0)
        {
            fileNameToWrite = CPLStrdup(CPLProjectRelativeFilename(current_path,papszArgv[nFirstSourceDataset]));
        }
        else
        {
            fileNameToWrite = CPLStrdup(papszArgv[nFirstSourceDataset]);
        }

        poDS = OGRSFDriverRegistrar::Open( papszArgv[nFirstSourceDataset], 
                                           FALSE );

        if( poDS == NULL )
        {
            fprintf( stderr, "Failed to open dataset %s, skipping.\n", 
                    papszArgv[nFirstSourceDataset] );
            CPLFree(fileNameToWrite);
            continue;
        }

/* -------------------------------------------------------------------- */
/*      Check all layers, and see if they match requests.               */
/* -------------------------------------------------------------------- */
        int iLayer;

        for( iLayer = 0; iLayer < poDS->GetLayerCount(); iLayer++ )
        {
            int bRequested = bLayersWildcarded;
            OGRLayer *poLayer = poDS->GetLayer(iLayer);

            for( iArg = 1; iArg < nArgc && !bRequested; iArg++ )
            {
                if( EQUAL(papszArgv[iArg],"-lnum") 
                    && atoi(papszArgv[iArg+1]) == iLayer )
                    bRequested = TRUE;
                else if( EQUAL(papszArgv[iArg],"-lname") 
                         && EQUAL(papszArgv[iArg+1],
                                  poLayer->GetLayerDefn()->GetName()) )
                    bRequested = TRUE;
            }

            if( !bRequested )
                continue;

            /* Checks that the layer is not already in tileindex */
            for(i=0;i<nExistingLayers;i++)
            {
                char        szLocation[5000];
                sprintf( szLocation, "%s,%d", 
                        fileNameToWrite, iLayer );
                if (EQUAL(szLocation, existingLayersTab[i]))
                {
                    fprintf(stderr, "Layer %d of %s is already in tileindex. Skipping it.\n",
                            iLayer, papszArgv[nFirstSourceDataset]);
                    break;
                }
            }
            if (i != nExistingLayers)
            {
                continue;
            }

            OGRSpatialReference* spatialRef = poLayer->GetSpatialRef();
            if (alreadyExistingSpatialRefValid)
            {
                if ((spatialRef != NULL && alreadyExistingSpatialRef != NULL &&
                     spatialRef->IsSame(alreadyExistingSpatialRef) == FALSE) ||
                    ((spatialRef != NULL) != (alreadyExistingSpatialRef != NULL)))
                {
                    fprintf(stderr, "Warning : layer %d of %s is not using the same projection system as "
                                "other files in the tileindex. This may cause problems when "
                                "using it in MapServer for example.%s\n", iLayer, papszArgv[nFirstSourceDataset],
                                (skip_different_projection) ? " Skipping it" : "");
                    if (skip_different_projection)
                    {
                        continue;
                    }
                }
            }
            else
            {
                alreadyExistingSpatialRefValid = TRUE;
                alreadyExistingSpatialRef = (spatialRef) ? spatialRef->Clone() : NULL;
            }

/* -------------------------------------------------------------------- */
/*		Check if all layers in dataset have the same attributes	schema. */
/* -------------------------------------------------------------------- */
			if( poFeatureDefn == NULL )
			{
				poFeatureDefn = poLayer->GetLayerDefn()->Clone();
			}
			else if ( !accept_different_schemas )
			{
				OGRFeatureDefn* poFeatureDefnCur = poLayer->GetLayerDefn();
				assert(NULL != poFeatureDefnCur);

				int fieldCount = poFeatureDefnCur->GetFieldCount();

				if( fieldCount != poFeatureDefn->GetFieldCount())
				{
					fprintf( stderr, "Number of attributes of layer %s of %s does not match ... skipping it.\n",
                             poLayer->GetLayerDefn()->GetName(), papszArgv[nFirstSourceDataset]);
                    if (bFirstWarningForNonMatchingAttributes)
                    {
                        fprintf( stderr, "Note : you can override this behaviour with -accept_different_schemas option\n"
                                         "but this may result in a tileindex incompatible with MapServer\n");
                        bFirstWarningForNonMatchingAttributes = FALSE;
                    }
					continue;
				}
				
                int bSkip = FALSE;
				for( int fn = 0; fn < poFeatureDefnCur->GetFieldCount(); fn++ )
				{
 					OGRFieldDefn* poField = poFeatureDefn->GetFieldDefn(fn);
 					OGRFieldDefn* poFieldCur = poFeatureDefnCur->GetFieldDefn(fn);

					/* XXX - Should those pointers be checked against NULL? */ 
					assert(NULL != poField);
					assert(NULL != poFieldCur);

					if( poField->GetType() != poFieldCur->GetType() 
						|| poField->GetWidth() != poFieldCur->GetWidth() 
						|| poField->GetPrecision() != poFieldCur->GetPrecision() 
						|| !EQUAL( poField->GetNameRef(), poFieldCur->GetNameRef() ) )
					{
						fprintf( stderr, "Schema of attributes of layer %s of %s does not match ... skipping it.\n",
                                 poLayer->GetLayerDefn()->GetName(), papszArgv[nFirstSourceDataset]);
                        if (bFirstWarningForNonMatchingAttributes)
                        {
                            fprintf( stderr, "Note : you can override this behaviour with -accept_different_schemas option\n"
                                             "but this may result in a tileindex incompatible with MapServer\n");
                            bFirstWarningForNonMatchingAttributes = FALSE;
                        }
                        bSkip = TRUE; 
                        break;
					}
				}
                
                if (bSkip)
                    continue;
			}


/* -------------------------------------------------------------------- */
/*      Get layer extents, and create a corresponding polygon           */
/*      geometry.                                                       */
/* -------------------------------------------------------------------- */
            OGREnvelope sExtents;
            OGRPolygon oRegion;
            OGRLinearRing oRing;

            if( poLayer->GetExtent( &sExtents, TRUE ) != OGRERR_NONE )
            {
                fprintf( stderr, "GetExtent() failed on layer %s of %s, skipping.\n", 
                        poLayer->GetLayerDefn()->GetName(), 
                        papszArgv[nFirstSourceDataset] );
                continue;
            }
            
            oRing.addPoint( sExtents.MinX, sExtents.MinY );
            oRing.addPoint( sExtents.MinX, sExtents.MaxY );
            oRing.addPoint( sExtents.MaxX, sExtents.MaxY );
            oRing.addPoint( sExtents.MaxX, sExtents.MinY );
            oRing.addPoint( sExtents.MinX, sExtents.MinY );

            oRegion.addRing( &oRing );

/* -------------------------------------------------------------------- */
/*      Add layer to tileindex.                                         */
/* -------------------------------------------------------------------- */
            char        szLocation[5000];
            OGRFeature  oTileFeat( poDstLayer->GetLayerDefn() );

            sprintf( szLocation, "%s,%d", 
                     fileNameToWrite, iLayer );
            oTileFeat.SetGeometry( &oRegion );
            oTileFeat.SetField( iTileIndexField, szLocation );

            if( poDstLayer->CreateFeature( &oTileFeat ) != OGRERR_NONE )
            {
                fprintf( stderr, "Failed to create feature on tile index ... terminating." );
                OGRDataSource::DestroyDataSource( poDstDS );
                exit( 1 );
            }
        }

/* -------------------------------------------------------------------- */
/*      Cleanup this data source.                                       */
/* -------------------------------------------------------------------- */
        CPLFree(fileNameToWrite);
        OGRDataSource::DestroyDataSource( poDS );
    }

/* -------------------------------------------------------------------- */
/*      Close tile index and clear buffers.                             */
/* -------------------------------------------------------------------- */
    OGRDataSource::DestroyDataSource( poDstDS );
	OGRFeatureDefn::DestroyFeatureDefn( poFeatureDefn );
  
    if (alreadyExistingSpatialRef != NULL)
        OGRSpatialReference::DestroySpatialReference( alreadyExistingSpatialRef );
  
    CPLFree(current_path);
    
    if (nExistingLayers)
    {
        int i;
        for(i=0;i<nExistingLayers;i++)
        {
            CPLFree(existingLayersTab[i]);
        }
        CPLFree(existingLayersTab);
    }

    return 0;
}