Example #1
0
int
NIImporter_ArcView::getLaneNo(OGRFeature& poFeature, const std::string& edgeid,
                              SUMOReal speed) {
    if (myOptions.isSet("shapefile.type-id")) {
        return (int) myTypeCont.getNumLanes(poFeature.GetFieldAsString((char*)(myOptions.getString("shapefile.type-id").c_str())));
    }
    // try to get definitions as to be found in SUMO-XML-definitions
    //  idea by John Michael Calandrino
    int index = poFeature.GetDefnRef()->GetFieldIndex("nolanes");
    if (index >= 0 && poFeature.IsFieldSet(index)) {
        return (int) poFeature.GetFieldAsInteger(index);
    }
    index = poFeature.GetDefnRef()->GetFieldIndex("NOLANES");
    if (index >= 0 && poFeature.IsFieldSet(index)) {
        return (int) poFeature.GetFieldAsInteger(index);
    }
    index = poFeature.GetDefnRef()->GetFieldIndex("rnol");
    if (index >= 0 && poFeature.IsFieldSet(index)) {
        return (int) poFeature.GetFieldAsInteger(index);
    }
    index = poFeature.GetDefnRef()->GetFieldIndex("LANE_CAT");
    if (index >= 0 && poFeature.IsFieldSet(index)) {
        std::string def = poFeature.GetFieldAsString(index);
        return NINavTeqHelper::getLaneNumber(edgeid, def, speed);
    }
    return 0;
}
Example #2
0
CPLErr GNMGenericNetwork::LoadGraph()
{
    if(m_bIsGraphLoaded)
        return CE_None;

    if(NULL == m_poGraphLayer)
    {
        CPLError( CE_Failure, CPLE_AppDefined, "Loading of graph data failed");
        return CE_Failure;
    }

    OGRFeature *poFeature;
    m_poGraphLayer->ResetReading();
    GNMGFID nSrcFID, nTgtFID, nConFID;
    double dfCost, dfInvCost;
    while ((poFeature = m_poGraphLayer->GetNextFeature()) != NULL)
    {
        nSrcFID = poFeature->GetFieldAsGNMGFID(GNM_SYSFIELD_SOURCE);
        nTgtFID = poFeature->GetFieldAsGNMGFID(GNM_SYSFIELD_TARGET);
        nConFID = poFeature->GetFieldAsGNMGFID(GNM_SYSFIELD_CONNECTOR);
        dfCost = poFeature->GetFieldAsDouble(GNM_SYSFIELD_COST);
        dfInvCost = poFeature->GetFieldAsDouble(GNM_SYSFIELD_INVCOST);
        GNMDirection eDir = poFeature->GetFieldAsInteger(GNM_SYSFIELD_DIRECTION);

        int nBlockState = poFeature->GetFieldAsInteger(GNM_SYSFIELD_BLOCKED);

        bool bIsBlock = GNM_BLOCK_NONE != nBlockState;

        m_oGraph.AddEdge(nConFID, nSrcFID, nTgtFID, eDir == GNM_EDGE_DIR_BOTH,
                         dfCost, dfInvCost);

        if(bIsBlock)
        {
            if(nBlockState & GNM_BLOCK_SRC)
                m_oGraph.ChangeBlockState(nSrcFID, bIsBlock);
            if(nBlockState & GNM_BLOCK_TGT)
                m_oGraph.ChangeBlockState(nTgtFID, bIsBlock);
            if(nBlockState & GNM_BLOCK_CONN)
                m_oGraph.ChangeBlockState(nConFID, bIsBlock);
        }

        if(nConFID < m_nVirtualConnectionGID)
            m_nVirtualConnectionGID = nConFID;

        OGRFeature::DestroyFeature(poFeature);
    }

    m_bIsGraphLoaded = true;
    return CE_None;
}
static swq_expr_node* OGRFeatureFetcher(swq_expr_node *op, void *pFeatureIn)

