Beispiel #1
0
// Return a OGR_G_ConvexHull based on the bounds in a specified projection.
OGRGeometryH
simplet_bounds_to_ogr(simplet_bounds_t *bounds, OGRSpatialReferenceH proj) {
  OGRGeometryH tmpLine;
  if(!(tmpLine = OGR_G_CreateGeometry(wkbLineString)))
    return NULL;

  // Add all the points defining the bounds to the geometry
  OGR_G_AddPoint_2D(tmpLine, bounds->nw.x, bounds->nw.y);
  OGR_G_AddPoint_2D(tmpLine, bounds->se.x, bounds->se.y);
  OGR_G_AddPoint_2D(tmpLine, bounds->nw.x, bounds->se.y);
  OGR_G_AddPoint_2D(tmpLine, bounds->se.x, bounds->nw.y);
  OGRGeometryH tmpPoint = OGR_G_ForceToMultiPoint(tmpLine);
  // Calculate the Convex Hull
  OGRGeometryH ogrBounds;
  if(!(ogrBounds = OGR_G_ConvexHull(tmpPoint))){
    OGR_G_DestroyGeometry(tmpLine);
    return NULL;
  }

  // And assign the projection.
  OGR_G_AssignSpatialReference(ogrBounds, proj);
  OGR_G_DestroyGeometry(tmpPoint);

  return ogrBounds;
}
Beispiel #2
0
// Create a bounds from the Convex Hull of an OGR Geometry.
simplet_bounds_t*
simplet_bounds_from_ogr(OGRGeometryH geom){
  OGRGeometryH hull;

  // Grab the Convex Hull
  if(!(hull = OGR_G_ConvexHull(geom)))
    return NULL;

  // Create the bounds.
  simplet_bounds_t *bounds;
  if(!(bounds = simplet_bounds_new())){
    OGR_G_DestroyGeometry(hull);
    return NULL;
  }

  // Extend the bounds by adding the points from the Convex Hull.
  double x, y;
  for(int i = 0; i < OGR_G_GetGeometryCount(hull); i++){
    OGRGeometryH subgeom = OGR_G_GetGeometryRef(hull, i);
    if(subgeom == NULL)
      continue;
    for(int j = 0; j < OGR_G_GetPointCount(subgeom); j++){
      OGR_G_GetPoint(subgeom, j, &x, &y, NULL);
      simplet_bounds_extend(bounds, x, y);
    }
  }

  OGR_G_DestroyGeometry(hull);
  return bounds;
}
Beispiel #3
0
/**
 * \brief Convenience function to check if a geometry is contained in a OGR
 *        datasource for a given layer.
 *
 * The passed geometry is a wkt representation of a geometry of type GeomType.
 * pszFile is opened, and the passed geometry is queried against all
 * geometries in pszLayer.  If the passed geometry is contained in *any* of the
 * geomtries in the layer, TRUE is returned.  FALSE is returned otherwise,
 * including errors.  The SRS of all geometries is assumed to be the same.
 *
 * \param pszWkt Well-known text representation of a geometry.
 * \param pszFile File to open
 * \param pszLayer Layer to extract geometry from, if NULL, use layer 0.
 * \return TRUE if pszWkt is contained in any geometry in pszLayer, FALSE
 *         otherwise, include errors
 */
int NinjaOGRContain(const char *pszWkt, const char *pszFile,
                    const char *pszLayer)
{
    int bContains = FALSE;
    if( pszWkt == NULL || pszFile == NULL )
    {
        return FALSE;
    }
    CPLDebug( "WINDNINJA", "Checking for containment of %s in %s:%s",
              pszWkt, pszFile, pszLayer ? pszLayer : "" );
    OGRGeometryH hTestGeometry = NULL;
    int err = OGR_G_CreateFromWkt( (char**)&pszWkt, NULL, &hTestGeometry );
    if( hTestGeometry == NULL || err != CE_None )
    {
        return FALSE;
    }
    OGRDataSourceH hDS = OGROpen( pszFile, 0, NULL );
    if( hDS == NULL )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "Failed to open datasource: %s", pszFile );
        OGR_G_DestroyGeometry( hTestGeometry );
        bContains = FALSE;
        return bContains;
    }
    OGRLayerH hLayer;
    if( pszLayer == NULL )
    {
        hLayer = OGR_DS_GetLayer( hDS, 0 );
    }
    else
    {
        hLayer = OGR_DS_GetLayerByName( hDS, pszLayer );
    }
    OGRFeatureH hFeature;
    if( hLayer != NULL )
    {
        OGRGeometryH hGeometry;
        OGR_L_ResetReading( hLayer );
        while( ( hFeature = OGR_L_GetNextFeature( hLayer ) ) != NULL )
        {
            hGeometry = OGR_F_GetGeometryRef( hFeature );
            if( OGR_G_Contains( hGeometry, hTestGeometry ) )
            {
                bContains = TRUE;
                OGR_F_Destroy( hFeature );
                break;
            }
            OGR_F_Destroy( hFeature );
        }
    }
    OGR_G_DestroyGeometry( hTestGeometry );
    OGR_DS_Destroy( hDS );
    return bContains;
}
Beispiel #4
0
void Polygon::update(const std::string& wkt_or_json, SpatialReference ref)
{
    bool isJson = wkt_or_json.find("{") != wkt_or_json.npos ||
                  wkt_or_json.find("}") != wkt_or_json.npos;

    if (!isJson)
    {
        m_geom = GEOSGeomFromWKT_r(m_ctx, wkt_or_json.c_str());
        if (!m_geom)
            throw pdal_error("Unable to create geometry from input WKT");
    }
    else
    {
        // Assume it is GeoJSON and try constructing from that
        OGRGeometryH json = OGR_G_CreateGeometryFromJson(wkt_or_json.c_str());

        if (!json)
            throw pdal_error("Unable to create geometry from "
                "input GeoJSON");

        char* gdal_wkt(0);
        OGRErr err = OGR_G_ExportToWkt(json, &gdal_wkt);
        m_geom = GEOSGeomFromWKT_r(m_ctx, gdal_wkt);
        //ABELL - Why should this ever throw?  Is it worth catching if
        //  we don't know why?
        if (!m_geom)
            throw pdal_error("Unable to create GEOS geometry from OGR WKT!");
        OGRFree(gdal_wkt);
        OGR_G_DestroyGeometry(json);
    }
    prepare();
}
Beispiel #5
0
    void object::test<11>()
    {
        char* wkt1 = "POINT(10 20)";
        err_ = OGR_G_CreateFromWkt(&wkt1, NULL, &g1_);
        ensure_equals("Can't import geometry from WKT", OGRERR_NONE, err_);
        ensure("Can't create geometry", NULL != g1_);

        char* wkt2 = "POINT(30 20)";
        err_ = OGR_G_CreateFromWkt(&wkt2, NULL, &g2_);
        ensure_equals("Can't import geometry from WKT", OGRERR_NONE, err_);
        ensure("Can't create geometry", NULL != g2_);

        g3_ = OGR_G_Union(g1_, g2_);
        ensure("OGR_G_Union failed with NULL", NULL != g3_);

        OGRGeometryH expect = NULL;
        char* wktExpect = "MULTIPOINT (10 20,30 20)";
        err_ = OGR_G_CreateFromWkt(&wktExpect, NULL, &expect);
        ensure_equals("Can't import geometry from WKT", OGRERR_NONE, err_);
        ensure("Can't create geometry", NULL != expect);

        // Compare operation result against expected geometry
        ensure_equal_geometries(g3_, expect, 0.0001);

        OGR_G_DestroyGeometry(expect);
    }
