In C++, get geometryRef from OGRFeatureH
In C++, when working with the GDAL/OGR library, you can retrieve the geometry reference from an OGRFeatureH
handle using the OGR_F_GetGeometryRef
function. This function returns a handle to the geometry associated with the feature.
Here's a step-by-step example of how you can achieve this:
Include the necessary headers: Make sure to include the GDAL/OGR headers in your source file.
#include "ogrsf_frmts.h"
Initialize GDAL/OGR: Before using any GDAL/OGR functions, you need to initialize the GDAL/OGR library.
OGRRegisterAll();
Open a data source and get a layer: Open your data source and get the layer from which you want to retrieve features.
const char* pszDataSource = "path/to/your/datasource";
GDALDatasetH hDS = GDALOpenEx(pszDataSource, GDAL_OF_VECTOR, NULL, NULL, NULL);
if (hDS == NULL) {
// Handle error
}
OGRLayerH hLayer = GDALDatasetGetLayer(hDS, 0);
if (hLayer == NULL) {
// Handle error
}
Fetch a feature and get its geometry: Fetch a feature from the layer and retrieve its geometry.
OGRFeatureH hFeature;
OGR_L_ResetReading(hLayer);
while ((hFeature = OGR_L_GetNextFeature(hLayer)) != NULL) {
OGRGeometryH hGeometry = OGR_F_GetGeometryRef(hFeature);
if (hGeometry != NULL) {
// Do something with the geometry
}
// Destroy the feature to avoid memory leaks
OGR_F_Destroy(hFeature);
}
Clean up: After you are done, close the data source and clean up.
GDALClose(hDS);
Here is the complete example:
#include "ogrsf_frmts.h"
int main() {
// Initialize GDAL/OGR
OGRRegisterAll();
// Open the data source
const char* pszDataSource = "path/to/your/datasource";
GDALDatasetH hDS = GDALOpenEx(pszDataSource, GDAL_OF_VECTOR, NULL, NULL, NULL);
if (hDS == NULL) {
// Handle error
return 1;
}
// Get the first layer
OGRLayerH hLayer = GDALDatasetGetLayer(hDS, 0);
if (hLayer == NULL) {
// Handle error
GDALClose(hDS);
return 1;
}
// Fetch features and get their geometries
OGRFeatureH hFeature;
OGR_L_ResetReading(hLayer);
while ((hFeature = OGR_L_GetNextFeature(hLayer)) != NULL) {
OGRGeometryH hGeometry = OGR_F_GetGeometryRef(hFeature);
if (hGeometry != NULL) {
// Do something with the geometry
}
// Destroy the feature to avoid memory leaks
OGR_F_Destroy(hFeature);
}
// Clean up
GDALClose(hDS);
return 0;
}
This example demonstrates how to open a data source, retrieve features from a layer, get the geometry reference from each feature, and clean up resources properly. Make sure to replace "path/to/your/datasource"
with the actual path