{
    OGRFeature    *poFeature = (OGRFeature*) pFeatureIn;
    swq_expr_node *poRetNode = NULL;

    switch (op->field_type)
    {
    case SWQ_INTEGER:
    case SWQ_BOOLEAN:
        poRetNode = new swq_expr_node(
            poFeature->GetFieldAsInteger(op->field_index));
        break;

    case SWQ_FLOAT:
        poRetNode = new swq_expr_node(
            poFeature->GetFieldAsDouble(op->field_index));
        break;

    default:
        poRetNode = new swq_expr_node(
            poFeature->GetFieldAsString(op->field_index));
        break;
    }

    poRetNode->is_null = !(poFeature->IsFieldSet(op->field_index));

    return poRetNode;
}
Example #4
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 );
}
static
void OGR2SQLITE_ogr_geocode_set_result(sqlite3_context* pContext,
                                       OGRLayerH hLayer,
                                       const char* pszField)
{
    if( hLayer == NULL )
        sqlite3_result_null (pContext);
    else
    {
        OGRLayer* poLayer = (OGRLayer*)hLayer;
        OGRFeatureDefn* poFDefn = poLayer->GetLayerDefn();
        OGRFeature* poFeature = poLayer->GetNextFeature();
        int nIdx = -1;
        if( poFeature == NULL )
            sqlite3_result_null (pContext);
        else if( strcmp(pszField, "geometry") == 0 &&
                 poFeature->GetGeometryRef() != NULL )
        {
            GByte* pabyGeomBLOB = NULL;
            int nGeomBLOBLen = 0;
            if( OGRSQLiteLayer::ExportSpatiaLiteGeometry(
                        poFeature->GetGeometryRef(), 4326, wkbNDR, FALSE, FALSE, FALSE,
                        &pabyGeomBLOB,
                        &nGeomBLOBLen ) != CE_None )
            {
                sqlite3_result_null (pContext);
            }
            else
            {
                sqlite3_result_blob (pContext, pabyGeomBLOB, nGeomBLOBLen, CPLFree);
            }
        }
        else if( (nIdx = poFDefn->GetFieldIndex(pszField)) >= 0 &&
                 poFeature->IsFieldSet(nIdx) )
        {
            OGRFieldType eType = poFDefn->GetFieldDefn(nIdx)->GetType();
            if( eType == OFTInteger )
                sqlite3_result_int(pContext,
                                   poFeature->GetFieldAsInteger(nIdx));
            else if( eType == OFTInteger64 )
                sqlite3_result_int64(pContext,
                                     poFeature->GetFieldAsInteger64(nIdx));
            else if( eType == OFTReal )
                sqlite3_result_double(pContext,
                                      poFeature->GetFieldAsDouble(nIdx));
            else
                sqlite3_result_text(pContext,
                                    poFeature->GetFieldAsString(nIdx),
                                    -1, SQLITE_TRANSIENT);
        }
        else
            sqlite3_result_null (pContext);
        delete poFeature;
        OGRGeocodeFreeResult(hLayer);
    }
}
Example #6
0
int
NIImporter_ArcView::getPriority(OGRFeature& poFeature, const std::string& /*edgeid*/) {
    if (myOptions.isSet("shapefile.type-id")) {
        return myTypeCont.getPriority(poFeature.GetFieldAsString((char*)(myOptions.getString("shapefile.type-id").c_str())));
    }
    // try to get definitions as to be found in SUMO-XML-definitions
    //  idea by John Michael Calandrino
    int index = poFeature.GetDefnRef()->GetFieldIndex("priority");
    if (index >= 0 && poFeature.IsFieldSet(index)) {
        return poFeature.GetFieldAsInteger(index);
    }
    index = poFeature.GetDefnRef()->GetFieldIndex("PRIORITY");
    if (index >= 0 && poFeature.IsFieldSet(index)) {
        return poFeature.GetFieldAsInteger(index);
    }
    // try to determine priority from NavTechs FUNC_CLASS attribute
    index = poFeature.GetDefnRef()->GetFieldIndex("FUNC_CLASS");
    if (index >= 0 && poFeature.IsFieldSet(index)) {
        return poFeature.GetFieldAsInteger(index);
    }
    return 0;
}
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 );
}
void GDALMergeFaces::run()
{
	OGRGeometry * geo;
	leadingView.resetReading();

	OGRFeature * f;
	std::set<int> indizes;
	while (f = leadingView.getNextFeature()) {
		indizes.insert(f->GetFieldAsInteger(this->attriubteName.c_str()));
	}

	//int cluster_id = 1;
	int counter = 1;


	foreach (int cluster_id, indizes) {
	//while(geo = joinCluster(cluster_id)) {
		//cluster_id++;
		geo = joinCluster(cluster_id);

		if (counter % 100 == 0) {
		DM::Logger(DM::Standard) << "merged " << counter << "/" << indizes.size();
		}
		counter++;
		if (!geo)
			continue;



		if (wkbMultiPolygon == geo->getGeometryType()){
			geo = geo->UnionCascaded();
			OGRMultiPolygon * mgeo = (OGRMultiPolygon*) geo;
			if (mgeo->getNumGeometries() == 0) {
				continue;
			}
			geo = mgeo->getGeometryRef(0);

			int n = mgeo->getNumGeometries();
			for (int i = 0; i < n; i++) {
				OGRFeature * f = combinedView.createFeature();

				f->SetGeometry(mgeo->getGeometryRef(i));
				f->SetField("test_id", counter);
			}
			continue;
		}
		OGRFeature * f = combinedView.createFeature();
		f->SetGeometry(geo);
	}
void MSN_Helper::LoadSamples(Config &config, Matrix &mat)
{
	if(config.bShapefile)
	{
		OGRRegisterAll();
		string pLayerName = StringGetFileName(config.sSamples);
		OGRDataSource* poDS = OGRSFDriverRegistrar::Open(config.sSamples.c_str(),FALSE);
		OGRLayer* poLayer = poDS->GetLayerByName(pLayerName.c_str());
	
		config.nSamples = poLayer->GetFeatureCount();
		mat.Resize(config.nSamples, 4);

		OGRPoint *poPoint;
		OGRFeature * pFeature =poLayer->GetNextFeature();
		for(unsigned long i=1; i<=config.nSamples; i++)
		{
			//样本取值字段名为value,double型
			poPoint = (OGRPoint *)pFeature->GetGeometryRef();
			mat[i][1] = poPoint->getX();
			mat[i][2] = poPoint->getY();
			mat[i][3] = pFeature->GetFieldAsInteger("stratum");
			mat[i][4] = pFeature->GetFieldAsDouble("value");
			pFeature = poLayer->GetNextFeature();
		}

		OGRDataSource::DestroyDataSource( poDS );
	}
	else
	{
		double x, y, v, stratum;
		string sline;
		ifstream infile(config.sSamples.c_str());
		infile >> config.nSamples;

		mat.Resize(config.nSamples, 4);
		for(unsigned long i=1; i<=config.nSamples; i++)
		{
			infile >> x >> y >> stratum >> v;
			mat[i][1] = x;
			mat[i][2] = y;
			mat[i][3] = stratum;
			mat[i][4] = v;
		}
		infile.close();
	}
}
void WaterDemandModel::initRain()
{
	//time series naming
	this->timeseries.resetReading();
	this->timeseries.setAttributeFilter("type = 'rainfall intensity' or type = 'evapotranspiration'");
	OGRFeature * r;

	while (r = this->timeseries.getNextFeature()) {
		std::vector<double> vec;
		DM::DMFeature::GetDoubleList(r, "data", vec);
		std::string type = r->GetFieldAsString("type");
		int station_id = r->GetFieldAsInteger("station_id");
		if (type == "rainfall intensity")
			rainfalls[station_id] = vec;
		if (type == "evapotranspiration")
			evaotranspirations[station_id] = vec;
		station_ids.insert(station_id);
	}
}
Example #11
0
static swq_expr_node *OGRFeatureFetcher( swq_expr_node *op, void *pFeatureIn )

{
    OGRFeature *poFeature = (OGRFeature *) pFeatureIn;
    swq_expr_node *poRetNode = NULL;

    if( op->field_type == SWQ_GEOMETRY )
    {
        int iField = op->field_index - (poFeature->GetFieldCount() + SPECIAL_FIELD_COUNT);
        poRetNode = new swq_expr_node( poFeature->GetGeomFieldRef(iField) );
        return poRetNode;
    }

    switch( op->field_type )
    {
      case SWQ_INTEGER:
      case SWQ_BOOLEAN:
        poRetNode = new swq_expr_node( 
            poFeature->GetFieldAsInteger(op->field_index) );
        break;

      case SWQ_INTEGER64:
        poRetNode = new swq_expr_node( 
            poFeature->GetFieldAsInteger64(op->field_index) );
        break;

      case SWQ_FLOAT:
        poRetNode = new swq_expr_node( 
            poFeature->GetFieldAsDouble(op->field_index) );
        break;

      default:
        poRetNode = new swq_expr_node( 
            poFeature->GetFieldAsString(op->field_index) );
        break;
    }

    poRetNode->is_null = !(poFeature->IsFieldSet(op->field_index));

    return poRetNode;
}
void GDALClusterNeighbourhood::getNext(int id, int marker, std::map<int, int> & visited) {

	if (visited[id] > 0)
		return;

	visited[id] = marker;
	//Find my neighbours
	std::stringstream query;
	query << name_id1 << " = " << id;

	ngView.resetReading();
	ngView.setAttributeFilter(query.str().c_str());

	OGRFeature * ng;

	std::vector<int> neighbours;
	while (ng = ngView.getNextFeature()) {
		int id2 = ng->GetFieldAsInteger(name_id2.c_str());
		neighbours.push_back(id2);
	}

	foreach(int n, neighbours)
		getNext(n, marker, visited);
}
bool DataProcessingWorker::loadDataFromSources(int Step)
{
  emit stepEntered(tr("Loading and checking data from sources..."));


  GDALAllRegister_COMPAT();

  for (int i=0; i<m_SourcesInfos.size();i++)
  {

    QString RealURI = m_SourcesInfos[i].SourceURI;
    if (!m_SourcesInfos[i].CachedSourceURI.isEmpty())
      RealURI = m_SourcesInfos[i].CachedSourceURI;


    GDALDataset_COMPAT* DS = GDALOpenRO_COMPAT(RealURI.toStdString().c_str());

    if (DS == nullptr)
    {
      emit stepCompleted(Step,getStyledText(tr("[Error] Unable to open datasource for layer \"%1\"")
                                            .arg(m_SourcesInfos[i].LayerName),"red"));
      return false;
    }

    OGRLayer *Layer;
    OGRFeature *Feature;

    Layer = DS->GetLayerByName(m_SourcesInfos[i].LayerName.toStdString().c_str());

    // For cached layers as GeoJSON files
    // TODO do better for that!
    if (Layer == nullptr)
    {
      Layer = DS->GetLayer(0);
    }

    Layer->ResetReading();
    while((Feature = Layer->GetNextFeature()) != nullptr )
    {
      SourceUnit CurrentUnit;
      int CurrentUnitID;

      int FieldIndex = 0;
      QString FieldValue;

      // === Unit ID ===

      FieldIndex = Feature->GetFieldIndex(OGRGDAL_UNITID_FIELD);

      if (FieldIndex < 0)
      {
        GDALClose_COMPAT(DS);
        emit stepCompleted(Step,getStyledText(tr("[Error] Field for unit ID not found in layer \"%1\"")
                                              .arg(m_SourcesInfos[i].LayerName),"red"));
        return false;
      }

      CurrentUnitID = Feature->GetFieldAsInteger(FieldIndex);

      if (CurrentUnitID <= 0)
      {
        GDALClose_COMPAT(DS);
        emit stepCompleted(Step,getStyledText(tr("[Error] Wrong field format for unit ID in layer \"%1\"")
                                              .arg(m_SourcesInfos[i].LayerName),"red"));
        return false;
      }

      if (m_SourcesData[i].isUnitExists(CurrentUnitID))
      {
        GDALClose_COMPAT(DS);
        emit stepCompleted(Step,getStyledText(tr("[Error] Unit ID %2 already exist in layer \"%1\"")
                                                 .arg(m_SourcesInfos[i].LayerName)
                                                 .arg(CurrentUnitID),
                                              "red"));
        return false;
      }


      // === Process order ===

      if (m_SourcesInfos[i].UnitsPcsOrdField.isEmpty())
      {
        CurrentUnit.ProcessOrder = 1;
      }
      else
      {
        FieldIndex = Feature->GetFieldIndex(m_SourcesInfos[i].UnitsPcsOrdField.toStdString().c_str());

        if (FieldIndex < 0)
        {
          GDALClose_COMPAT(DS);
          emit stepCompleted(Step,getStyledText(tr("[Error] Field for process order not found in layer \"%1\"")
                                                   .arg(m_SourcesInfos[i].LayerName),
                                                "red"));
          return false;
        }

        int PcsOrd = Feature->GetFieldAsInteger(FieldIndex);

        if (PcsOrd <= 0)
        {
          GDALClose_COMPAT(DS);
          emit stepCompleted(Step,getStyledText(tr("[Error] Wrong field format for process order in layer \"%1\"")
                                                 .arg(m_SourcesInfos[i].LayerName),
                                                "red"));
          return false;
        }

        CurrentUnit.ProcessOrder = PcsOrd;
      }


      // === To connections ===

      if (!m_SourcesInfos[i].ToConnectionsField.isEmpty())
      {
        FieldIndex = Feature->GetFieldIndex(m_SourcesInfos[i].ToConnectionsField.toStdString().c_str());

        if (FieldIndex < 0)
        {
          GDALClose_COMPAT(DS);
          emit stepCompleted(Step,getStyledText(tr("[Error] Field for \"To\" connections not found in layer \"%1\"")
                                                .arg(m_SourcesInfos[i].LayerName),"red"));
          return false;
        }

        CurrentUnit.ToConnStr = QString(Feature->GetFieldAsString(FieldIndex));

        if (!OGRGDALHelpers::convertConnectionsStringToList(CurrentUnit.ToConnStr,CurrentUnit.ToConn))
        {
          emit stepCompleted(Step,getStyledText(tr("[Error] Wrong field \"%2\" format for \"To\" connections "
                                                   "in layer \"%1\"")
                                                   .arg(m_SourcesInfos[i].LayerName)
                                                   .arg(m_SourcesInfos[i].ToConnectionsField),
                                                "red"));
          return false;
        }
      }


      // === Childof connections ===

      if (!m_SourcesInfos[i].ChildofConnectionsField.isEmpty())
      {
        FieldIndex = Feature->GetFieldIndex(m_SourcesInfos[i].ChildofConnectionsField.toStdString().c_str());

        if (FieldIndex < 0)
        {
          GDALClose_COMPAT(DS);
          emit stepCompleted(Step,
                             getStyledText(tr("[Error] Field for \"Child Of\" connections not found in layer \"%1\"")
                                           .arg(m_SourcesInfos[i].LayerName),"red"));
          return false;
        }

        CurrentUnit.ChildofConnStr = QString(Feature->GetFieldAsString(FieldIndex));

        if (!OGRGDALHelpers::convertConnectionsStringToList(CurrentUnit.ChildofConnStr,CurrentUnit.ChildofConn))
        {
          emit stepCompleted(Step,getStyledText(tr("[Error] Wrong field \"%2\" format for \"Child Of\" connections "
                                                   "in layer \"%1\"")
                                                   .arg(m_SourcesInfos[i].LayerName)
                                                   .arg(m_SourcesInfos[i].ChildofConnectionsField),
                                                "red"));
          return false;
        }
      }


      // === Attributes ===

      for (int j=0;j<m_SourcesInfos[i].ImportedFields.size(); j++)
      {
        FieldIndex = Feature->GetFieldIndex(m_SourcesInfos[i].ImportedFields[j].toStdString().c_str());

        if (FieldIndex <0)
        {
          GDALClose_COMPAT(DS);
          emit stepCompleted(Step,getStyledText(tr("[Error] Field for attribute \"%2\" not found in layer \"%1\"")
                                                   .arg(m_SourcesInfos[i].LayerName)
                                                   .arg(m_SourcesInfos[i].ImportedFields[j]),
                                                "red"));
          return false;
        }

        // replacing unwanted chars (space, tab) by underscore
        QString Attr;

        if (!OGRGDALHelpers::convertFieldToAttribute(Feature,FieldIndex,Attr))
        {
          GDALClose_COMPAT(DS);
          emit stepCompleted(Step,getStyledText(tr("[Error] Wrong field format for attribute \"%2\" in layer \"%1\"")
                                                   .arg(m_SourcesInfos[i].LayerName)
                                                   .arg(m_SourcesInfos[i].ImportedFields[j]),
                                                "red"));
          return false;
        }

        CurrentUnit.Attributes[m_SourcesInfos[i].ImportedFields[j]] = Attr.replace(" ","_")
                                                                          .replace("\t","_");
      }


      // === Area computed attribute ===

      if (m_SourcesInfos[i].IsAreaCompute)
      {
        if (m_SourcesInfos[i].ImportedFields.contains(m_SourcesInfos[i].AreaComputeAttribute))
        {
          GDALClose_COMPAT(DS);
          emit stepCompleted(Step,getStyledText(tr("[Error] Attribute \"%2\" for computed area attribute "
                                                   "is already imported from layer \"%1\"")
                                                   .arg(m_SourcesInfos[i].LayerName)
                                                   .arg(m_SourcesInfos[i].AreaComputeAttribute),
                                                "red"));
          return false;
        }
        else
        {
          double Area = ((OGRPolygon*)(Feature->GetGeometryRef()))->get_Area();
          CurrentUnit.Attributes[m_SourcesInfos[i].AreaComputeAttribute] = QString::number(Area,'g');
        }
      }


      // === Length computed attribute ===

      if (m_SourcesInfos[i].IsLengthCompute)
      {
        if (m_SourcesInfos[i].ImportedFields.contains(m_SourcesInfos[i].LengthComputeAttribute))
        {
          GDALClose_COMPAT(DS);
          emit stepCompleted(Step,getStyledText(tr("[Error] Attribute \"%2\" for computed length attribute "
                                                   "is already imported from layer \"%1\"")
                                                   .arg(m_SourcesInfos[i].LayerName)
                                                   .arg(m_SourcesInfos[i].LengthComputeAttribute),
                                                "red"));
          return false;
        }
        else
        {
          double Length = ((OGRLineString*)(Feature->GetGeometryRef()))->get_Length();
          CurrentUnit.Attributes[m_SourcesInfos[i].LengthComputeAttribute] = QString::number(Length,'g');
        }
      }


      // === Preprocess for computed centroid

      OGRPoint Centroid;

      if (Feature->GetGeometryRef()->Centroid(&Centroid) != OGRERR_NONE)
      {
        GDALClose_COMPAT(DS);
        emit stepCompleted(Step,
                           getStyledText(tr("[Error] Unable to compute centroid coordinates "
                                            "for geometries in layer \"%1\"."
                                            "Computing centroid coordinates should be unchecked "
                                            "in computed attributes.")
                                         .arg(m_SourcesInfos[i].LayerName),"red"));
        return false;
      }


      // === XCentroid computed attribute ===

      if (m_SourcesInfos[i].IsXCentroidCompute)
      {
        if (m_SourcesInfos[i].ImportedFields.contains(m_SourcesInfos[i].XCentroidComputeAttribute))
        {
          GDALClose_COMPAT(DS);
          emit stepCompleted(Step,getStyledText(tr("[Error] Attribute \"%2\" for computed centroid X attribute "
                                                   "is already imported from layer \"%1\"")
                                                   .arg(m_SourcesInfos[i].LayerName)
                                                   .arg(m_SourcesInfos[i].XCentroidComputeAttribute),
                                                "red"));
          return false;
        }
        else
        {
          CurrentUnit.Attributes[m_SourcesInfos[i].XCentroidComputeAttribute] = QString::number(Centroid.getX(),'g');
        }
      }


      // === YCentroid computed attribute ===

      if (m_SourcesInfos[i].IsYCentroidCompute)
      {
        if (m_SourcesInfos[i].ImportedFields.contains(m_SourcesInfos[i].YCentroidComputeAttribute))
        {
          GDALClose_COMPAT(DS);
          emit stepCompleted(Step,getStyledText(tr("[Error] Attribute \"%2\" for computed centroid Y attribute "
                                                   "is already imported from layer \"%1\"")
                                                   .arg(m_SourcesInfos[i].LayerName)
                                                   .arg(m_SourcesInfos[i].YCentroidComputeAttribute),
                                                "red"));
          return false;
        }
        else
        {
          CurrentUnit.Attributes[m_SourcesInfos[i].YCentroidComputeAttribute] = QString::number(Centroid.getY(),'g');
        }
      }


      // === ZCentroid computed attribute ===

      if (m_SourcesInfos[i].IsZCentroidCompute)
      {
        if (m_SourcesInfos[i].ImportedFields.contains(m_SourcesInfos[i].ZCentroidComputeAttribute))
        {
          GDALClose_COMPAT(DS);
          emit stepCompleted(Step,getStyledText(tr("[Error] Attribute \"%2\" for computed centroid Z attribute "
                                                   "is already imported from layer \"%1\"")
                                                   .arg(m_SourcesInfos[i].LayerName)
                                                   .arg(m_SourcesInfos[i].ZCentroidComputeAttribute),
                                                "red"));
          return false;
        }
        else
        {
          CurrentUnit.Attributes[m_SourcesInfos[i].ZCentroidComputeAttribute] = QString::number(Centroid.getZ(),'g');
        }
      }


      m_SourcesData[i].Units[CurrentUnitID] = CurrentUnit;
    }

    GDALClose_COMPAT(DS);
    DS = nullptr;
  }

  emit stepCompleted(Step,getStyledText(tr("[OK]"),"green"));
  return true;
}
Example #14
0
feature_ptr ogr_featureset::next()
{
    OGRFeature *poFeature;
    while ((poFeature = layer_.GetNextFeature()) != NULL)
    {
        // ogr feature ids start at 0, so add one to stay
        // consistent with other mapnik datasources that start at 1
        const int feature_id = (poFeature->GetFID() + 1);
        feature_ptr feature(feature_factory::create(ctx_,feature_id));

        OGRGeometry* geom = poFeature->GetGeometryRef();
        if (geom && ! geom->IsEmpty())
        {
            ogr_converter::convert_geometry(geom, feature);
        }
        else
        {
            MAPNIK_LOG_DEBUG(ogr) << "ogr_featureset: Feature with null geometry="
                << poFeature->GetFID();
            OGRFeature::DestroyFeature( poFeature );
            continue;
        }

        ++count_;

        int fld_count = layerdef_->GetFieldCount();
        for (int i = 0; i < fld_count; i++)
        {
            OGRFieldDefn* fld = layerdef_->GetFieldDefn(i);
            const OGRFieldType type_oid = fld->GetType();
            const std::string fld_name = fld->GetNameRef();

            switch (type_oid)
            {
            case OFTInteger:
            {
                feature->put( fld_name, poFeature->GetFieldAsInteger(i));
                break;
            }

            case OFTReal:
            {
                feature->put( fld_name, poFeature->GetFieldAsDouble(i));
                break;
            }

            case OFTString:
            case OFTWideString:     // deprecated !
            {
                UnicodeString ustr = tr_->transcode(poFeature->GetFieldAsString(i));
                feature->put( fld_name, ustr);
                break;
            }

            case OFTIntegerList:
            case OFTRealList:
            case OFTStringList:
            case OFTWideStringList: // deprecated !
            {
                MAPNIK_LOG_WARN(ogr) << "ogr_featureset: Unhandled type_oid=" << type_oid;
                break;
            }

            case OFTBinary:
            {
                MAPNIK_LOG_WARN(ogr) << "ogr_featureset: Unhandled type_oid=" << type_oid;
                //feature->put(name,feat->GetFieldAsBinary (i, size));
                break;
            }

            case OFTDate:
            case OFTTime:
            case OFTDateTime:       // unhandled !
            {
                MAPNIK_LOG_WARN(ogr) << "ogr_featureset: Unhandled type_oid=" << type_oid;
                break;
            }

            default: // unknown
            {
                MAPNIK_LOG_WARN(ogr) << "ogr_featureset: Unknown type_oid=" << type_oid;
                break;
            }
            }
        }
        OGRFeature::DestroyFeature( poFeature );
        return feature;
    }

    MAPNIK_LOG_DEBUG(ogr) << "ogr_featureset: " << count_ << " features";

    return feature_ptr();
}
Example #15
0
feature_ptr ogr_featureset::next()
{
    if (count_ == 0)
    {
        // Reset the layer reading on the first feature read
        // this is a hack, but needed due to https://github.com/mapnik/mapnik/issues/2048
        // Proper solution is to avoid storing layer state in featureset
        layer_.ResetReading();
    }
    OGRFeature *poFeature;
    while ((poFeature = layer_.GetNextFeature()) != nullptr)
    {
        // ogr feature ids start at 0, so add one to stay
        // consistent with other mapnik datasources that start at 1
        mapnik::value_integer feature_id = (poFeature->GetFID() + 1);
        feature_ptr feature(feature_factory::create(ctx_,feature_id));

        OGRGeometry* geom = poFeature->GetGeometryRef();
        if (geom && ! geom->IsEmpty())
        {
            auto geom_corrected = ogr_converter::convert_geometry(geom);
            mapnik::geometry::correct(geom_corrected);
            feature->set_geometry(std::move(geom_corrected));
        }
        else
        {
            MAPNIK_LOG_DEBUG(ogr) << "ogr_featureset: Feature with null geometry="
                << poFeature->GetFID();
            OGRFeature::DestroyFeature( poFeature );
            continue;
        }

        ++count_;

        int fld_count = layerdef_->GetFieldCount();
        for (int i = 0; i < fld_count; i++)
        {
            OGRFieldDefn* fld = layerdef_->GetFieldDefn(i);
            const OGRFieldType type_oid = fld->GetType();
            const std::string fld_name = fld->GetNameRef();

            switch (type_oid)
            {
            case OFTInteger:
            {
                feature->put<mapnik::value_integer>( fld_name, poFeature->GetFieldAsInteger(i));
                break;
            }
#if GDAL_VERSION_MAJOR >= 2
            case OFTInteger64:
            {
                feature->put<mapnik::value_integer>( fld_name, poFeature->GetFieldAsInteger64(i));
                break;
            }
#endif

            case OFTReal:
            {
                feature->put( fld_name, poFeature->GetFieldAsDouble(i));
                break;
            }

            case OFTString:
            case OFTWideString:     // deprecated !
            {
                feature->put( fld_name, tr_->transcode(poFeature->GetFieldAsString(i)));
                break;
            }

            case OFTIntegerList:
#if GDAL_VERSION_MAJOR >= 2
            case OFTInteger64List:
#endif
            case OFTRealList:
            case OFTStringList:
            case OFTWideStringList: // deprecated !
            {
                MAPNIK_LOG_WARN(ogr) << "ogr_featureset: Unhandled type_oid=" << type_oid;
                break;
            }

            case OFTBinary:
            {
                MAPNIK_LOG_WARN(ogr) << "ogr_featureset: Unhandled type_oid=" << type_oid;
                //feature->put(name,feat->GetFieldAsBinary (i, size));
                break;
            }

            case OFTDate:
            case OFTTime:
            case OFTDateTime:       // unhandled !
            {
                MAPNIK_LOG_WARN(ogr) << "ogr_featureset: Unhandled type_oid=" << type_oid;
                break;
            }

            default: // unknown
            {
                MAPNIK_LOG_WARN(ogr) << "ogr_featureset: Unknown type_oid=" << type_oid;
                break;
            }
            }
        }
        OGRFeature::DestroyFeature( poFeature );
        return feature;
    }

    MAPNIK_LOG_DEBUG(ogr) << "ogr_featureset: " << count_ << " features";

    return feature_ptr();
}
Example #16
0
CPLErr GNMGenericNetwork::ChangeBlockState(GNMGFID nFID, bool bIsBlock)
{
    if(!m_bIsGraphLoaded && LoadGraph() != CE_None)
    {
        return CE_Failure;
    }

    // change block state in layer
    OGRLayer* poLayer = GetLayerByName(m_moFeatureFIDMap[nFID]);
    if(NULL == poLayer)
    {
        CPLError( CE_Failure, CPLE_AppDefined, "Failed to get layer '%s'.",
                  m_moFeatureFIDMap[nFID].c_str() );
        return CE_Failure;
    }

    OGRFeature* poFeature = poLayer->GetFeature(nFID);
    if(NULL == poFeature)
    {
        CPLError( CE_Failure, CPLE_AppDefined, "Failed to get feature '"
                  GNMGFIDFormat"'.", nFID );
        return CE_Failure;
    }

    if(bIsBlock)
    {
        poFeature->SetField( GNM_SYSFIELD_BLOCKED, GNM_BLOCK_ALL );
    }
    else
    {
        poFeature->SetField( GNM_SYSFIELD_BLOCKED, GNM_BLOCK_NONE );
    }

    if( poLayer->SetFeature( poFeature ) != OGRERR_NONE )
    {
        OGRFeature::DestroyFeature( poFeature );
        CPLError( CE_Failure, CPLE_AppDefined, "Failed to update feature." );
        return CE_Failure;
    }

    OGRFeature::DestroyFeature( poFeature );

    GNMGFID nSrcFID, nTgtFID, nConFID;

    // change block state in graph layer
    m_poGraphLayer->ResetReading();
    while ((poFeature = m_poGraphLayer->GetNextFeature()) != NULL)
    {
        nSrcFID = poFeature->GetFieldAsGNMGFID(GNM_SYSFIELD_SOURCE);
        nTgtFID = poFeature->GetFieldAsGNMGFID(GNM_SYSFIELD_TARGET);
        nConFID = poFeature->GetFieldAsGNMGFID(GNM_SYSFIELD_CONNECTOR);
        int nBlockState = poFeature->GetFieldAsInteger(GNM_SYSFIELD_BLOCKED);

        if(bIsBlock)
        {
            if(nSrcFID == nFID)
                nBlockState |= GNM_BLOCK_SRC;
            else if(nTgtFID == nFID)
                nBlockState |= GNM_BLOCK_TGT;
            else if(nConFID == nFID)
                nBlockState |= GNM_BLOCK_CONN;

            poFeature->SetField( GNM_SYSFIELD_BLOCKED, nBlockState );
        }
        else
        {
            if(nSrcFID == nFID)
                nBlockState &= ~GNM_BLOCK_SRC;
            else if(nTgtFID == nFID)
                nBlockState &= ~GNM_BLOCK_TGT;
            else if(nConFID == nFID)
                nBlockState &= ~GNM_BLOCK_CONN;

            poFeature->SetField( GNM_SYSFIELD_BLOCKED, nBlockState );
        }

        if( m_poGraphLayer->SetFeature( poFeature ) != OGRERR_NONE )
        {
            OGRFeature::DestroyFeature( poFeature );
            CPLError( CE_Failure, CPLE_AppDefined, "Failed to update feature." );
            return CE_Failure;
        }

        OGRFeature::DestroyFeature( poFeature );
    }

    // change block state in graph
    m_oGraph.ChangeBlockState(nFID, bIsBlock);

    return CE_None;
}
Example #17
0
int ILI1Reader::ReadTable(const char *layername) {
    char **tokens = NULL;
    const char *firsttok = NULL;
    int ret = TRUE;
    int warned = FALSE;
    int fIndex;
    int geomIdx;

    // curLayer is NULL if we have more than one
    // point geometry column
    if(curLayer == NULL) {
      OGRFeature *metaFeature = NULL;
      metaLayer->ResetReading();
      while((metaFeature = metaLayer->GetNextFeature()) != NULL ) {
        if(EQUAL(layername, metaFeature->GetFieldAsString(0))) {
          const char *geomlayername = metaFeature->GetFieldAsString(2);
          curLayer = GetLayerByName(geomlayername);
          break;
        }
      }
    }

    OGRFeatureDefn *featureDef = curLayer->GetLayerDefn();
    OGRFeature *feature = NULL;

    // get the geometry index of the current layer
    // only if the model is read
    if(featureDef->GetFieldCount() != 0) {
      OGRFeature *metaFeature = NULL;
      metaLayer->ResetReading();
      while((metaFeature = metaLayer->GetNextFeature()) != NULL ) {
        if(EQUAL(curLayer->GetLayerDefn()->GetName(), metaFeature->GetFieldAsString(2))) {
          geomIdx = metaFeature->GetFieldAsInteger(1);
        }
      }
    }

    long fpos = VSIFTell(fpItf);
    while (ret && (tokens = ReadParseLine()))
    {
      firsttok = CSLGetField(tokens, 0);
      if (EQUAL(firsttok, "OBJE"))
      {
        //Check for features spread over multiple objects
        if (featureDef->GetGeomType() == wkbPolygon)
        {
          //Multiple polygon rings
          feature = curLayer->GetFeatureRef(atol(CSLGetField(tokens, 2)));
        }
        else if (featureDef->GetGeomType() == wkbGeometryCollection)
        {
          //AREA lines spread over mutltiple objects
        }
        else
        {
          feature = NULL;
        }

        if (feature == NULL)
        {
          if (featureDef->GetFieldCount() == 0)
          {
            CPLDebug( "OGR_ILI", "No field definition found for table: %s", featureDef->GetName() );
            //Model not read - use heuristics
            for (fIndex=1; fIndex<CSLCount(tokens); fIndex++)
            {
              char szFieldName[32];
              sprintf(szFieldName, "Field%02d", fIndex);
              OGRFieldDefn oFieldDefn(szFieldName, OFTString);
              featureDef->AddFieldDefn(&oFieldDefn);
            }
          }
          //start new feature
          feature = new OGRFeature(featureDef);

          int fieldno = 0;
          for (fIndex=1; fIndex<CSLCount(tokens) && fieldno < featureDef->GetFieldCount(); fIndex++, fieldno++)
          {
            if (!EQUAL(tokens[fIndex], "@")) {
              //CPLDebug( "READ TABLE OGR_ILI", "Adding Field %d: %s", fieldno, tokens[fIndex]);
              feature->SetField(fieldno, tokens[fIndex]);
              if (featureDef->GetFieldDefn(fieldno)->GetType() == OFTReal
                  && fieldno > 0
                  && featureDef->GetFieldDefn(fieldno-1)->GetType() == OFTReal
                  && featureDef->GetGeomType() == wkbPoint

                  /*
                  // if there is no ili model read,
                  // we have no chance to detect the
                  // geometry column!!
                  */

                  && (fieldno-2) == geomIdx) {
                //add Point geometry
                OGRPoint *ogrPoint = new OGRPoint(atof(tokens[fIndex-1]), atof(tokens[fIndex]));
                feature->SetGeometryDirectly(ogrPoint);
              }
            }
          }
          if (!warned && featureDef->GetFieldCount() != CSLCount(tokens)-1 && !(featureDef->GetFieldCount() == CSLCount(tokens) && EQUAL(featureDef->GetFieldDefn(featureDef->GetFieldCount()-1)->GetNameRef(), "ILI_Geometry"))) {
            CPLDebug( "OGR_ILI", "Field count doesn't match. %d declared, %d found", featureDef->GetFieldCount(), CSLCount(tokens)-1);
            warned = TRUE;
          }
          if (featureDef->GetGeomType() == wkbPolygon)
            feature->SetFID(atol(feature->GetFieldAsString(1)));
          else if (feature->GetFieldCount() > 0)
            feature->SetFID(atol(feature->GetFieldAsString(0)));
          curLayer->AddFeature(feature);
        }
      }
      else if (EQUAL(firsttok, "STPT"))
      {
        ReadGeom(tokens, featureDef->GetGeomType(), feature);
        if (EQUAL(featureDef->GetFieldDefn(featureDef->GetFieldCount()-1)->GetNameRef(), "ILI_Geometry"))
        {
          AddIliGeom(feature, featureDef->GetFieldCount()-1, fpos); //TODO: append multi-OBJECT geometries
        }
      }
      else if (EQUAL(firsttok, "ELIN"))
      {
        //empty geom
      }
      else if (EQUAL(firsttok, "EDGE"))
      {
        tokens = ReadParseLine(); //STPT
        ReadGeom(tokens, wkbMultiLineString, feature);
        if (EQUAL(featureDef->GetFieldDefn(featureDef->GetFieldCount()-1)->GetNameRef(), "ILI_Geometry"))
        {
          AddIliGeom(feature, featureDef->GetFieldCount()-1, fpos);
        }
      }
      else if (EQUAL(firsttok, "PERI"))
      {
      }
      else if (EQUAL(firsttok, "ETAB"))
      {
        if(HasMultiplePointGeom(layername) > 0) {
          OGRFeature *metaFeature = NULL;
          metaLayer->ResetReading();
          while((metaFeature = metaLayer->GetNextFeature()) != NULL ) {
            int pntCln = 1;
            if(EQUAL(layername, metaFeature->GetFieldAsString(0)) && !EQUAL(curLayer->GetLayerDefn()->GetName(), metaFeature->GetFieldAsString(2))) {
              pntCln++;
              OGRILI1Layer *curLayerTmp = GetLayerByName(metaFeature->GetFieldAsString(2));
              OGRFeature *tmpFeature = NULL;
              int geomIdxTmp = metaFeature->GetFieldAsInteger(1);
              curLayer->ResetReading();
              while((tmpFeature = curLayer->GetNextFeature()) != NULL ) {
                OGRPoint *ogrPoint = new OGRPoint(atof(tmpFeature->GetFieldAsString(geomIdxTmp + pntCln)), atof(tmpFeature->GetFieldAsString(geomIdxTmp + pntCln + 1)));
                tmpFeature->SetGeometryDirectly(ogrPoint);
                curLayerTmp->AddFeature(tmpFeature);
              }
            }
          }
        }
        CSLDestroy(tokens);
        return TRUE;
      }
      else
      {
        CPLDebug( "OGR_ILI", "Unexpected token: %s", firsttok );
      }

      CSLDestroy(tokens);
      fpos = VSIFTell(fpItf);
    }

    return ret;
}
Example #18
0
OGRFeature* OGRPLScenesLayer::GetNextRawFeature()
{
    if( bEOF ||
        (!bFilterMustBeClientSideEvaluated && nFeatureCount >= 0 && nNextFID > nFeatureCount) )
        return NULL;

    if( poGeoJSONLayer == NULL )
    {
        if( !GetNextPage() )
            return NULL;
    }

#ifdef notdef
    if( CSLTestBoolean(CPLGetConfigOption("OGR_LIMIT_TOO_MANY_FEATURES", "FALSE")) &&
        nFeatureCount > nPageSize )
    {
        bEOF = TRUE;
        OGRFeature* poFeature = new OGRFeature(poFeatureDefn);
        OGRGeometry* poGeom;
        const char* pszWKT = "MULTIPOLYGON(((-180 90,180 90,180 -90,-180 -90,-180 90)))";
        OGRGeometryFactory::createFromWkt((char**)&pszWKT, poSRS, &poGeom);
        poFeature->SetGeometryDirectly(poGeom);
        return poFeature;
    }
#endif

    OGRFeature* poGeoJSONFeature = poGeoJSONLayer->GetNextFeature();
    if( poGeoJSONFeature == NULL )
    {
        osRequestURL = osNextURL;
        bStillInFirstPage = FALSE;
        if( !GetNextPage() )
            return NULL;
        poGeoJSONFeature = poGeoJSONLayer->GetNextFeature();
        if( poGeoJSONFeature == NULL )
        {
            bEOF = TRUE;
            return NULL;
        }
    }
    OGRFeature* poFeature = new OGRFeature(poFeatureDefn);
    poFeature->SetFID(nNextFID++);

    OGRGeometry* poGeom = poGeoJSONFeature->StealGeometry();
    if( poGeom != NULL )
    {
        if( poGeom->getGeometryType() == wkbPolygon )
        {
            OGRMultiPolygon* poMP = new OGRMultiPolygon();
            poMP->addGeometryDirectly(poGeom);
            poGeom = poMP;
        }
        poGeom->assignSpatialReference(poSRS);
        poFeature->SetGeometryDirectly(poGeom);
    }
    
    for(int i=0;i<poFeatureDefn->GetFieldCount();i++)
    {
        OGRFieldDefn* poFieldDefn = poFeatureDefn->GetFieldDefn(i);
        OGRFieldType eType = poFieldDefn->GetType();
        int iSrcField = poGeoJSONFeature->GetFieldIndex(poFieldDefn->GetNameRef());
        if( iSrcField >= 0 && poGeoJSONFeature->IsFieldSet(iSrcField) )
        {
            if( eType == OFTInteger )
                poFeature->SetField(i,
                    poGeoJSONFeature->GetFieldAsInteger(iSrcField));
            else if( eType == OFTReal )
                poFeature->SetField(i,
                    poGeoJSONFeature->GetFieldAsDouble(iSrcField));
            else
                poFeature->SetField(i,
                    poGeoJSONFeature->GetFieldAsString(iSrcField));
        }
    }

    delete poGeoJSONFeature;

    return poFeature;
}
Example #19
0
void DrawShape::paintMap(WPaintDevice *paintDevice)
{
	WPainter painter(paintDevice);
	painter.setRenderHint(WPainter::LowQualityShadows);
	painter.save();
	if(!sfile.empty()) {

		vector<LABELS> label_list;
		OGRDataSource       *poDS,*PointDS;
		string dfile = sfile  + ".shp";
		string shp = "g_4326/" + sfile + ".shp";
		poDS = OGRSFDriverRegistrar::Open(shp.c_str(), FALSE );  //comment till here

		if(poDS==NULL)
		{
			printf( "Open failed.\n" );
			exit( 1 );
		}
		OGRLayer  *poLayer;
		poLayer = poDS->GetLayerByName( sfile.c_str() ); // comment here 
		OGRFeature *poFeature;
		OGREnvelope *   	 psExtent = new OGREnvelope();

		poLayer->GetExtent(psExtent);
		double xMin = psExtent->MinX;
		double yMin = psExtent->MinY;
		double xMax = psExtent->MaxX;
		double yMax = psExtent->MaxY;

		stringstream strm;
		strm << xMin;
		string exp;
		double scaleFactor;
		string bound_string = strm.str();
		int size = bound_string.size();
		size_t found=bound_string.find("+");
		if (found!=string::npos) {
			exp =  bound_string.substr(found+1,size);     
		}

		if(exp.empty()) {

			stringstream strExtent;
			strExtent << yMin;
			bound_string = strExtent.str();
			size = bound_string.size();
			found = bound_string.find("+");
			if(found!=string::npos) {
				exp = bound_string.substr(found+1,size); 
			}
		}
		if(exp.empty()) {
			stringstream strExtent;
			strExtent << xMax;
			bound_string = strExtent.str();
			size = bound_string.size();
			found = bound_string.find("+");
			if(found!=string::npos) {
				exp = bound_string.substr(found+1,size); 
			}
		}
		if(exp.empty()) {
			stringstream strExtent;
			strExtent << yMax;
			bound_string = strExtent.str();
			size = bound_string.size();
			found = bound_string.find("+");
			if(found!=string::npos) {
				exp = bound_string.substr(found+1,size); 
			}
		}
		//cout << "EXXP: " << exp << endl;
		if(!exp.empty()) {
			int exponent  = boost::lexical_cast<int>(exp);

			exponent-=3;
			scaleFactor = pow (10,exponent);
		}
		else
		{
			//cout << "EXXP is empty " << exp << endl;
			scaleFactor = 1;
		}

		xMin/=scaleFactor;
		xMax/=scaleFactor;
		yMin/=scaleFactor;
		yMax/=scaleFactor;

		double gWidth = xMax - xMin;
		double gHeight = yMax - yMin;
		double widthFactor = 1;
		double pwidth = abs(gWidth-gHeight);
		double s = gWidth - gHeight;
		if(s<0.16)
			gWidth = gHeight + 0.16;

		double ratio=gWidth/gHeight;
		//for zoom n pan
		if(increase_width<100 && increase_height<100){
			painter.setWindow(xMin +(-x_pos_shift+increase_width/2)/100*gWidth* widthFactor, yMax+(y_pos_shift-increase_height/2)/100*gHeight * widthFactor, gWidth* widthFactor*(100-increase_width)/100, gHeight * widthFactor*(-1+increase_height/100));

			brush.setStyle(SolidPattern);
			brush.setColor(backcolor);
			painter.setBrush(brush);
			painter.drawRect(xMin +(-x_pos_shift+increase_width/2)/100*gWidth* widthFactor, yMax+(y_pos_shift-increase_height/2)/100*gHeight * widthFactor, gWidth* widthFactor*(100-increase_width)/100, gHeight * widthFactor*(-1+increase_height/100));
}
		else{
			painter.setWindow(xMin +x_pos_shift, yMax-y_pos_shift, 0, 0);
}

		// for normal picture

		//painter.setWindow(xMin , yMax, gWidth* widthFactor, -gHeight * widthFactor);
		pwidth/=480;
		pwidth*=4;
		//if(iwidth<0.06)
		//		iwidth=0.06;
		if(iwidth == 0.0015){
			pen.setWidth(pwidth);
		}
		else
		{
			pen.setWidth(iwidth);
		}

		//std::cerr<<pwidth<<" "<<iwidth<<"\n";
		pen.setColor(bordercolor);
		brush.setStyle(SolidPattern);
		brush.setColor(fillcolor);
		font= new WFont();
		font->setSize(WLength(labelpercentage*gWidth*widthFactor));
		painter.setFont(*font);
		painter.setPen(pen);
		painter.setBrush(brush);
		WPainterPath path;
		poLayer->ResetReading();


		OGRPoint *centroid = new OGRPoint();
		char label[100];
		while( (poFeature = poLayer->GetNextFeature()) != NULL )
		{
			centroid->empty();
			label[0]=0;
			if(labelindex>0)
			{
				OGRFeatureDefn *PointFDefn = poLayer->GetLayerDefn();
				OGRFieldDefn *PointFieldDefn = PointFDefn->GetFieldDefn(labelindex-1);
				if( PointFieldDefn->GetType() == OFTInteger )
					sprintf(label, "%d", poFeature->GetFieldAsInteger(labelindex-1) );
				else if( PointFieldDefn->GetType() == OFTReal )
					sprintf(label, "%.3f", poFeature->GetFieldAsDouble(labelindex-1) );
				else if( PointFieldDefn->GetType() == OFTString )
					sprintf(label, "%s", poFeature->GetFieldAsString(labelindex-1) );
				else
					sprintf(label, "%s", poFeature->GetFieldAsString(labelindex-1) );
			}
			OGRGeometry *poGeometry;

			poGeometry = poFeature->GetGeometryRef();

			if( poGeometry != NULL && wkbFlatten(poGeometry->getGeometryType()) == wkbPoint )
			{
				OGRPoint *poPoint = (OGRPoint *) poGeometry;
				double x = poPoint->getX();
				double y = poPoint->getY();
				//painter.drawPoint(x/scaleFactor,y/scaleFactor);
				painter.drawEllipse(x/scaleFactor-0.005*gWidth*widthFactor,y/scaleFactor-0.005*gWidth*widthFactor,0.01*gWidth*widthFactor,0.01*gWidth*widthFactor);
				poGeometry->Centroid(centroid);

			} //end wkbpoint

			else if( poGeometry != NULL  && wkbFlatten(poGeometry->getGeometryType()) == wkbLineString  )
			{
				OGRLineString *poPoint = (OGRLineString *) poGeometry;

				for(int i=0;i<poPoint->getNumPoints();i++)
				{
					double x=poPoint->getX(i) ;
					double y = poPoint->getY(i);
					x/=scaleFactor; y/=scaleFactor;

					if(i==0)
						path = WPainterPath( WPointF(x, y));
					else
						path.lineTo( x , y);
				}

				painter.drawPath(path); 
				poGeometry->Centroid(centroid); 
			}

			else if( (poGeometry != NULL)  &&  wkbFlatten(poGeometry->getGeometryType()) == wkbPolygon) 
			{
				OGRPolygon *poPoint = (OGRPolygon *) poGeometry;
				OGRLinearRing *extring = poPoint->getExteriorRing();

				int n = extring->getNumPoints();
				double x, y;
				for(int i=0;i<n;i++)
				{
					x = extring->getX(i);   y = extring->getY(i);
					x/=scaleFactor; y/=scaleFactor;
					if(i==0)
						path = WPainterPath( WPointF(x , y));

					else
						path.lineTo( x , y);
				}
				painter.drawPath(path);
				poGeometry->Centroid(centroid);

			}
			else if( (poGeometry != NULL)  &&  wkbFlatten(poGeometry->getGeometryType()) == wkbMultiPolygon) 
			{
				double x, y;
				OGRMultiPolygon *poPoint = (OGRMultiPolygon *) poGeometry;
				int p = poPoint->getNumGeometries();
				for(int k=0;k<p;k++) {
					OGRGeometry* geom = poPoint->getGeometryRef(k);
					OGRPolygon *poly = (OGRPolygon *) geom;
					OGRLinearRing  *ring = poly->getExteriorRing();

					for(int i=0;i<ring->getNumPoints();i++)
					{
						x = ring->getX(i);   y = ring->getY(i);
						x/=scaleFactor; y/=scaleFactor;
						if(i==0)
							path = WPainterPath( WPointF(x , y));
						else
							path.lineTo( x , y);

					}
					painter.drawPath(path); 
					poGeometry->Centroid(centroid);


				}

			}
			if(labelindex>0 && !centroid->IsEmpty()){
				LABELS l={centroid->getX(),centroid->getY(),label};
				label_list.push_back(l);
			}
		}
		painter.restore(); 


		//labelling the contents
if(increase_width<100 && increase_height<100){
		painter.setWindow(0.0, 0.0, (paintDevice->width()).value(),(paintDevice->height()).value());
		font= new WFont(WFont::SansSerif);
		font->setSize(WLength(10*labelpercentage));
		painter.setFont(*font);
		pen.setColor(labelcolor);
		painter.setPen(pen);
		std::vector<LABELS>::iterator the_iterator = label_list.begin();
		double x, y, minx=(xMin+(-x_pos_shift+increase_width/2)/100*gWidth* widthFactor),miny=(yMax+(y_pos_shift-increase_height/2)/100*gHeight*widthFactor);
		
		double multx=(paintDevice->width().value())/(gWidth* widthFactor*(100-increase_width)/100);
		double multy=(paintDevice->height().value())/(gHeight*widthFactor*(-1+increase_height/100));

		while( the_iterator != label_list.end() ) {
		
		x=((*the_iterator).x/scaleFactor-minx)*multx;
		y=((*the_iterator).y/scaleFactor-miny)*multy;
	
		painter.drawText(WRectF( x-(*the_iterator).label.size()*5*labelpercentage, y-5*labelpercentage, (*the_iterator).label.size()	*10*labelpercentage,10*labelpercentage),AlignCenter,(*the_iterator).label);
			++the_iterator;
		}
		pen.setColor(red);
		painter.setPen(pen);
		painter.setFont(*font);
		//painter.drawText(WRectF(paintDevice->width().value()-dfile.size()*10*labelpercentage,paintDevice->height().value()-10*labelpercentage*(paintDevice->height()).value(), dfile.size()*10*labelpercentage,10*labelpercentage ),AlignCenter,dfile); //this text is not seen in the picture when painted.
}
	}					



}
Example #20
0
    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());

            CreatedFeature->SetGeometry(SourceFeature->GetGeometryRef()->clone());
            CreatedFeature->SetField("OFLD_ID",SourceID);


            for (itV = itVb; itV != itVe; ++itV)
            {
              std::string VarName = (*itV).first;
              std::string FieldName = (*itV).second;
              openfluid::core::DoubleValue CreatedValue = 0.0;
              bool IsValueCreated = false;

              if (FieldName.empty())
                FieldName = VarName;

              openfluid::core::IndexedValue VarValue;

              if (OPENFLUID_IsVariableExist(UU,VarName))
              {
                OPENFLUID_GetLatestVariable(UU,VarName,VarValue);

                if (VarValue.value()->isDoubleValue()) // OpenFLUID value is double
                {
                  CreatedValue = VarValue.value()->asDoubleValue();
                  IsValueCreated = true;
                }
                else if (VarValue.value()->convert(CreatedValue)) // OpenFLUID value can be converted to double
                {
                  IsValueCreated = true;
                }
                else
                {
                  QString Msg = QString("Variable %1 on unit %2#%3 is not a double or a compatible type")
                                .arg(VarName.c_str()).arg(UU->getClass().c_str()).arg(UU->getID());
                  OPENFLUID_LogWarning(Msg.toStdString());
                }
              }
              else
              {
                QString Msg = QString("Variable %1 does not exist on unit %2#%3")
                              .arg(VarName.c_str()).arg(UU->getClass().c_str()).arg(UU->getID());
                OPENFLUID_LogWarning(Msg.toStdString());
              }

              if (IsValueCreated) // OpenFLUID value is written to GIS file only if it is double or converted to double
                CreatedFeature->SetField(FieldName.c_str(),CreatedValue);
            }

            if (CreatedLayer->CreateFeature(CreatedFeature) != OGRERR_NONE)
            {
              QString Msg = QString("Feature for unit %1#%2 cannot be created")
                            .arg(UU->getClass().c_str()).arg(UU->getID());
              OPENFLUID_LogWarning(Msg.toStdString());
            }


            OGRFeature::DestroyFeature(CreatedFeature);
          }
        }
        GDALClose_COMPAT(CreatedFile);
      }
    }