Beispiel #6
0
void OGR::writeDensity(hexer::HexGrid *grid)
{
    int counter(0);
    for (hexer::HexIter iter = grid->hexBegin(); iter != grid->hexEnd(); ++iter)
    {

        hexer::HexInfo hi = *iter;
        OGRGeometryH polygon = collectHexagon(hi, grid);
        OGRFeatureH hFeature;

        hFeature = OGR_F_Create(OGR_L_GetLayerDefn(m_layer));
        OGR_F_SetFieldInteger( hFeature, OGR_F_GetFieldIndex(hFeature, "ID"),
            counter);
        OGR_F_SetFieldInteger( hFeature, OGR_F_GetFieldIndex(hFeature, "COUNT"),
            hi.m_density);

        OGR_F_SetGeometry(hFeature, polygon);
        OGR_G_DestroyGeometry(polygon);

        if( OGR_L_CreateFeature( m_layer, hFeature ) != OGRERR_NONE )
        {
            std::ostringstream oss;
            oss << "Unable to create feature for multipolygon with error '"
                << CPLGetLastErrorMsg() << "'";
            throw pdal::pdal_error(oss.str());
        }
        OGR_F_Destroy( hFeature );
        counter++;
    }
}
Beispiel #7
0
    void object::test<14>()
    {
        char* wkt1 = "POLYGON((0 0, 10 10, 10 0, 0 0))";
        err_ = OGR_G_CreateFromWkt(&wkt1, NULL, &g1_);
        ensure_equals("Can't import geometry from WKT", OGRERR_NONE, err_);
        ensure("Can't create geometry", NULL != g1_);

        char* wkt2 = "POLYGON((0 0, 0 10, 10 0, 0 0))";
        err_ = OGR_G_CreateFromWkt(&wkt2, NULL, &g2_);
        ensure_equals("Can't import geometry from WKT", OGRERR_NONE, err_);
        ensure("Can't create geometry", NULL != g2_);

        g3_ = OGR_G_SymmetricDifference(g1_, g2_);
        ensure("OGR_G_SymmetricDifference failed with NULL", NULL != g3_);

        OGRGeometryH expect = NULL;
        char* wktExpect = "MULTIPOLYGON (((5 5,0 0,0 10,5 5)),((5 5,10 10,10 0,5 5)))";
        err_ = OGR_G_CreateFromWkt(&wktExpect, NULL, &expect);
        ensure_equals("Can't import geometry from WKT", OGRERR_NONE, err_);
        ensure("Can't create geometry", NULL != expect);

        // Compare operation result against expected geometry
        ensure_equal_geometries(g3_, expect, 0.0001);

        OGR_G_DestroyGeometry(expect);
    }
QgsOgrFeatureIterator::QgsOgrFeatureIterator( QgsOgrProvider* p, const QgsFeatureRequest& request )
    : QgsAbstractFeatureIterator( request ), P( p )
{
  // make sure that only one iterator is active
  if ( P->mActiveIterator )
    P->mActiveIterator->close();
  P->mActiveIterator = this;

  // set the selection rectangle pointer to 0
  mSelectionRectangle = 0;

  mFeatureFetched = false;

  ensureRelevantFields();

  // spatial query to select features
  if ( mRequest.filterType() == QgsFeatureRequest::FilterRect )
  {
    OGRGeometryH filter = 0;
    QString wktExtent = QString( "POLYGON((%1))" ).arg( mRequest.filterRect().asPolygon() );
    QByteArray ba = wktExtent.toAscii();
    const char *wktText = ba;

    if ( mRequest.flags() & QgsFeatureRequest::ExactIntersect )
    {
      // store the selection rectangle for use in filtering features during
      // an identify and display attributes
      if ( mSelectionRectangle )
        OGR_G_DestroyGeometry( mSelectionRectangle );

      OGR_G_CreateFromWkt(( char ** )&wktText, NULL, &mSelectionRectangle );
      wktText = ba;
    }

    OGR_G_CreateFromWkt(( char ** )&wktText, NULL, &filter );
    QgsDebugMsg( "Setting spatial filter using " + wktExtent );
    OGR_L_SetSpatialFilter( P->ogrLayer, filter );
    OGR_G_DestroyGeometry( filter );
  }
  else
  {
    OGR_L_SetSpatialFilter( P->ogrLayer, 0 );
  }

  //start with first feature
  rewind();
}
QgsOgrFeatureIterator::QgsOgrFeatureIterator( QgsOgrFeatureSource* source, bool ownSource, const QgsFeatureRequest& request )
    : QgsAbstractFeatureIteratorFromSource<QgsOgrFeatureSource>( source, ownSource, request )
    , ogrDataSource( 0 )
    , ogrLayer( 0 )
    , mSubsetStringSet( false )
    , mGeometrySimplifier( NULL )
{
  mFeatureFetched = false;

  ogrDataSource = OGROpen( TO8F( mSource->mFilePath ), false, NULL );

  if ( mSource->mLayerName.isNull() )
  {
    ogrLayer = OGR_DS_GetLayer( ogrDataSource, mSource->mLayerIndex );
  }
  else
  {
    ogrLayer = OGR_DS_GetLayerByName( ogrDataSource, TO8( mSource->mLayerName ) );
  }

  if ( !mSource->mSubsetString.isEmpty() )
  {
    ogrLayer = QgsOgrUtils::setSubsetString( ogrLayer, ogrDataSource, mSource->mEncoding, mSource->mSubsetString );
    mSubsetStringSet = true;
  }

  mFetchGeometry = ( mRequest.filterType() == QgsFeatureRequest::FilterRect ) || !( mRequest.flags() & QgsFeatureRequest::NoGeometry );
  QgsAttributeList attrs = ( mRequest.flags() & QgsFeatureRequest::SubsetOfAttributes ) ? mRequest.subsetOfAttributes() : mSource->mFields.allAttributesList();

  // make sure we fetch just relevant fields
  // unless it's a VRT data source filtered by geometry as we don't know which
  // attributes make up the geometry and OGR won't fetch them to evaluate the
  // filter if we choose to ignore them (fixes #11223)
  if (( mSource->mDriverName != "VRT" && mSource->mDriverName != "OGR_VRT" ) || mRequest.filterType() != QgsFeatureRequest::FilterRect )
  {
    QgsOgrUtils::setRelevantFields( ogrLayer, mSource->mFields.count(), mFetchGeometry, attrs );
  }

  // spatial query to select features
  if ( mRequest.filterType() == QgsFeatureRequest::FilterRect )
  {
    OGRGeometryH filter = 0;
    QString wktExtent = QString( "POLYGON((%1))" ).arg( mRequest.filterRect().asPolygon() );
    QByteArray ba = wktExtent.toAscii();
    const char *wktText = ba;

    OGR_G_CreateFromWkt(( char ** )&wktText, NULL, &filter );
    QgsDebugMsg( "Setting spatial filter using " + wktExtent );
    OGR_L_SetSpatialFilter( ogrLayer, filter );
    OGR_G_DestroyGeometry( filter );
  }
  else
  {
    OGR_L_SetSpatialFilter( ogrLayer, 0 );
  }

  //start with first feature
  rewind();
}
Beispiel #10
0
static void
geometry_destroy(ErlNifEnv *env, void *obj)
{
    // If env is NULL then is GeometryRef else is Geometry
    // GeometryRef should not be freed by the application
    EnvGeometry_t **geometry = (EnvGeometry_t**)obj;
    if ((**geometry).env == NULL) {
        OGR_G_DestroyGeometry((**geometry).obj);
    } else {
        enif_free_env((**geometry).env);
    }
    enif_free(*geometry);
}
QgsOgrFeatureIterator::QgsOgrFeatureIterator( QgsOgrProvider* p, const QgsFeatureRequest& request )
    : QgsAbstractFeatureIterator( request )
    , P( p )
    , ogrDataSource( 0 )
    , ogrLayer( 0 )
    , mSubsetStringSet( false )
    , mGeometrySimplifier( NULL )
{
  mFeatureFetched = false;

  ogrDataSource = OGROpen( TO8F( P->filePath() ), false, NULL );

  if ( P->layerName().isNull() )
  {
    ogrLayer = OGR_DS_GetLayer( ogrDataSource, P->layerIndex() );
  }
  else
  {
    ogrLayer = OGR_DS_GetLayerByName( ogrDataSource, TO8( p->layerName() ) );
  }

  if ( !P->subsetString().isEmpty() )
  {
    ogrLayer = P->setSubsetString( ogrLayer, ogrDataSource );
    mSubsetStringSet = true;
  }

  ensureRelevantFields();

  // spatial query to select features
  if ( mRequest.filterType() == QgsFeatureRequest::FilterRect )
  {
    OGRGeometryH filter = 0;
    QString wktExtent = QString( "POLYGON((%1))" ).arg( mRequest.filterRect().asPolygon() );
    QByteArray ba = wktExtent.toAscii();
    const char *wktText = ba;

    OGR_G_CreateFromWkt(( char ** )&wktText, NULL, &filter );
    QgsDebugMsg( "Setting spatial filter using " + wktExtent );
    OGR_L_SetSpatialFilter( ogrLayer, filter );
    OGR_G_DestroyGeometry( filter );
  }
  else
  {
    OGR_L_SetSpatialFilter( ogrLayer, 0 );
  }

  //start with first feature
  rewind();
}
Beispiel #12
0
bool Writer::IsValidGeometryWKT(std::string const& input) const
{
#ifdef PDAL_HAVE_GDAL

    OGRGeometryH g;

    char* wkt = const_cast<char*>(input.c_str());
    OGRErr e = OGR_G_CreateFromWkt(&wkt, NULL, &g);
    OGR_G_DestroyGeometry(g);
    if (e != 0) return false;

    return true;
#else

    throw pdal_error("GDAL support not available for WKT validation");
#endif
}
bool QgsOgrFeatureIterator::close()
{
  if ( mClosed )
    return false;

  if ( mSelectionRectangle )
  {
    OGR_G_DestroyGeometry( mSelectionRectangle );
    mSelectionRectangle = 0;
  }

  // tell provider that this iterator is not active anymore
  P->mActiveIterator = 0;

  mClosed = true;
  return true;
}
Beispiel #14
0
    void object::test<3>()
    {
        ensure("SRS UTM handle is NULL", NULL != srs_utm_);
        ensure("SRS LL handle is NULL", NULL != srs_ll_);

        err_ = OSRSetUTM(srs_utm_, 11, TRUE);
        ensure_equals("Can't set UTM zone", err_, OGRERR_NONE);

        err_ = OSRSetWellKnownGeogCS(srs_utm_, "WGS84");
        ensure_equals("Can't set GeogCS", err_, OGRERR_NONE);

        err_ = OSRSetWellKnownGeogCS(srs_ll_, "WGS84");
        ensure_equals("Can't set GeogCS", err_, OGRERR_NONE);

        ct_ = OCTNewCoordinateTransformation(srs_ll_, srs_utm_);
        ensure("PROJ.4 missing, transforms not available", NULL != ct_);

        const char* wkt = "POINT(-117.5 32.0)";
        OGRGeometryH geom = NULL;
        err_ = OGR_G_CreateFromWkt((char**) &wkt, NULL, &geom);
        ensure_equals("Can't import geometry from WKT", OGRERR_NONE, err_);
        ensure("Can't create geometry", NULL != geom);

        err_ = OGR_G_Transform(geom, ct_);
        ensure_equals("OGR_G_Transform() failed", err_, OGRERR_NONE);

        OGRSpatialReferenceH srs = NULL;
        srs = OGR_G_GetSpatialReference(geom);
        
        char* wktSrs = NULL;
        err_ = OSRExportToPrettyWkt(srs, &wktSrs, FALSE);
        ensure("Exported SRS to WKT is NULL", NULL != wktSrs);

        std::string pretty(wktSrs);
        ensure_equals("SRS output is incorrect", pretty.substr(0, 6), std::string("PROJCS"));

        OGRFree(wktSrs);
        OGR_G_DestroyGeometry(geom);
    }
Beispiel #15
0
bool CUtils::insideInPolygons(OGRDataSourceH poDS, double x, double y)
{
	bool res = false;
	OGRGeometryH pt = OGR_G_CreateGeometry(wkbPoint);
	OGR_G_AddPoint_2D(pt, x, y);

	for(int iLayer = 0; iLayer < OGR_DS_GetLayerCount(poDS); iLayer++)	
	{
		OGRLayerH poLayer = OGR_DS_GetLayer(poDS, iLayer);
		if(poLayer!=NULL)
		{
			OGREnvelope layerBounds;
			OGR_L_GetExtent(poLayer, &layerBounds, 1);
			
			if(	(layerBounds.MinX <= x) && (layerBounds.MinY <= y) && 
				(layerBounds.MaxX >= x) && (layerBounds.MaxY >= y) )
			{
				OGR_L_ResetReading(poLayer);
				if(OGR_FD_GetGeomType( OGR_L_GetLayerDefn(poLayer) ) == wkbPolygon)
				{
					OGRFeatureH poFeat;
					while((poFeat = OGR_L_GetNextFeature(poLayer))!= NULL)
					{
						OGRGeometryH hGeom = OGR_F_GetGeometryRef(poFeat);
						if(OGR_G_Within(pt, hGeom))
						{
							res = true;
							break;
						}
					}
					if(res) { OGR_L_ResetReading(poLayer); break; }
				}
			}
		}
	}	
	OGR_G_DestroyGeometry(pt);
	return res;
}
Beispiel #16
0
    void object::test<10>()
    {
        OGRErr err = OGRERR_NONE;

        // Read feature without geometry
        std::string tmp(data_tmp_);
        tmp += SEP;
        tmp += "tpoly.shp";
        OGRDataSourceH ds = OGR_Dr_Open(drv_, tmp.c_str(), false);
        ensure("Can't open layer", NULL != ds);

        OGRLayerH lyr = OGR_DS_GetLayer(ds, 0);
        ensure("Can't get layer", NULL != lyr);

        // Set empty filter for attributes
        err = OGR_L_SetAttributeFilter(lyr, NULL);
        ensure_equals("Can't set attribute filter", OGRERR_NONE, err);

        // Set spatial filter
        const char* wkt = "LINESTRING(479505 4763195,480526 4762819)";
        OGRGeometryH filterGeom = NULL;
        err = OGR_G_CreateFromWkt((char**) &wkt, NULL, &filterGeom);
        ensure_equals("Can't create geometry from WKT", OGRERR_NONE, err);

        OGR_L_SetSpatialFilter(lyr, filterGeom);

        // Prepare tester collection
        std::vector<int> list;
        list.push_back(158);
        list.push_back(0);
       
        // Test attributes
        ensure_equal_attributes(lyr, "eas_id", list);

        OGR_G_DestroyGeometry(filterGeom);
        OGR_DS_Destroy(ds);
    }
Beispiel #17
0
    void object::test<9>()
    {
        // Open directory as a datasource
        OGRDataSourceH ds = OGR_Dr_Open(drv_, data_tmp_ .c_str(), false);
        ensure("Can't open datasource", NULL != ds);

        std::string sql("select * from tpoly where prfedea = '35043413'");
        OGRLayerH lyr = OGR_DS_ExecuteSQL(ds, sql.c_str(), NULL, NULL);
        ensure("Can't create layer from query", NULL != lyr);

        // Prepare tester collection
        std::vector<std::string> list;
        list.push_back("35043413");
       
        // Test attributes
        ensure_equal_attributes(lyr, "prfedea", list);

        // Test geometry
        const char* wkt = "POLYGON ((479750.688 4764702.000,479658.594 4764670.000,"
            "479640.094 4764721.000,479735.906 4764752.000,"
            "479750.688 4764702.000))";

        OGRGeometryH testGeom = NULL;
        OGRErr err = OGR_G_CreateFromWkt((char**) &wkt, NULL, &testGeom);
        ensure_equals("Can't create geometry from WKT", OGRERR_NONE, err);

        OGR_L_ResetReading(lyr);
        OGRFeatureH feat = OGR_L_GetNextFeature(lyr);
        ensure("Can't featch feature", NULL != feat);

        ensure_equal_geometries(OGR_F_GetGeometryRef(feat), testGeom, 0.001);

        OGR_F_Destroy(feat);
        OGR_G_DestroyGeometry(testGeom);
        OGR_DS_ReleaseResultSet(ds, lyr);
        OGR_DS_Destroy(ds);
    }