Example #21
0
bool MapWidget::loadCountyShapes()
{
    OGRRegisterAll();

    std::string filename = g_dataDirectory + "/counties/tl_2009_48_county00.shp";

    OGRDataSource * dataSource = OGRSFDriverRegistrar::Open(filename.c_str(), false);

    if(dataSource == NULL)
    {
        put_flog(LOG_ERROR, "could not open %s", filename.c_str());
        return false;
    }

    OGRLayer * layer = dataSource->GetLayerByName("tl_2009_48_county00");

    layer->ResetReading();

    OGRFeature * feature;

    while((feature = layer->GetNextFeature()) != NULL)
    {
        // get county FIPS code
        int nodeId = feature->GetFieldAsInteger("COUNTYFP00");

        if(nodeId == 0)
        {
            put_flog(LOG_WARN, "invalid county");
        }

        // add a new county to the counties map corresponding to this nodeId
        boost::shared_ptr<MapShape> county(new MapShape());
        counties_[nodeId] = county;

        OGRGeometry * geometry = feature->GetGeometryRef();

        if(geometry != NULL && geometry->getGeometryType() == wkbPolygon)
        {
            OGRPolygon * polygon = (OGRPolygon *)geometry;

            OGRLinearRing * ring = polygon->getExteriorRing();

            for(int i=0; i<ring->getNumPoints(); i++)
            {
                // x is longitude, y latitude
                county->addVertex(ring->getY(i), ring->getX(i));
            }

            // set the centroid
            OGRPoint centroidPoint;

            if(polygon->Centroid(&centroidPoint) == OGRERR_NONE)
            {
                county->setCentroid(centroidPoint.getY(), centroidPoint.getX());
            }
            else
            {
                put_flog(LOG_WARN, "no polygon centroid");
            }
        }
        else
        {
            put_flog(LOG_WARN, "no polygon geometry");
        }

        OGRFeature::DestroyFeature(feature);
    }

    OGRDataSource::DestroyDataSource(dataSource);

    return true;
}
Example #22
0
OGRFeature *TigerCompleteChain::GetFeature( int nRecordId )