Beispiel #18
0
void OGR::writeBoundary(hexer::HexGrid *grid)
{
    OGRGeometryH multi = OGR_G_CreateGeometry(wkbMultiPolygon);

    const std::vector<hexer::Path *>& paths = grid->rootPaths();
    for (auto pi = paths.begin(); pi != paths.end(); ++pi)
    {
        OGRGeometryH polygon = OGR_G_CreateGeometry(wkbPolygon);
        collectPath(*pi, polygon);

        if( OGR_G_AddGeometryDirectly(multi, polygon ) != OGRERR_NONE )
        {
            std::ostringstream oss;
            oss << "Unable to add polygon to multipolygon with error '"
                << CPLGetLastErrorMsg() << "'";
            throw pdal::pdal_error(oss.str());
        }
    }

    OGRFeatureH hFeature;

    hFeature = OGR_F_Create(OGR_L_GetLayerDefn(m_layer));
    OGR_F_SetFieldInteger( hFeature, OGR_F_GetFieldIndex(hFeature, "ID"), 0);

    OGR_F_SetGeometry(hFeature, multi);
    OGR_G_DestroyGeometry(multi);

    if( OGR_L_CreateFeature( m_layer, hFeature ) != OGRERR_NONE )
    {
        std::ostringstream oss;
        oss << "Unable to create feature for multipolygon with error '"
            << CPLGetLastErrorMsg() << "'";
        throw pdal::pdal_error(oss.str());
    }
    OGR_F_Destroy( hFeature );
}
QgsOgrFeatureIterator::QgsOgrFeatureIterator( QgsOgrProvider* p, const QgsFeatureRequest& request )
    : QgsAbstractFeatureIterator( request ), P( p )
{
  // make sure that only one iterator is active
  if ( P->mActiveIterator )
  {
    QgsMessageLog::logMessage( QObject::tr( "Already active iterator on this provider was closed." ), QObject::tr( "OGR" ) );
    P->mActiveIterator->close();
  }
  P->mActiveIterator = this;

  mFeatureFetched = false;

  ensureRelevantFields();

  // spatial query to select features
  if ( mRequest.filterType() == QgsFeatureRequest::FilterRect )
  {
    OGRGeometryH filter = 0;
    QString wktExtent = QString( "POLYGON((%1))" ).arg( mRequest.filterRect().asPolygon() );
    QByteArray ba = wktExtent.toAscii();
    const char *wktText = ba;

    OGR_G_CreateFromWkt(( char ** )&wktText, NULL, &filter );
    QgsDebugMsg( "Setting spatial filter using " + wktExtent );
    OGR_L_SetSpatialFilter( P->ogrLayer, filter );
    OGR_G_DestroyGeometry( filter );
  }
  else
  {
    OGR_L_SetSpatialFilter( P->ogrLayer, 0 );
  }

  //start with first feature
  rewind();
}
Beispiel #20
0
std::string FetchTimeZone( double dfX, double dfY, const char *pszWkt )
{
    CPLDebug( "WINDNINJA", "Fetching timezone for  %lf,%lf", dfX, dfY );
    if( pszWkt != NULL )
    {
        OGRSpatialReference oSourceSRS, oTargetSRS;
        OGRCoordinateTransformation *poCT;

        oSourceSRS.SetWellKnownGeogCS( "WGS84" );
        oTargetSRS.importFromWkt( (char**)&pszWkt );

        poCT = OGRCreateCoordinateTransformation( &oSourceSRS, &oTargetSRS );
        if( poCT == NULL )
        {
            CPLError( CE_Failure, CPLE_AppDefined,
                      "OGR coordinate transformation failed" );
            return std::string();
        }
        if( !poCT->Transform( 1, &dfX, &dfY ) )
        {
            CPLError( CE_Failure, CPLE_AppDefined,
                      "OGR coordinate transformation failed" );
            return std::string();
        }
        OGRCoordinateTransformation::DestroyCT( poCT );
    }
    OGRGeometryH hGeometry = OGR_G_CreateGeometry( wkbPoint );
    OGR_G_SetPoint_2D( hGeometry, 0, dfX, dfY );

    OGRDataSourceH hDS;
    OGRLayerH hLayer;
    OGRFeatureH hFeature;

    std::string oTzFile = FindDataPath( "tz_world.zip" );
    oTzFile = "/vsizip/" + oTzFile + "/world/tz_world.shp";

    hDS = OGROpen( oTzFile.c_str(), 0, NULL );
    if( hDS == NULL )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "Failed to open datasource: %s", oTzFile.c_str() );
        return std::string();
    }
    hLayer = OGR_DS_GetLayer( hDS, 0 );
    OGR_L_SetSpatialFilter( hLayer, hGeometry );
    OGR_L_ResetReading( hLayer );
    int nMaxTries = 5;
    int nTries = 0;
    OGRGeometryH hBufferGeometry;
    do
    {
        if( nTries == 0 )
        {
            hBufferGeometry = OGR_G_Clone( hGeometry );
        }
        else
        {
            hBufferGeometry = OGR_G_Buffer( hGeometry, 0.2 * nTries, 30 );
        }
        OGR_L_SetSpatialFilter( hLayer, hBufferGeometry );
        hFeature = OGR_L_GetNextFeature( hLayer );
        OGR_G_DestroyGeometry( hBufferGeometry );
        nTries++;
    }
    while( hFeature == NULL && nTries < nMaxTries );
    std::string oTimeZone;
    if( hFeature == NULL )
    {
        oTimeZone = std::string();
        CPLError( CE_Failure, CPLE_AppDefined,
                  "Failed to find timezone" );
    }
    else
    {
        oTimeZone = std::string( OGR_F_GetFieldAsString( hFeature, 0 ) );
    }
    OGR_F_Destroy( hFeature );
    OGR_G_DestroyGeometry( hGeometry );
    OGR_DS_Destroy( hDS );
    return oTimeZone;
}
static CPLErr ProcessLayer(
    OGRLayerH hSrcLayer, int bSRSIsSet,
    GDALDatasetH hDstDS, std::vector<int> anBandList,
    const std::vector<double> &adfBurnValues, int b3D, int bInverse,
    const char *pszBurnAttribute, char **papszRasterizeOptions,
    GDALProgressFunc pfnProgress, void* pProgressData )

{
/* -------------------------------------------------------------------- */
/*      Checkout that SRS are the same.                                 */
/*      If -a_srs is specified, skip the test                           */
/* -------------------------------------------------------------------- */
    OGRCoordinateTransformationH hCT = NULL;
    if (!bSRSIsSet)
    {
        OGRSpatialReferenceH  hDstSRS = NULL;
        if( GDALGetProjectionRef( hDstDS ) != NULL )
        {
            char *pszProjection;

            pszProjection = (char *) GDALGetProjectionRef( hDstDS );

            hDstSRS = OSRNewSpatialReference(NULL);
            if( OSRImportFromWkt( hDstSRS, &pszProjection ) != OGRERR_NONE )
            {
                OSRDestroySpatialReference(hDstSRS);
                hDstSRS = NULL;
            }
        }

        OGRSpatialReferenceH hSrcSRS = OGR_L_GetSpatialRef(hSrcLayer);
        if( hDstSRS != NULL && hSrcSRS != NULL )
        {
            if( OSRIsSame(hSrcSRS, hDstSRS) == FALSE )
            {
                hCT = OCTNewCoordinateTransformation(hSrcSRS, hDstSRS);
                if( hCT == NULL )
                {
                    CPLError(CE_Warning, CPLE_AppDefined,
                        "The output raster dataset and the input vector layer do not have the same SRS.\n"
                        "And reprojection of input data did not work. Results might be incorrect.");
                }
            }
        }
        else if( hDstSRS != NULL && hSrcSRS == NULL )
        {
            CPLError(CE_Warning, CPLE_AppDefined,
                    "The output raster dataset has a SRS, but the input vector layer SRS is unknown.\n"
                    "Ensure input vector has the same SRS, otherwise results might be incorrect.");
        }
        else if( hDstSRS == NULL && hSrcSRS != NULL )
        {
            CPLError(CE_Warning, CPLE_AppDefined,
                    "The input vector layer has a SRS, but the output raster dataset SRS is unknown.\n"
                    "Ensure output raster dataset has the same SRS, otherwise results might be incorrect.");
        }

        if( hDstSRS != NULL )
        {
            OSRDestroySpatialReference(hDstSRS);
        }
    }

/* -------------------------------------------------------------------- */
/*      Get field index, and check.                                     */
/* -------------------------------------------------------------------- */
    int iBurnField = -1;

    if( pszBurnAttribute )
    {
        iBurnField = OGR_FD_GetFieldIndex( OGR_L_GetLayerDefn( hSrcLayer ),
                                           pszBurnAttribute );
        if( iBurnField == -1 )
        {
            CPLError(CE_Failure, CPLE_AppDefined, "Failed to find field %s on layer %s, skipping.",
                    pszBurnAttribute,
                    OGR_FD_GetName( OGR_L_GetLayerDefn( hSrcLayer ) ) );
            if( hCT != NULL )
                OCTDestroyCoordinateTransformation(hCT);
            return CE_Failure;
        }
    }

/* -------------------------------------------------------------------- */
/*      Collect the geometries from this layer, and build list of       */
/*      burn values.                                                    */
/* -------------------------------------------------------------------- */
    OGRFeatureH hFeat;
    std::vector<OGRGeometryH> ahGeometries;
    std::vector<double> adfFullBurnValues;

    OGR_L_ResetReading( hSrcLayer );

    while( (hFeat = OGR_L_GetNextFeature( hSrcLayer )) != NULL )
    {
        OGRGeometryH hGeom;

        if( OGR_F_GetGeometryRef( hFeat ) == NULL )
        {
            OGR_F_Destroy( hFeat );
            continue;
        }

        hGeom = OGR_G_Clone( OGR_F_GetGeometryRef( hFeat ) );
        if( hCT != NULL )
        {
            if( OGR_G_Transform(hGeom, hCT) != OGRERR_NONE )
            {
                OGR_F_Destroy( hFeat );
                OGR_G_DestroyGeometry(hGeom);
                continue;
            }
        }
        ahGeometries.push_back( hGeom );

        for( unsigned int iBand = 0; iBand < anBandList.size(); iBand++ )
        {
            if( adfBurnValues.size() > 0 )
                adfFullBurnValues.push_back(
                    adfBurnValues[MIN(iBand,adfBurnValues.size()-1)] );
            else if( pszBurnAttribute )
            {
                adfFullBurnValues.push_back( OGR_F_GetFieldAsDouble( hFeat, iBurnField ) );
            }
            /* I have made the 3D option exclusive to other options since it
               can be used to modify the value from "-burn value" or
               "-a attribute_name" */
            if( b3D )
            {
                // TODO: get geometry "z" value
                /* Points and Lines will have their "z" values collected at the
                   point and line levels respectively. However filled polygons
                   (GDALdllImageFilledPolygon) can use some help by getting
                   their "z" values here. */
                adfFullBurnValues.push_back( 0.0 );
            }
        }

        OGR_F_Destroy( hFeat );
    }

    if( hCT != NULL )
        OCTDestroyCoordinateTransformation(hCT);

/* -------------------------------------------------------------------- */
/*      If we are in inverse mode, we add one extra ring around the     */
/*      whole dataset to invert the concept of insideness and then      */
/*      merge everything into one geometry collection.                  */
/* -------------------------------------------------------------------- */
    if( bInverse )
    {
        if( ahGeometries.size() == 0 )
        {
            for( unsigned int iBand = 0; iBand < anBandList.size(); iBand++ )
            {
                if( adfBurnValues.size() > 0 )
                    adfFullBurnValues.push_back(
                        adfBurnValues[MIN(iBand,adfBurnValues.size()-1)] );
                else /* FIXME? Not sure what to do exactly in the else case, but we must insert a value */
                    adfFullBurnValues.push_back( 0.0 );
            }
        }

        InvertGeometries( hDstDS, ahGeometries );
    }

/* -------------------------------------------------------------------- */
/*      Perform the burn.                                               */
/* -------------------------------------------------------------------- */
    CPLErr eErr = GDALRasterizeGeometries( hDstDS, static_cast<int>(anBandList.size()), &(anBandList[0]),
                             static_cast<int>(ahGeometries.size()), &(ahGeometries[0]),
                             NULL, NULL, &(adfFullBurnValues[0]),
                             papszRasterizeOptions,
                             pfnProgress, pProgressData );

/* -------------------------------------------------------------------- */
/*      Cleanup geometries.                                             */
/* -------------------------------------------------------------------- */
    int iGeom;

    for( iGeom = static_cast<int>(ahGeometries.size())-1; iGeom >= 0; iGeom-- )
        OGR_G_DestroyGeometry( ahGeometries[iGeom] );

    return eErr;
}
Beispiel #22
0
 ~test_geos_data()
 {
     OGR_G_DestroyGeometry(g1_);
     OGR_G_DestroyGeometry(g2_);
     OGR_G_DestroyGeometry(g3_);
 }