{
    char        achRecord[OGR_TIGER_RECBUF_LEN];

    if( nRecordId < 0 || nRecordId >= nFeatures )
    {
        CPLError( CE_Failure, CPLE_FileIO,
                  "Request for out-of-range feature %d of %s1",
                  nRecordId, pszModule );
        return NULL;
    }

/* -------------------------------------------------------------------- */
/*      Read the raw record data from the file.                         */
/* -------------------------------------------------------------------- */
    if( fpPrimary == NULL )
        return NULL;

    if( VSIFSeekL( fpPrimary, (nRecordId+nRT1RecOffset) * nRecordLength, 
                  SEEK_SET ) != 0 )
    {
        CPLError( CE_Failure, CPLE_FileIO,
                  "Failed to seek to %d of %s1",
                  nRecordId * nRecordLength, pszModule );
        return NULL;
    }

    if( VSIFReadL( achRecord, psRT1Info->nRecordLength, 1, fpPrimary ) != 1 )
    {
        CPLError( CE_Failure, CPLE_FileIO,
                  "Failed to read %d bytes of record %d of %s1 at offset %d",
                  psRT1Info->nRecordLength, nRecordId, pszModule,
                  (nRecordId+nRT1RecOffset) * nRecordLength );
        return NULL;
    }

    /* -------------------------------------------------------------------- */
    /*      Set fields.                                                     */
    /* -------------------------------------------------------------------- */

    OGRFeature  *poFeature = new OGRFeature( poFeatureDefn );

    SetFields( psRT1Info, poFeature, achRecord );

    /* -------------------------------------------------------------------- */
    /*      Read RT3 record, and apply fields.                              */
    /* -------------------------------------------------------------------- */

    if( fpRT3 != NULL )
    {
        char    achRT3Rec[OGR_TIGER_RECBUF_LEN];
        int     nRT3RecLen = psRT3Info->nRecordLength + nRecordLength - psRT1Info->nRecordLength;

        if( VSIFSeekL( fpRT3, nRecordId * nRT3RecLen, SEEK_SET ) != 0 )
        {
            CPLError( CE_Failure, CPLE_FileIO,
                      "Failed to seek to %d of %s3",
                      nRecordId * nRT3RecLen, pszModule );
            return NULL;
        }

        if( VSIFReadL( achRT3Rec, psRT3Info->nRecordLength, 1, fpRT3 ) != 1 )
        {
            CPLError( CE_Failure, CPLE_FileIO,
                      "Failed to read record %d of %s3",
                      nRecordId, pszModule );
            return NULL;
        }

        SetFields( psRT3Info, poFeature, achRT3Rec );

    }

/* -------------------------------------------------------------------- */
/*      Set geometry                                                    */
/* -------------------------------------------------------------------- */
    OGRLineString       *poLine = new OGRLineString();

    poLine->setPoint(0,
                     atoi(GetField(achRecord, 191, 200)) / 1000000.0,
                     atoi(GetField(achRecord, 201, 209)) / 1000000.0 );

    if( !AddShapePoints( poFeature->GetFieldAsInteger("TLID"), nRecordId,
                         poLine, 0 ) )
    {
        delete poFeature;
        return NULL;
    }
    
    poLine->addPoint(atoi(GetField(achRecord, 210, 219)) / 1000000.0,
                     atoi(GetField(achRecord, 220, 228)) / 1000000.0 );

    poFeature->SetGeometryDirectly( poLine );

    return poFeature;
}
Example #23
0
void CDlg_GISDataExchange::ExportDataToCSV(CString csv_file_name)
{
#ifndef _WIN64

	CString message_str;
	OGRRegisterAll();
	OGRDataSource       *poDS;

	poDS = OGRSFDriverRegistrar::Open(m_GIS_ShapeFile, FALSE );
	if( poDS == NULL )
	{
		m_MessageList.AddString("Open file failed." );
		return;
	}

	ofstream CSVFile;
	CSVFile.open (csv_file_name, ios::out);

	if(CSVFile.is_open ()  == false)
	{
		AfxMessageBox("This file cannot be found or opened.\n It might be currently used and locked by EXCEL.");
		return;	 
	}else
	{
		CSVFile.width(15);
		CSVFile.precision(6) ;
		CSVFile.setf(ios::fixed);
	}

	int poLayers = ((OGRDataSource*)poDS)->GetLayerCount() ;
	for (int i=0; i < poLayers; i++) 
	{

		OGRLayer  *poLayer;

		poLayer = ((OGRDataSource*)poDS)->GetLayer(i);	

		if(poLayer == NULL)
		{
			message_str.Format("Open layer %d failed", i+1);
			m_MessageList.AddString (message_str);
			return;			
		}

		OGRFeature *poFeature;

		int feature_count = 0;

		poLayer->ResetReading();

		while( (poFeature = poLayer->GetNextFeature()) != NULL )
		{
			OGRFeatureDefn *poFDefn = poLayer->GetLayerDefn();
			int iField;

			if(feature_count == 0)    // first feature point, output field name;
			{
				for( iField = 0; iField < poFDefn->GetFieldCount(); iField++ )
				{

					OGRFieldDefn *poFieldDefn = poFDefn->GetFieldDefn( iField );
					CString str = poFieldDefn->GetNameRef();
					str.Replace(" ", NULL);  // remove space
					CSVFile <<  str << "," ;

				}

				CSVFile << "geometry" << endl;

			}

			for( iField = 0; iField < poFDefn->GetFieldCount(); iField++ )
			{

				OGRFieldDefn *poFieldDefn = poFDefn->GetFieldDefn( iField );
				CString str;

				if( poFieldDefn->GetType() == OFTInteger )
					CSVFile <<  poFeature->GetFieldAsInteger( iField ) << ",";
				else if( poFieldDefn->GetType() == OFTReal )
					CSVFile <<  poFeature->GetFieldAsDouble(iField) << ",";
				else if( poFieldDefn->GetType() == OFTString )
				{
					str = poFeature->GetFieldAsString(iField);
					if(str.Find(',') >=0) 
						CSVFile << "\"" << poFeature->GetFieldAsString(iField)  << "\",";
					else
						CSVFile <<   poFeature->GetFieldAsString(iField)  << ",";
				}
				else
				{
					str = poFeature->GetFieldAsString(iField);
					if(str.Find(',') >=0) 
						CSVFile << "\"" << poFeature->GetFieldAsString(iField)  << "\",";
					else
						CSVFile <<   poFeature->GetFieldAsString(iField)  << ",";
				}

			}

			OGRGeometry *poGeometry;

			poGeometry = poFeature->GetGeometryRef();
			if( poGeometry != NULL )
			{
				if(wkbFlatten(poGeometry->getGeometryType()) == wkbPoint )
				{
					OGRPoint *poPoint = (OGRPoint *) poGeometry;

					CSVFile << "\"<Point><coordinates>" <<  poPoint->getX() << ","  << poPoint->getY() << ",0.0" << "</coordinates></Point>\"" ;
				}
				else if (wkbFlatten(poGeometry->getGeometryType()) == wkbLineString)
				{
					OGRLineString *poLine = (OGRLineString *) poGeometry;

					CSVFile << "\"<LineString><coordinates>";

					for(unsigned int si = 0; si< poLine->getNumPoints(); si++)
					{
						CSVFile	 <<  poLine->getX(si) << ","  << poLine->getY(si) << ",0.0";

						if(si!=poLine->getNumPoints()-1)
							CSVFile << " ";
					}

					CSVFile << "</coordinates></LineString>\",";

				} if (wkbFlatten(poGeometry->getGeometryType()) == wkbPolygon )
				{

					OGRPolygon* polygon = (OGRPolygon*)(poGeometry);

					OGRLinearRing *ring = polygon->getExteriorRing();
					OGRPoint point;

					CSVFile << "\"<Polygon><outerBoundaryIs><LinearRing><coordinates>";

					for(int i = 0; i < ring->getNumPoints(); i++)
					{
						ring->getPoint(i, &point);
						CSVFile	 <<  point.getX() << ","  << point.getY() << ",0.0";

						if(i!=ring->getNumPoints()-1)
							CSVFile << " ";
					}

					CSVFile << "</coordinates></LinearRing></outerBoundaryIs></Polygon>\"";
				}
				CSVFile << endl;

			}
			feature_count ++;
		}
		OGRFeature::DestroyFeature( poFeature );
		message_str.Format("Layer %d has %d features.", i+1, feature_count);
		m_MessageList.AddString(message_str);


	}

	OGRDataSource::DestroyDataSource( poDS );

	CSVFile.close();
#endif
}
void CTLiteDoc::ImportOGRShapeFile(CString FileName)
{
	#ifndef _WIN64
	
		OGRRegisterAll();
			OGRDataSource       *poDS;

			poDS = OGRSFDriverRegistrar::Open(FileName, FALSE );
			if( poDS == NULL )
			{
				AfxMessageBox( "Open file failed." );
				return;
			}

	int poLayers = ((OGRDataSource*)poDS)->GetLayerCount() ;
    for (int i=0; i < poLayers; i++) 
    {

			OGRLayer  *poLayer;

	        poLayer = ((OGRDataSource*)poDS)->GetLayer(i);	

			if(poLayer == NULL)
			{
				AfxMessageBox( "Open layer failed." );
				return;			
			}

			OGRFeature *poFeature;

			poLayer->ResetReading();

			while( (poFeature = poLayer->GetNextFeature()) != NULL )
			{
				OGRFeatureDefn *poFDefn = poLayer->GetLayerDefn();
				int iField;

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

					if( poFieldDefn->GetType() == OFTInteger )
						TRACE( "%d,", poFeature->GetFieldAsInteger( iField ) );
					else if( poFieldDefn->GetType() == OFTReal )
						TRACE( "%.3f,", poFeature->GetFieldAsDouble(iField) );
					else if( poFieldDefn->GetType() == OFTString )
						TRACE( "%s,", poFeature->GetFieldAsString(iField) );
					else
						TRACE( "%s,", poFeature->GetFieldAsString(iField) );
				}

				OGRGeometry *poGeometry;

				TRACE("    ");
				poGeometry = poFeature->GetGeometryRef();
				if( poGeometry != NULL 
					&& wkbFlatten(poGeometry->getGeometryType()) == wkbPoint )
				{
					OGRPoint *poPoint = (OGRPoint *) poGeometry;

					TRACE( "x = %f ,y = %f\n", poPoint->getX(), poPoint->getY() );
				}
				else
				{
					TRACE( "no point geometry\n" );
				}       
				OGRFeature::DestroyFeature( poFeature );
			}
	}

			OGRDataSource::DestroyDataSource( poDS );