Beispiel #23
0
/*!
  \brief Writes feature on level 1 (OGR interface)

  \param Map pointer to Map_info structure
  \param type feature type
  \param points pointer to line_pnts structure (feature geometry)
  \param cats pointer to line_cats structure (feature categories)

  \return feature offset into file
  \return -1 on error
*/
off_t V1_write_line_ogr(struct Map_info *Map, int type,
                        const struct line_pnts *points,
                        const struct line_cats *cats)
{
    int i, cat, ret;

    struct field_info *Fi;
    struct Format_info_ogr *fInfo;

    OGRGeometryH       Ogr_geometry;
    OGRFeatureH        Ogr_feature;
    OGRFeatureDefnH    Ogr_featuredefn;
    OGRwkbGeometryType Ogr_geom_type;

    if (!Map->fInfo.ogr.layer) {
        if (V2_open_new_ogr(Map, type) < 0)
            return -1;
    }

    cat = -1; /* no attributes to be written */
    if (cats->n_cats > 0) {
        /* check for attributes */
        Fi = Vect_get_dblink(Map, 0);
        if (Fi) {
            if (!Vect_cat_get(cats, Fi->number, &cat))
                G_warning(_("No category defined for layer %d"), Fi->number);
            if (cats->n_cats > 1) {
                G_warning(_("Feature has more categories, using "
                            "category %d (from layer %d)"),
                          cat, cats->field[0]);
            }
        }
    }

    fInfo = &(Map->fInfo.ogr);
    Ogr_featuredefn = OGR_L_GetLayerDefn(fInfo->layer);
    Ogr_geom_type = OGR_FD_GetGeomType(Ogr_featuredefn);

    /* determine matching OGR feature geometry type */
    /* NOTE: centroids are not supported in OGR,
     *       pseudotopo holds virtual centroids */
    /* NOTE: boundaries are not supported in OGR,
     *       pseudotopo treats polygons as boundaries */

    if (type & (GV_POINT | GV_KERNEL)) {
        if (Ogr_geom_type != wkbPoint &&
                Ogr_geom_type != wkbPoint25D) {
            G_warning(_("Feature is not a point. Skipping."));
            return -1;
        }
        Ogr_geometry = OGR_G_CreateGeometry(wkbPoint);
    }
    else if (type & GV_LINE) {
        if (Ogr_geom_type != wkbLineString &&
                Ogr_geom_type != wkbLineString25D) {
            G_warning(_("Feature is not a line. Skipping."));
            return -1;
        }
        Ogr_geometry = OGR_G_CreateGeometry(wkbLineString);
    }
    else if (type & GV_BOUNDARY) {
        if (Ogr_geom_type != wkbPolygon) {
            G_warning(_("Feature is not a polygon. Skipping."));
            return -1;
        }
        Ogr_geometry = OGR_G_CreateGeometry(wkbPolygon);
    }
    else if (type & GV_FACE) {
        if (Ogr_geom_type != wkbPolygon25D) {
            G_warning(_("Feature is not a face. Skipping."));
            return -1;
        }
        Ogr_geometry = OGR_G_CreateGeometry(wkbPolygon25D);
    }
    else {
        G_warning(_("Unsupported feature type (%d)"), type);
        return -1;
    }

    G_debug(3, "V1_write_line_ogr(): type = %d", type);

    if (Ogr_geom_type == wkbPolygon || Ogr_geom_type == wkbPolygon25D) {
        /* create exterior ring */
        OGRGeometryH Ogr_ring;
        int npoints;

        npoints = points->n_points - 1;
        Ogr_ring = OGR_G_CreateGeometry(wkbLinearRing);
        if (points->x[0] != points->x[npoints] ||
                points->y[0] != points->y[npoints] ||
                points->z[0] != points->z[npoints]) {
            G_warning(_("Boundary is not closed. Skipping."));
            return -1;
        }

        /* add points */
        for (i = 0; i < points->n_points; i++) {
            OGR_G_AddPoint(Ogr_ring, points->x[i], points->y[i],
                           points->z[i]);
        }
        OGR_G_AddGeometry(Ogr_geometry, Ogr_ring);
    }
    else {
        for (i = 0; i < points->n_points; i++) {
            OGR_G_AddPoint(Ogr_geometry, points->x[i], points->y[i],
                           points->z[i]);
        }
    }

    G_debug(4, "   n_points = %d", points->n_points);

    /* create feature & set geometry */
    Ogr_feature = OGR_F_Create(Ogr_featuredefn);
    OGR_F_SetGeometry(Ogr_feature, Ogr_geometry);

    /* write attributes */
    if (cat > -1 && fInfo->dbdriver) {
        write_attributes(fInfo->dbdriver,
                         cat, Fi, fInfo->layer, Ogr_feature);
        G_free(Fi);
    }
    /* write feature into layer */
    ret = OGR_L_CreateFeature(fInfo->layer, Ogr_feature);

    /* update offset array */
    if (fInfo->offset_num >= fInfo->offset_alloc) {
        fInfo->offset_alloc += 1000;
        fInfo->offset = (int *) G_realloc(fInfo->offset,
                                          fInfo->offset_alloc *
                                          sizeof(int));
    }
    /* how to deal with OGRNullFID ? */
    fInfo->offset[fInfo->offset_num] = (int)OGR_F_GetFID(Ogr_feature);

    /* destroy */
    OGR_G_DestroyGeometry(Ogr_geometry);
    OGR_F_Destroy(Ogr_feature);

    if (ret != OGRERR_NONE)
        return -1;

    return fInfo->offset_num++;
}
int create_grid(char *infile, char *outfile, int gridsize, char *format, char *layer) {

	OGRSFDriverH out_driver;
	OGRDataSourceH out_ds;
	OGRLayerH out_layer;
	OGRFieldDefnH field;
	OGRFeatureH feat;
	OGRGeometryH geom;
	morph *mgrid;
	int xstep, ystep, step;
	double topleftx, toplefty, weres, nsres, rot1, rot2;
	int i,j, fid, row, col;
	
	
	OGRRegisterAll();
	
	// Read the morph grid file.
	mgrid = read_grid(infile);
	if (mgrid == NULL) {
		fprintf(stderr, "Error. Unable to read input morph file '%s'.\n", infile);
		exit(1);
	}
	
	// Create the ouptut layer.
	out_driver = OGRGetDriverByName(format);
	if (out_driver == NULL) {
		fprintf(stderr, "Error. Driver for format '%s' not available.\n", format);
		exit(1);
	}
	out_ds = OGR_Dr_CreateDataSource(out_driver, outfile, NULL);
	if (out_ds == NULL) {
		fprintf(stderr, "Error. Unable to create output data source.\n");
		exit(1);
	}
	out_layer = OGR_DS_CreateLayer(out_ds, layer, NULL, wkbLineString, NULL);
	if (out_layer == NULL) {
		fprintf(stderr, "Error. Unable to create output layer.\n");
		exit(1);
	}
	
	// Add the attributes to the new layer.
	field = OGR_Fld_Create("ID", OFTInteger);
	OGR_Fld_SetWidth(field, 11);
	if (OGR_L_CreateField(out_layer, field, TRUE) != OGRERR_NONE) {
		fprintf(stderr, "Error. Creating ID attribute failed.\n");
		exit(1);
	}
	OGR_Fld_Destroy(field);
	
	field = OGR_Fld_Create("ROW", OFTInteger);
	OGR_Fld_SetWidth(field, 6);
	if (OGR_L_CreateField(out_layer, field, TRUE) != OGRERR_NONE) {
		fprintf(stderr, "Error. Creating ROW attribute failed.\n");
		exit(1);
	}
	OGR_Fld_Destroy(field);
	
	field = OGR_Fld_Create("COL", OFTInteger);
	OGR_Fld_SetWidth(field, 6);
	if (OGR_L_CreateField(out_layer, field, TRUE) != OGRERR_NONE) {
		fprintf(stderr, "Error. Creating COL attribute failed.\n");
		exit(1);
	}
	OGR_Fld_Destroy(field);
	
	// Compute the step size.
	xstep = mgrid->xsize / gridsize;
	if (xstep < 1) {
		xstep = 1;
	}
	if (xstep > (mgrid->xsize / 2)) {
		xstep = mgrid->xsize / 2;
	}
	ystep = mgrid->ysize / gridsize;
	if (ystep < 1) {
		ystep = 1;
	}
	if (ystep > (mgrid->ysize / 2)) {
		ystep = mgrid->ysize / 2;
	}
	if (xstep < ystep) {
		step = ystep;
	} else {
		step = xstep;
	}
	
	// Read the georeference
	topleftx = mgrid->georef[0];
	weres = mgrid->georef[1];
	rot1 = mgrid->georef[2];
	toplefty = mgrid->georef[3];
	rot2 = mgrid->georef[4];
	nsres = mgrid->georef[5];
	
	// Write all horizontal lines.
	fid = 1;
	row = 1;
	for (j = 0; j < mgrid->ysize; j += step) {
		// Create a new Feature with the projected coordinates.
		feat = OGR_F_Create(OGR_L_GetLayerDefn(out_layer));
		OGR_F_SetFieldInteger(feat, OGR_F_GetFieldIndex(feat, "ID"), fid);
		OGR_F_SetFieldInteger(feat, OGR_F_GetFieldIndex(feat, "ROW"), row);
		OGR_F_SetFieldInteger(feat, OGR_F_GetFieldIndex(feat, "COL"), 0);

		// Create a new geometry object.
		geom = OGR_G_CreateGeometry(wkbLineString);
		for (i = 0; i < mgrid->xsize; i++) {
			OGR_G_SetPoint_2D(
							  geom, 
							  i, 
							  topleftx + mgrid->x[i][j]*weres + mgrid->y[i][j]*rot1, 
							  toplefty + mgrid->x[i][j]*rot2 + mgrid->y[i][j]*nsres);
		}
		OGR_F_SetGeometry(feat, geom);
		OGR_G_DestroyGeometry(geom);
		
		// Write the feature to the output vector layer.
		if (OGR_L_CreateFeature(out_layer, feat) != OGRERR_NONE) {
			fprintf(stderr, "Error. Unable to create new feature.\n");
			exit(1);
		}
		OGR_F_Destroy(feat);
		
		row++;
		fid++;
	}
	
	// Write all vertical lines.
	col = 1;
	for (i = 0; i < mgrid->xsize; i += step) {
		// Create a new Feature with the projected coordinates.
		feat = OGR_F_Create(OGR_L_GetLayerDefn(out_layer));
		OGR_F_SetFieldInteger(feat, OGR_F_GetFieldIndex(feat, "ID"), fid);
		OGR_F_SetFieldInteger(feat, OGR_F_GetFieldIndex(feat, "ROW"), 0);
		OGR_F_SetFieldInteger(feat, OGR_F_GetFieldIndex(feat, "COL"), col);
		
		// Create a new geometry object.
		geom = OGR_G_CreateGeometry(wkbLineString);
		for (j = 0; j < mgrid->ysize; j++) {
			OGR_G_SetPoint_2D(
							  geom, 
							  j, 
							  topleftx + mgrid->x[i][j]*weres + mgrid->y[i][j]*rot1, 
							  toplefty + mgrid->x[i][j]*rot2 + mgrid->y[i][j]*nsres);
		}
		OGR_F_SetGeometry(feat, geom);
		OGR_G_DestroyGeometry(geom);
		
		// Write the feature to the output vector layer.
		if (OGR_L_CreateFeature(out_layer, feat) != OGRERR_NONE) {
			fprintf(stderr, "Error. Unable to create new feature.\n");
			exit(1);
		}
		OGR_F_Destroy(feat);
		
		col++;
		fid++;
	}

	// Close the datasources and free the memory.
	OGR_DS_Destroy(out_ds);
	free_morph(mgrid);
	
	return 0;
}
Beispiel #25
0
// Create and add a placement to the current lithograph if it doesn't overlap
// with current labels.
void
simplet_lithograph_add_placement(simplet_lithograph_t *litho,
  OGRFeatureH feature, simplet_list_t *styles, cairo_t *proj_ctx) {

  simplet_style_t *field = simplet_lookup_style(styles, "text-field");
  if(!field) return;

  OGRFeatureDefnH defn;
  if(!(defn = OGR_F_GetDefnRef(feature))) return;

  int idx = OGR_FD_GetFieldIndex(defn, (const char*) field->arg);
  if(idx < 0) return;

  // Find the largest sub geometry of a particular multi-geometry.
  OGRGeometryH super = OGR_F_GetGeometryRef(feature);
  OGRGeometryH geom = super;
  double area = 0.0;
  switch(wkbFlatten(OGR_G_GetGeometryType(super))) {
    case wkbMultiPolygon:
    case wkbGeometryCollection:
      for(int i = 0; i < OGR_G_GetGeometryCount(super); i++) {
        OGRGeometryH subgeom = OGR_G_GetGeometryRef(super, i);
        if(subgeom == NULL) continue;
        double ar = OGR_G_Area(subgeom);
        if(ar > area) {
          geom = subgeom;
          area = ar;
        }
      }
      break;
    default:
      ;
  }

  // Find the center of our geometry. This sometimes throws an invalid geometry
  // error, so there is a slight bug here somehow.
  OGRGeometryH center;
  if(!(center = OGR_G_CreateGeometry(wkbPoint))) return;
  if(OGR_G_Centroid(geom, center) == OGRERR_FAILURE) {
    OGR_G_DestroyGeometry(center);
    return;
  }

  // Turn font hinting off
  cairo_font_options_t *opts;
  if(!(opts = cairo_font_options_create())){
    OGR_G_DestroyGeometry(center);
    return;
  }

  cairo_font_options_set_hint_style(opts, CAIRO_HINT_STYLE_NONE);
  cairo_font_options_set_hint_metrics(opts, CAIRO_HINT_METRICS_OFF);
  pango_cairo_context_set_font_options(litho->pango_ctx, opts);
  cairo_font_options_destroy(opts);

  // Get the field containing the text for the label.
  char *txt = simplet_copy_string(OGR_F_GetFieldAsString(feature, idx));
  PangoLayout *layout = pango_layout_new(litho->pango_ctx);
  pango_layout_set_text(layout, txt, -1);
  free(txt);

  // Grab the font to use and apply tracking.
  simplet_style_t *font = simplet_lookup_style(styles, "font");
  simplet_apply_styles(layout, styles, "letter-spacing", NULL);

  const char *font_family;

  if(!font)
    font_family = "helvetica 12px";
  else
    font_family = font->arg;

  PangoFontDescription *desc = pango_font_description_from_string(font_family);
  pango_layout_set_font_description(layout, desc);
  pango_font_description_free(desc);

  double x = OGR_G_GetX(center, 0), y = OGR_G_GetY(center, 0);
  cairo_user_to_device(proj_ctx, &x, &y);

  // Finally try the placement and test for overlaps.
  try_and_insert_placement(litho, layout, x, y);
  OGR_G_DestroyGeometry(center);
}
Beispiel #26
0
int export_areas_multi(struct Map_info *In, int field, int donocat,
                       OGRFeatureDefnH Ogr_featuredefn,OGRLayerH Ogr_layer,
                       struct field_info *Fi, dbDriver *driver, int ncol, int *colctype,
                       const char **colname, int doatt, int nocat,
                       int *n_noatt, int *n_nocat)
{
    int i, n_exported, area;
    int cat, ncats_field, line, type, findex, ipart;

    struct line_pnts *Points;
    struct line_cats *Cats;
    struct ilist *cat_list, *line_list, *lcats;

    OGRGeometryH Ogr_geometry, Ogr_geometry_part;
    OGRFeatureH Ogr_feature;
    OGRwkbGeometryType wkbtype, wkbtype_part;
    
    Points = Vect_new_line_struct();
    Cats = Vect_new_cats_struct();
    cat_list = Vect_new_list();
    line_list = Vect_new_list();
    lcats = Vect_new_list();

    n_exported = 0;

    /* check if category index is available for given field */
    findex = Vect_cidx_get_field_index(In, field);
    if (findex == -1)
        G_fatal_error(_("Unable to export multi-features. No category index for layer %d."),
                      field);
    
    /* determine type */
    wkbtype_part = wkbPolygon;
    wkbtype = get_multi_wkbtype(wkbtype_part);
    
    ncats_field = Vect_cidx_get_unique_cats_by_index(In, findex, cat_list);
    G_debug(1, "n_cats = %d for layer %d", ncats_field, field);

    if (donocat)
	G_message(_("Exporting features with category..."));

    for (i = 0; i < cat_list->n_values; i++) {
        G_percent(i, cat_list->n_values - 1, 5);

        cat = cat_list->value[i];
        /* find all centroids with given category */
        Vect_cidx_find_all(In, field, GV_CENTROID, cat, line_list);

        /* create multi-feature */
        Ogr_geometry = OGR_G_CreateGeometry(wkbtype);

        /* build simple features geometry, go through all parts */
        for (ipart = 0; ipart < line_list->n_values; ipart++) {
            line = line_list->value[ipart];
            G_debug(3, "cat=%d, line=%d -> part=%d", cat, line, ipart);

            /* get centroid's category */
            Vect_read_line(In, NULL, Cats, line);
            /* check for category consistency */
            Vect_field_cat_get(Cats, field, lcats);
	    if (!Vect_val_in_list(lcats, cat))
                G_fatal_error(_("Unable to create multi-feature. "
                                "Category %d not found in line %d, field %d"),
                              cat, line, field);
            
            /* find correspoding area */
            area = Vect_get_centroid_area(In, line);
            if (area == 0)
                continue;
                
            /* create polygon from area */
            Ogr_geometry_part = create_polygon(In, area, Points);

            /* add part */
            OGR_G_AddGeometryDirectly(Ogr_geometry, Ogr_geometry_part);
        }

        if (!OGR_G_IsEmpty(Ogr_geometry)) {
            /* write multi-feature */
            Ogr_feature = OGR_F_Create(Ogr_featuredefn);
            OGR_F_SetGeometry(Ogr_feature, Ogr_geometry);
            
            mk_att(cat, Fi, driver, ncol, colctype, colname, doatt, nocat,
                   Ogr_feature, n_noatt);
            OGR_L_CreateFeature(Ogr_layer, Ogr_feature);

            OGR_F_Destroy(Ogr_feature);

            n_exported++;
        }
        else {
            /* skip empty features */
            G_debug(3, "multi-feature is empty -> skipped");
        }
        
        OGR_G_DestroyGeometry(Ogr_geometry);
    }

    if (donocat)
	G_message(_("Exporting features without category..."));

    /* check lines without category, if -c flag is given write them as
     * one multi-feature */
    Ogr_geometry = OGR_G_CreateGeometry(wkbtype);
    
    Vect_rewind(In);
    Vect_set_constraint_type(In, GV_CENTROID);
    while(TRUE) {
        type = Vect_read_next_line(In, NULL, Cats);
        if (type < 0)
            break;

        /* get centroid's category */
        Vect_cat_get(Cats, field, &cat);
        if (cat > 0)
            continue; /* skip features with category */
        if (cat < 0 && !donocat) {
            (*n_nocat)++;
            continue; /* skip lines without category, do not export
                       * not labeled */
        }

        /* find correspoding area */
	line = Vect_get_next_line_id(In);
        area = Vect_get_centroid_area(In, line);
        if (area == 0)
            continue;
                
        /* create polygon from area */
        Ogr_geometry_part = create_polygon(In, area, Points);
        
        /* add part */
        OGR_G_AddGeometryDirectly(Ogr_geometry, Ogr_geometry_part);

        (*n_nocat)++;
    }

    if (!OGR_G_IsEmpty(Ogr_geometry)) {
        /* write multi-feature */
        Ogr_feature = OGR_F_Create(Ogr_featuredefn);
        OGR_F_SetGeometry(Ogr_feature, Ogr_geometry);
        
        mk_att(cat, Fi, driver, ncol, colctype, colname, doatt, nocat,
               Ogr_feature, n_noatt);
        OGR_L_CreateFeature(Ogr_layer, Ogr_feature);

        OGR_F_Destroy(Ogr_feature);
        
        n_exported++;
    }
    else {
        /* skip empty features */
        G_debug(3, "multi-feature is empty -> skipped");
    }
    
    OGR_G_DestroyGeometry(Ogr_geometry);
    
    Vect_destroy_line_struct(Points);
    Vect_destroy_cats_struct(Cats);
    Vect_destroy_list(cat_list);
    Vect_destroy_list(line_list);
    Vect_destroy_list(lcats);
    
    return n_exported;
}
Beispiel #27
0
void gdal::OGRGeometryDeleter::operator()( void *geometry )
{
  OGR_G_DestroyGeometry( geometry );
}
Beispiel #28
0
s_sat * sat_aoi(s_sat * sat, const char * shp_aoi_fname, const char * shp_forest_fname)
{
	try;

		OGRDataSourceH a_ds = NULL, f_ds = NULL;
		OGRLayerH a_layer = NULL, f_layer = NULL;
		OGRGeometryH a_geometry = NULL, fa_geometry = NULL, union_geometry = NULL, intersection_geometry = NULL, simplify_geometry = NULL;
		OGRFeatureH next_feature = NULL;
		s_sat * fa_img = NULL;

		throw_null((a_ds = OGR_Dr_Open(drv_shp, shp_aoi_fname, FALSE)));
		throw_null((f_ds = OGR_Dr_Open(drv_shp, shp_forest_fname, FALSE)));

		throw_null((a_layer = OGR_DS_GetLayer(a_ds, 0)));
		throw_null((f_layer = OGR_DS_GetLayer(f_ds, 0)));

		throw_null((a_geometry = OGR_G_CreateGeometry(wkbPolygon)));
		throw_null((fa_geometry = OGR_G_CreateGeometry(wkbPolygon)));

		OGR_L_ResetReading(a_layer);
		
		while((next_feature = OGR_L_GetNextFeature(a_layer)) != NULL)
		{
			throw_null((union_geometry = OGR_G_Union(a_geometry, OGR_F_GetGeometryRef(next_feature))));

			OGR_G_DestroyGeometry(a_geometry);

			a_geometry = union_geometry;

			union_geometry = NULL;
		}

		OGR_L_SetSpatialFilter(f_layer, a_geometry);
		OGR_L_ResetReading(f_layer);

		while((next_feature = OGR_L_GetNextFeature(f_layer)) != NULL)
		{
			throw_null((intersection_geometry = OGR_G_Intersection(a_geometry, OGR_F_GetGeometryRef(next_feature))));
			throw_null((union_geometry = OGR_G_Union(fa_geometry, intersection_geometry)));

			OGR_G_DestroyGeometry(intersection_geometry);
			OGR_G_DestroyGeometry(fa_geometry);

			fa_geometry = union_geometry;

			union_geometry = intersection_geometry = NULL;
		}

		throw_null((simplify_geometry = OGR_G_Simplify(fa_geometry, 0)));
		
		OGR_G_DestroyGeometry(fa_geometry);

		fa_geometry = simplify_geometry;

		simplify_geometry = NULL;

		throw_null((fa_img = sat_rasterize_copy(sat, fa_geometry)));

	catch;

		sat_destroy(fa_img);

		fa_img = NULL;

	finally;

		if(next_feature != NULL)
			OGR_F_Destroy(next_feature);

		if(a_geometry != NULL)
			OGR_G_DestroyGeometry(a_geometry);

		if(fa_geometry != NULL)
			OGR_G_DestroyGeometry(fa_geometry);

		if(union_geometry != NULL)
			OGR_G_DestroyGeometry(union_geometry);

		if(intersection_geometry != NULL)
			OGR_G_DestroyGeometry(intersection_geometry);

		if(simplify_geometry != NULL)
			OGR_G_DestroyGeometry(simplify_geometry);
		
		if(a_ds != NULL)
			OGRReleaseDataSource(a_ds);

		if(f_ds != NULL)
			OGRReleaseDataSource(f_ds);

	return fa_img;
}
Beispiel #29
0
 void newRef(void *v)
 {
     m_ref = RefPtr(v, [](void* t){ OGR_G_DestroyGeometry(t); } );
 }
Beispiel #30
0
int export_areas_single(struct Map_info *In, int field, int donocat,
                        OGRFeatureDefnH Ogr_featuredefn,OGRLayerH Ogr_layer,
                        struct field_info *Fi, dbDriver *driver, int ncol, int *colctype,
                        const char **colname, int doatt, int nocat,
                        int *n_noatt, int *n_nocat)
{
    int i, j;
    int centroid, cat, area, n_areas;
    int n_exported;
    
    struct line_pnts *Points;
    struct line_cats *Cats;

    OGRGeometryH Ogr_geometry;
    OGRFeatureH Ogr_feature;

    Points = Vect_new_line_struct();
    Cats = Vect_new_cats_struct();

    n_exported = 0;

    n_areas = Vect_get_num_areas(In);
    for (i = 1; i <= n_areas; i++) {
        G_percent(i, n_areas, 5);
        
        /* get centroid's category */
        centroid = Vect_get_area_centroid(In, i);
        cat = -1;
        if (centroid > 0) {
            Vect_read_line(In, NULL, Cats, centroid);
            Vect_cat_get(Cats, field, &cat);
        }
        G_debug(3, "area = %d centroid = %d ncats = %d", i, centroid,
                Cats->n_cats);
        if (cat < 0 && !donocat) {
            (*n_nocat)++;
            continue; /* skip areas without category, do not export
                       * not labeled */
        }
        
        /* find correspoding area */
        area = Vect_get_centroid_area(In, centroid);
        if (area == 0)
            continue;

        /* create polygon from area */
        Ogr_geometry = create_polygon(In, area, Points);

        /* add feature */
        Ogr_feature = OGR_F_Create(Ogr_featuredefn);
        OGR_F_SetGeometry(Ogr_feature, Ogr_geometry);
        
        /* output one feature for each category */
        for (j = -1; j < Cats->n_cats; j++) {
            if (j == -1) {
                if (cat >= 0)
                    continue;	/* cat(s) exists */
		(*n_nocat)++;
            }
            else {
                if (Cats->field[j] == field)
                    cat = Cats->cat[j];
                else
                    continue;
            }
            
            mk_att(cat, Fi, driver, ncol, colctype, colname, doatt, nocat,
                   Ogr_feature, n_noatt);
            OGR_L_CreateFeature(Ogr_layer, Ogr_feature);
            
            n_exported++;
        }
        OGR_G_DestroyGeometry(Ogr_geometry);
        OGR_F_Destroy(Ogr_feature);
    }

    Vect_destroy_line_struct(Points);
    Vect_destroy_cats_struct(Cats);

    return n_exported;
}