#else
	AfxMessageBox("NEXTA 64-bit version does not support shape file exporting function. Please use NEXTA_32.exe ");
	RunNEXTA_32();
#endif
}
Example #25
0
int main()
{
    GDALAllRegister();  //register all the format drivers
    cout << "GDAL All Registed!" << endl;

    GDALDataset *poDS;  //Data source
    poDS = (GDALDataset*) GDALOpenEx("./beijing/road/Nbeijing_point.shp", GDAL_OF_VECTOR, NULL, NULL, NULL);
    if(poDS == NULL)
    {
        cout << "Open shp file failed!" << endl;
        exit(1);
    }
    cout << "Data source open success!" << endl;

    int layerNum = poDS->GetLayerCount();   //a dataset may have many layers
    cout << "Layer number:" << layerNum << endl;

    OGRLayer *poLayer;
    poLayer = poDS->GetLayerByName("Nbeijing_point");
    
    //feature is a geometry and a set of attributes
    OGRFeature *poFeature;
    poLayer->ResetReading();    //Start at the beginning of the layer
    cout << "Feature number:" << poLayer->GetFeatureCount() << endl;

    stringstream ss;
    map<string, pair<double, double> > mip;
    map<string, pair<double, double> >::iterator imip;
    
	ofstream ofile("beijingNode");

    string id;
	int	crossFlag;
	string stmp, stmp2;
	vector<string> vs;
	vector<string>::iterator ivs;
    while((poFeature = poLayer->GetNextFeature()) != NULL)
    {
        //Defn contains the definition of all the fields
        OGRFeatureDefn *poFDefn = poLayer->GetLayerDefn();
//        for(iField = 0; iField < poFDefn->GetFieldCount(); iField++)
 //       {
//        OGRFieldDefn * poFieldDefn = poFDefn->GetFieldDefn(iField);
        id = poFeature->GetFieldAsString(1);

		ofile << id;

		crossFlag = poFeature->GetFieldAsInteger(4);
		if(crossFlag == 0)
		{
			ofile << "\t" << crossFlag << "\t" << 0 << "\t" << 0 << "\t" << 0;
		}
		else if(crossFlag == 1)
		{	
			ofile << "\t" << crossFlag << "\t" << 0 << "\t" << poFeature->GetFieldAsInteger(7) << "\t" << 0;
		}
		else if(crossFlag == 2)
		{
			stmp = poFeature->GetFieldAsString(6);
			vs = split(stmp, "|");
			ofile << "\t" << crossFlag << "\t" << vs.size();
			for(ivs = vs.begin(); ivs != vs.end(); ivs++)
				ofile << "\t" << *ivs;
			vs.clear();
			ofile << "\t" << poFeature->GetFieldAsInteger(7) << "\t" << 0;
		}
		else if(crossFlag == 3)
		{
			stmp = poFeature->GetFieldAsString(6);
			vs = split(stmp, "|");
			ofile << "\t" << crossFlag << "\t" << vs.size();
			for(ivs = vs.begin(); ivs != vs.end(); ivs++)
				ofile << "\t" << *ivs;
			vs.clear();
			
			ofile << "\t" << poFeature->GetFieldAsInteger(7);
			stmp = poFeature->GetFieldAsString(8);
			stmp2 = poFeature->GetFieldAsString(9);
			if(stmp2 != "")
				stmp += "|" + stmp2;
			vs = split(stmp, "|");
			ofile << "\t" << vs.size();
			for(ivs = vs.begin(); ivs != vs.end(); ivs++)
				ofile << "\t" << *ivs;
			vs.clear();
		}
	
		ofile << "\t" << poFeature->GetFieldAsString(11);

		stmp = poFeature->GetFieldAsString(12);
		vs = split(stmp, "|");
		ofile << "\t" << vs.size();
		for(ivs = vs.begin(); ivs != vs.end(); ivs++)
			ofile << "\t" << *ivs;
		vs.clear();
/*            if(poFieldDefn->GetType() == OFTInteger)
                cout << poFeature->GetFieldAsInteger(iField) << ", ";
            else if(poFieldDefn->GetType() == OFTInteger64)
                cout << poFeature->GetFieldAsInteger64(iField) << ", ";
            else if(poFieldDefn->GetType() == OFTReal)
                cout << setprecision(15) << poFeature->GetFieldAsDouble(iField) << ", ";
            else if(poFieldDefn->GetType() == OFTString)
                cout << poFeature->GetFieldAsString(iField) << ", ";
            else
                cout << poFeature->GetFieldAsString(iField) << ", ";*/
//        }

        OGRGeometry *poGeometry;
        poGeometry = poFeature->GetGeometryRef();
//        cout << "Geometry Type:" << poGeometry->getGeometryType() << endl;
        if(poGeometry != NULL && wkbFlatten(poGeometry->getGeometryType()) == wkbMultiPoint)
        {
            OGRMultiPoint *poMultiPoint = (OGRMultiPoint*)poGeometry;
  //          cout << "Number in the MultiPoint:" << poMultiPoint->getNumGeometries() << endl;

            OGRGeometry *pG;
            pG = poMultiPoint->getGeometryRef(0);
            OGRPoint *pP = (OGRPoint*)pG;
			ofile << "\t" <<  pP->getY() << "\t" << pP->getX();
//            pP->flattenTo2D();
 //           cout <<  setprecision(15) << pP->getY() << ", " << pP->getX() << endl;
 //           mip[id] = make_pair(pP->getY(), pP->getX());
            
         }
        else
            cout << "No Point Geometry" << endl;
		ofile << endl;
        OGRFeature::DestroyFeature(poFeature);
    }

/*	cout << "Writing nodes" << endl;
    for(imip = mip.begin(); imip != mip.end(); imip++)
        ofile << setprecision(15) << (*imip).first << "\t" << (*imip).second.first << "\t" << (*imip).second.second << endl;*/

    GDALClose(poFeature);
    ofile.close();

    return 0;
}
static int TestOGRLayerFeatureCount( OGRDataSource* poDS, OGRLayer *poLayer, int bIsSQLLayer )

{
    int bRet = TRUE;
    int         nFC = 0, nClaimedFC = poLayer->GetFeatureCount();
    OGRFeature  *poFeature;
    OGRSpatialReference * poSRS = poLayer->GetSpatialRef();
    int         bWarnAboutSRS = FALSE;
    OGRFeatureDefn* poLayerDefn = poLayer->GetLayerDefn();

    poLayer->ResetReading();

    while( (poFeature = poLayer->GetNextFeature()) != NULL )
    {
        nFC++;

        if (poFeature->GetDefnRef() != poLayerDefn)
        {
            bRet = FALSE;
            printf( "ERROR: Feature defn differs from layer defn.\n"
                    "Feature defn = %p\n"
                    "Layer defn = %p\n",
                     poFeature->GetDefnRef(), poLayerDefn);
        }

        if( poFeature->GetGeometryRef() != NULL
            && poFeature->GetGeometryRef()->getSpatialReference() != poSRS
            && !bWarnAboutSRS )
        {
            char        *pszLayerSRSWKT, *pszFeatureSRSWKT;
            
            bWarnAboutSRS = TRUE;

            if( poSRS != NULL )
                poSRS->exportToWkt( &pszLayerSRSWKT );
            else
                pszLayerSRSWKT = CPLStrdup("(NULL)");

            if( poFeature->GetGeometryRef()->getSpatialReference() != NULL )
                poFeature->GetGeometryRef()->
                    getSpatialReference()->exportToWkt( &pszFeatureSRSWKT );
            else
                pszFeatureSRSWKT = CPLStrdup("(NULL)");

            bRet = FALSE;
            printf( "ERROR: Feature SRS differs from layer SRS.\n"
                    "Feature SRS = %s (%p)\n"
                    "Layer SRS = %s (%p)\n",
                    pszFeatureSRSWKT, poFeature->GetGeometryRef()->getSpatialReference(),
                    pszLayerSRSWKT, poSRS );
            CPLFree( pszLayerSRSWKT );
            CPLFree( pszFeatureSRSWKT );
        }
        
        OGRFeature::DestroyFeature(poFeature);
    }

    if( nFC != nClaimedFC )
    {
        bRet = FALSE;
        printf( "ERROR: Claimed feature count %d doesn't match actual, %d.\n",
                nClaimedFC, nFC );
    }
    else if( nFC != poLayer->GetFeatureCount() )
    {
        bRet = FALSE;
        printf( "ERROR: Feature count at end of layer %d differs "
                "from at start, %d.\n",
                nFC, poLayer->GetFeatureCount() );
    }
    else if( bVerbose )
        printf( "INFO: Feature count verified.\n" );
        
    if (!bIsSQLLayer)
    {
        CPLString osSQL;
        osSQL.Printf("SELECT COUNT(*) FROM \"%s\"", poLayer->GetName());
        OGRLayer* poSQLLyr = poDS->ExecuteSQL(osSQL.c_str(), NULL, NULL);
        if (poSQLLyr)
        {
            OGRFeature* poFeatCount = poSQLLyr->GetNextFeature();
            if (nClaimedFC != poFeatCount->GetFieldAsInteger(0))
            {
                bRet = FALSE;
                printf( "ERROR: Claimed feature count %d doesn't match '%s' one, %d.\n",
                        nClaimedFC, osSQL.c_str(), poFeatCount->GetFieldAsInteger(0) );
            }
            OGRFeature::DestroyFeature(poFeatCount);
            poDS->ReleaseResultSet(poSQLLyr);
        }
    }

    if( bVerbose && !bWarnAboutSRS )
    {
        printf("INFO: Feature/layer spatial ref. consistency verified.\n");
    }

    return bRet;
}
OGRFeatureDefn * OGRCARTODBTableLayer::GetLayerDefnInternal(CPL_UNUSED json_object* poObjIn)
{
    if( poFeatureDefn != NULL )
        return poFeatureDefn;

    CPLString osCommand;
    if( poDS->IsAuthenticatedConnection() )
    {
        // Get everything !
        osCommand.Printf(
                 "SELECT a.attname, t.typname, a.attlen, "
                        "format_type(a.atttypid,a.atttypmod), "
                        "a.attnum, "
                        "a.attnotnull, "
                        "i.indisprimary, "
                        "pg_get_expr(def.adbin, c.oid) AS defaultexpr, "
                        "postgis_typmod_dims(a.atttypmod) dim, "
                        "postgis_typmod_srid(a.atttypmod) srid, "
                        "postgis_typmod_type(a.atttypmod)::text geomtyp, "
                        "srtext "
                 "FROM pg_class c "
                 "JOIN pg_attribute a ON a.attnum > 0 AND "
                                        "a.attrelid = c.oid AND c.relname = '%s' "
                 "JOIN pg_type t ON a.atttypid = t.oid "
                 "JOIN pg_namespace n ON c.relnamespace=n.oid AND n.nspname= '%s' "
                 "LEFT JOIN pg_index i ON c.oid = i.indrelid AND "
                                         "i.indisprimary = 't' AND a.attnum = ANY(i.indkey) "
                 "LEFT JOIN pg_attrdef def ON def.adrelid = c.oid AND "
                                              "def.adnum = a.attnum "
                 "LEFT JOIN spatial_ref_sys srs ON srs.srid = postgis_typmod_srid(a.atttypmod) "
                 "ORDER BY a.attnum",
                 OGRCARTODBEscapeLiteral(osName).c_str(),
                 OGRCARTODBEscapeLiteral(poDS->GetCurrentSchema()).c_str());
    }
    else if( poDS->HasOGRMetadataFunction() != FALSE )
    {
        osCommand.Printf( "SELECT * FROM ogr_table_metadata('%s', '%s')",
                          OGRCARTODBEscapeLiteral(poDS->GetCurrentSchema()).c_str(),
                          OGRCARTODBEscapeLiteral(osName).c_str() );
    }

    if( osCommand.size() )
    {
        if( !poDS->IsAuthenticatedConnection() && poDS->HasOGRMetadataFunction() < 0 )
            CPLPushErrorHandler(CPLQuietErrorHandler);
        OGRLayer* poLyr = poDS->ExecuteSQLInternal(osCommand);
        if( !poDS->IsAuthenticatedConnection() && poDS->HasOGRMetadataFunction() < 0 )
        {
            CPLPopErrorHandler();
            if( poLyr == NULL )
            {
                CPLDebug("CARTODB", "ogr_table_metadata(text, text) not available");
                CPLErrorReset();
            }
            else if( poLyr->GetLayerDefn()->GetFieldCount() != 12 )
            {
                CPLDebug("CARTODB", "ogr_table_metadata(text, text) has unexpected column count");
                poDS->ReleaseResultSet(poLyr);
                poLyr = NULL;
            }
            poDS->SetOGRMetadataFunction(poLyr != NULL);
        }
        if( poLyr )
        {
            OGRFeature* poFeat;
            while( (poFeat = poLyr->GetNextFeature()) != NULL )
            {
                if( poFeatureDefn == NULL )
                {
                    // We could do that outside of the while() loop, but
                    // by doing that here, we are somewhat robust to
                    // ogr_table_metadata() returning suddenly an empty result set
                    // for example if CDB_UserTables() no longer works
                    poFeatureDefn = new OGRFeatureDefn(osName);
                    poFeatureDefn->Reference();
                    poFeatureDefn->SetGeomType(wkbNone);
                }

                const char* pszAttname = poFeat->GetFieldAsString("attname");
                const char* pszType = poFeat->GetFieldAsString("typname");
                int nWidth = poFeat->GetFieldAsInteger("attlen");
                const char* pszFormatType = poFeat->GetFieldAsString("format_type");
                int bNotNull = poFeat->GetFieldAsInteger("attnotnull");
                int bIsPrimary = poFeat->GetFieldAsInteger("indisprimary");
                int iDefaultExpr = poLyr->GetLayerDefn()->GetFieldIndex("defaultexpr");
                const char* pszDefault = (iDefaultExpr >= 0 && poFeat->IsFieldSet(iDefaultExpr)) ?
                            poFeat->GetFieldAsString(iDefaultExpr) : NULL;

                if( bIsPrimary &&
                    (EQUAL(pszType, "int2") ||
                     EQUAL(pszType, "int4") ||
                     EQUAL(pszType, "int8") ||
                     EQUAL(pszType, "serial") ||
                     EQUAL(pszType, "bigserial")) )
                {
                    osFIDColName = pszAttname;
                }
                else if( strcmp(pszAttname, "created_at") == 0 ||
                         strcmp(pszAttname, "updated_at") == 0 ||
                         strcmp(pszAttname, "the_geom_webmercator") == 0)
                {
                    /* ignored */
                }
                else
                {
                    if( EQUAL(pszType,"geometry") )
                    {
                        int nDim = poFeat->GetFieldAsInteger("dim");
                        int nSRID = poFeat->GetFieldAsInteger("srid");
                        const char* pszGeomType = poFeat->GetFieldAsString("geomtyp");
                        const char* pszSRText = (poFeat->IsFieldSet(
                            poLyr->GetLayerDefn()->GetFieldIndex("srtext"))) ?
                                    poFeat->GetFieldAsString("srtext") : NULL;
                        OGRwkbGeometryType eType = OGRFromOGCGeomType(pszGeomType);
                        if( nDim == 3 )
                            eType = wkbSetZ(eType);
                        OGRCartoDBGeomFieldDefn *poFieldDefn =
                            new OGRCartoDBGeomFieldDefn(pszAttname, eType);
                        if( bNotNull )
                            poFieldDefn->SetNullable(FALSE);
                        OGRSpatialReference* poSRS = NULL;
                        if( pszSRText != NULL )
                        {
                            poSRS = new OGRSpatialReference();
                            char* pszTmp = (char* )pszSRText;
                            if( poSRS->importFromWkt(&pszTmp) != OGRERR_NONE )
                            {
                                delete poSRS;
                                poSRS = NULL;
                            }
                            if( poSRS != NULL )
                            {
                                poFieldDefn->SetSpatialRef(poSRS);
                                poSRS->Release();
                            }
                        }
                        poFieldDefn->nSRID = nSRID;
                        poFeatureDefn->AddGeomFieldDefn(poFieldDefn, FALSE);
                    }
                    else
                    {
                        OGRFieldDefn oField(pszAttname, OFTString);
                        if( bNotNull )
                            oField.SetNullable(FALSE);
                        OGRPGCommonLayerSetType(oField, pszType, pszFormatType, nWidth);
                        if( pszDefault )
                            OGRPGCommonLayerNormalizeDefault(&oField, pszDefault);

                        poFeatureDefn->AddFieldDefn( &oField );
                    }
                }
                delete poFeat;
            }

            poDS->ReleaseResultSet(poLyr);
        }
    }

    if( poFeatureDefn == NULL )
    {
        osBaseSQL.Printf("SELECT * FROM %s", OGRCARTODBEscapeIdentifier(osName).c_str());
        EstablishLayerDefn(osName, NULL);
        osBaseSQL = "";
    }

    if( osFIDColName.size() > 0 )
    {
        osBaseSQL = "SELECT ";
        osBaseSQL += OGRCARTODBEscapeIdentifier(osFIDColName);
    }
    for(int i=0; i<poFeatureDefn->GetGeomFieldCount(); i++)
    {
        if( osBaseSQL.size() == 0 )
            osBaseSQL = "SELECT ";
        else
            osBaseSQL += ", ";
        osBaseSQL += OGRCARTODBEscapeIdentifier(poFeatureDefn->GetGeomFieldDefn(i)->GetNameRef());
    }
    for(int i=0; i<poFeatureDefn->GetFieldCount(); i++)
    {
        if( osBaseSQL.size() == 0 )
            osBaseSQL = "SELECT ";
        else
            osBaseSQL += ", ";
        osBaseSQL += OGRCARTODBEscapeIdentifier(poFeatureDefn->GetFieldDefn(i)->GetNameRef());
    }
    if( osBaseSQL.size() == 0 )
        osBaseSQL = "SELECT *";
    osBaseSQL += " FROM ";
    osBaseSQL += OGRCARTODBEscapeIdentifier(osName);

    osSELECTWithoutWHERE = osBaseSQL;

    return poFeatureDefn;
}
Example #28
0
feature_ptr ogr_index_featureset<filterT>::next()
{
    while (itr_ != ids_.end())
    {
        int pos = *itr_++;
        layer_.SetNextByIndex (pos);

        OGRFeature *poFeature = layer_.GetNextFeature();
        if (poFeature == nullptr)
        {
            return feature_ptr();
        }

        // ogr feature ids start at 0, so add one to stay
        // consistent with other mapnik datasources that start at 1
        mapnik::value_integer feature_id = (poFeature->GetFID() + 1);
        feature_ptr feature(feature_factory::create(ctx_,feature_id));

        OGRGeometry* geom=poFeature->GetGeometryRef();
        if (geom && !geom->IsEmpty())
        {
            geom->getEnvelope(&feature_envelope_);
            if (!filter_.pass(mapnik::box2d<double>(feature_envelope_.MinX,feature_envelope_.MinY,
                                            feature_envelope_.MaxX,feature_envelope_.MaxY))) continue;
            feature->set_geometry(std::move(ogr_converter::convert_geometry(geom)));
        }
        else
        {
            MAPNIK_LOG_DEBUG(ogr) << "ogr_index_featureset: Feature with null geometry="
                << poFeature->GetFID();
            OGRFeature::DestroyFeature( poFeature );
            continue;
        }

        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:
            {
                feature->put<mapnik::value_integer>(fld_name,poFeature->GetFieldAsInteger (i));
                break;
            }

            case OFTReal:
            {
                feature->put(fld_name,poFeature->GetFieldAsDouble (i));
                break;
            }

            case OFTString:
            case OFTWideString:     // deprecated !
            {
                feature->put(fld_name,tr_->transcode(poFeature->GetFieldAsString (i)));
                break;
            }

            case OFTIntegerList:
            case OFTRealList:
            case OFTStringList:
            case OFTWideStringList: // deprecated !
            {
                MAPNIK_LOG_WARN(ogr) << "ogr_index_featureset: Unhandled type_oid=" << type_oid;
                break;
            }

            case OFTBinary:
            {
                MAPNIK_LOG_WARN(ogr) << "ogr_index_featureset: Unhandled type_oid=" << type_oid;
                //feature->put(name,feat->GetFieldAsBinary (i, size));
                break;
            }

            case OFTDate:
            case OFTTime:
            case OFTDateTime:       // unhandled !
            {
                MAPNIK_LOG_WARN(ogr) << "ogr_index_featureset: Unhandled type_oid=" << type_oid;
                break;
            }
            }
        }
        OGRFeature::DestroyFeature( poFeature );
        return feature;
    }

    return feature_ptr();
}
void WaterDemandModel::run()
{
	station_ids = std::set<int>();
	rainfalls = std::map<int, std::vector<double> >();
	evaotranspirations = std::map<int, std::vector<double> >();

	stormwater_runoff = std::map<int, std::vector<double> >();
	non_potable_demand = std::map<int, std::vector<double> >();
	potable_demand = std::map<int, std::vector<double> >();
	outdoor_demand = std::map<int, std::vector<double> >();
	grey_water = std::map<int, std::vector<double> >();
	black_water = std::map<int, std::vector<double> >();

	if (!initmodel())
		return;


	// init rain
	if (this->from_rain_station)
		initRain();

	// Calculate outdoor demand for standard unit (100m2 roof, 100m2 garden, 1 person)
	double imp_fraction = 0.2;
	calculateRunoffAndDemand(500, imp_fraction, 0.8, 1);


	if (this->to_rain_station) {
		this->station.resetReading();
		OGRFeature * st;
		while (st = station.getNextFeature()) {
			DM::DMFeature::SetDoubleList( st, "potable_demand_daily", this->mutiplyVector(this->potable_demand[st->GetFID()], 1));
			DM::DMFeature::SetDoubleList( st, "non_potable_demand_daily", this->mutiplyVector(this->non_potable_demand[st->GetFID()], 1));
			DM::DMFeature::SetDoubleList( st, "outdoor_demand_daily", this->mutiplyVector(this->outdoor_demand[st->GetFID()], 1./400.)); //Unit Area
			DM::DMFeature::SetDoubleList( st, "run_off_roof_daily", this->mutiplyVector(this->stormwater_runoff[st->GetFID()], 1./100.)); //Unit area
			DM::DMFeature::SetDoubleList( st, "grey_water_daily", this->mutiplyVector(this->grey_water[st->GetFID()], 1));
			DM::DMFeature::SetDoubleList( st, "black_water_daily", this->mutiplyVector(this->black_water[st->GetFID()], 1));
		}
		return;
	}
	int counter = 0;
	OGRFeature * p;
	this->parcels.resetReading();
	while(p = this->parcels.getNextFeature()) {
		counter++;
		double persons = p->GetFieldAsDouble("persons");
		double garden_area = p->GetFieldAsDouble("garden_area");
		double roof_area = p->GetFieldAsDouble("roof_area");

		int station_id = -1;
		if (this->from_rain_station)
			station_id= p->GetFieldAsInteger("station_id");

		DM::DMFeature::SetDoubleList( p, "potable_demand_daily", this->mutiplyVector(this->potable_demand[station_id], persons));
		DM::DMFeature::SetDoubleList( p, "non_potable_demand_daily", this->mutiplyVector(this->non_potable_demand[station_id], persons));
		DM::DMFeature::SetDoubleList( p, "outdoor_demand_daily", this->mutiplyVector(this->outdoor_demand[station_id], garden_area/400.)); //Unit Area
		DM::DMFeature::SetDoubleList( p, "run_off_roof_daily", this->mutiplyVector(this->stormwater_runoff[station_id], roof_area/100.)); //Unit area
		DM::DMFeature::SetDoubleList( p, "grey_water_daily", this->mutiplyVector(this->grey_water[station_id], 1));
		DM::DMFeature::SetDoubleList( p, "black_water_daily", this->mutiplyVector(this->black_water[station_id], 1));
		if (counter % 1000 == 0){
			this->parcels.syncAlteredFeatures();
			this->parcels.setNextByIndex(counter);
		}

	}
}
Example #30
0
SEXP ogrReadColumn(OGRLayer *poLayer, SEXP FIDs, int iField, int int64, int ENC_DEBUG) {
    // read feature data and return something according to the type
    OGRFeatureDefn *poDefn;
    OGRFieldDefn *poField;
    OGRFeature *poFeature;
    int iRow,nRows;
    SEXP ans = R_NilValue;

    nRows=length(FIDs);
    // get field data from layer
    installErrorHandler();
    poDefn = poLayer->GetLayerDefn();
    poField = poDefn->GetFieldDefn(iField);
    uninstallErrorHandlerAndTriggerError();
    if(poField == NULL) {
        error("Error getting field %d ",iField);
    }
    // allocate an object for the result depending on the feature type:
    installErrorHandler();
    switch(poField->GetType()) {
    case OFTInteger:
        PROTECT(ans=allocVector(INTSXP,nRows));
        break;
#ifdef GDALV2
    case OFTInteger64:
        if (int64 ==3) {
            PROTECT(ans=allocVector(STRSXP,nRows));
        } else {
            PROTECT(ans=allocVector(INTSXP,nRows));
        }
        break;
#endif
    case OFTReal:
        PROTECT(ans=allocVector(REALSXP,nRows));
        break;
    case OFTString:
        PROTECT(ans=allocVector(STRSXP,nRows));
        break;
    case OFTDate:
        PROTECT(ans=allocVector(STRSXP,nRows));
        break;
    case OFTDateTime:
        PROTECT(ans=allocVector(STRSXP,nRows));
        break;
    case OFTTime:
        PROTECT(ans=allocVector(STRSXP,nRows));
        break;
    default:
        const char *desc = poField->GetFieldTypeName(poField->GetType());
        uninstallErrorHandlerAndTriggerError();
        error("unsupported field type: %s", desc);
        break;
    }
    uninstallErrorHandlerAndTriggerError();

    // now go over each row and retrieve data. iRow is an index in a
    // vector of FIDs
    /*#ifndef EJP
        installErrorHandler();
        for(iRow=0;iRow<nRows;iRow++){
          poFeature=poLayer->GetFeature(INTEGER(FIDs)[iRow]);
          if(poFeature == NULL){
    	error("Error getting feature FID: %d",(INTEGER(FIDs)[iRow]));
          }
        }
        uninstallErrorHandlerAndTriggerError();
    #else*/
    // EJP, changed into:
    installErrorHandler();
    poLayer->ResetReading();
    iRow = 0;
    while((poFeature = poLayer->GetNextFeature()) != NULL) {
//#endif
        // now get the value using the right type:
        switch(poField->GetType()) {
        case OFTInteger:
            if (poFeature->IsFieldSet(iField))
                INTEGER(ans)[iRow]=poFeature->GetFieldAsInteger(iField);
            else INTEGER(ans)[iRow]=NA_INTEGER;
            break;
#ifdef GDALV2
        case OFTInteger64:
            if (poFeature->IsFieldSet(iField)) {
                if (int64 == 3) {
                    SET_STRING_ELT(ans, iRow,
                                   mkChar(poFeature->GetFieldAsString(iField)));
                } else {
                    GIntBig nVal64 = poFeature->GetFieldAsInteger64(iField);
                    int nVal = (nVal64 > INT_MAX) ? INT_MAX :
                               (nVal64 < INT_MIN) ? INT_MIN : (int) nVal64;
                    INTEGER(ans)[iRow]=nVal;
                    if (((GIntBig)nVal != nVal64) && int64 == 2) {
                        warning("Integer64 value clamped: feature %d", iRow);
                    }
                }
            } else {
                if (int64 == 3) {
                    SET_STRING_ELT(ans, iRow, NA_STRING);
                } else {
                    INTEGER(ans)[iRow]=NA_INTEGER;
                }
            }
            break;
#endif
        case OFTReal:
            if (poFeature->IsFieldSet(iField))
                REAL(ans)[iRow]=poFeature->GetFieldAsDouble(iField);
            else REAL(ans)[iRow]=NA_REAL;
            break;
        case OFTString:
// ENC
            char str[4096];
            size_t stln;
            if (poFeature->IsFieldSet(iField)) {
                stln = CPLStrnlen(poFeature->GetFieldAsString(iField), 4096);
                CPLStrlcpy(str, (const char *) poFeature->GetFieldAsString(iField),
                           4096);
                SET_STRING_ELT(ans, iRow, mkChar(str));
            } else SET_STRING_ELT(ans, iRow, NA_STRING);
            if (ENC_DEBUG) {
                Rprintf("iField: %d, iRow: %d stln %u Enc %s ", iField,
                        iRow, stln, CPLIsUTF8(str, (int) stln)?"UTF-8":"other");
                for (int si=0; si < (int) stln; si++)
                    Rprintf("%x ", (unsigned char) str[si]);
                Rprintf("\n");
            } /* FIXME */
            break;
        case OFTDate:
            if (poFeature->IsFieldSet(iField))
                SET_STRING_ELT(ans,iRow,mkChar(poFeature->GetFieldAsString(iField)));
            else SET_STRING_ELT(ans, iRow, NA_STRING);
            break;
        case OFTDateTime:
            if (poFeature->IsFieldSet(iField))
                SET_STRING_ELT(ans,iRow,mkChar(poFeature->GetFieldAsString(iField)));
            else SET_STRING_ELT(ans, iRow, NA_STRING);
            break;
        case OFTTime:
            if (poFeature->IsFieldSet(iField))
                SET_STRING_ELT(ans,iRow,mkChar(poFeature->GetFieldAsString(iField)));
            else SET_STRING_ELT(ans, iRow, NA_STRING);
            break;

        default:
            OGRFeature::DestroyFeature( poFeature );
//        delete poFeature;
            uninstallErrorHandlerAndTriggerError();
            error("Unsupported field type. should have been caught before");
        }
        OGRFeature::DestroyFeature( poFeature );
//      delete poFeature;
//#ifdef EJP
        // according to tutorial: OGRFeature::DestroyFeature(poFeature);
        // see comment FW in OGR tutorial: We could just "delete" it,
        // but this can cause problems in windows builds where the GDAL DLL
        // has a different "heap" from the main program. To be on the safe
        // side we use a GDAL function to delete the feature.
        iRow++;
//#endif
    }
    uninstallErrorHandlerAndTriggerError();
    UNPROTECT(1);
    return(ans);
}