In C, get the intersection of OGRFeatureH and OGRGeometry
To get the intersection of an OGRFeatureH
and an OGRGeometry
in C using the GDAL/OGR library, you need to follow these steps:
OGRFeatureH
.OGRGeometry
.Here is a step-by-step example:
Include the necessary headers:
#include "ogr_api.h"
#include "ogr_srs_api.h"
Initialize the GDAL/OGR library:
OGRRegisterAll();
Extract the geometry from the OGRFeatureH
:
OGRFeatureH hFeature; // Assume this is already created and populated
OGRGeometryH hFeatureGeometry = OGR_F_GetGeometryRef(hFeature);
Compute the intersection:
OGRGeometryH hOtherGeometry; // Assume this is already created and populated
OGRGeometryH hIntersection = OGR_G_Intersection(hFeatureGeometry, hOtherGeometry);
Check the result and handle it:
if (hIntersection != NULL) {
// Do something with the intersection geometry
// For example, print it as WKT
char* pszWKT = NULL;
OGR_G_ExportToWkt(hIntersection, &pszWKT);
printf("Intersection WKT: %s\n", pszWKT);
CPLFree(pszWKT);
// Destroy the intersection geometry when done
OGR_G_DestroyGeometry(hIntersection);
} else {
printf("No intersection found.\n");
}
Cleanup and close the GDAL/OGR library:
OGRCleanupAll();
Here is the complete example code:
#include "ogr_api.h"
#include "ogr_srs_api.h"
#include <stdio.h>
int main() {
// Initialize GDAL/OGR
OGRRegisterAll();
// Assume hFeature and hOtherGeometry are already created and populated
OGRFeatureH hFeature; // This should be initialized with a valid feature
OGRGeometryH hOtherGeometry; // This should be initialized with a valid geometry
// Extract the geometry from the feature
OGRGeometryH hFeatureGeometry = OGR_F_GetGeometryRef(hFeature);
// Compute the intersection
OGRGeometryH hIntersection = OGR_G_Intersection(hFeatureGeometry, hOtherGeometry);
// Check the result and handle it
if (hIntersection != NULL) {
// Print the intersection geometry as WKT
char* pszWKT = NULL;
OGR_G_ExportToWkt(hIntersection, &pszWKT);
printf("Intersection WKT: %s\n", pszWKT);
CPLFree(pszWKT);
// Destroy the intersection geometry when done
OGR_G_DestroyGeometry(hIntersection);
} else {
printf("No intersection found.\n");
}
// Cleanup GDAL/OGR
OGRCleanupAll();
return 0;
}
Note:
hFeature
and hOtherGeometry
are properly initialized and populated with valid data before using them.OGR_G_Intersection
function returns a new geometry that represents the intersection. You are responsible for destroying this geometry using OGR_G_DestroyGeometry
when you are done with it.OGR_F_GetGeometryRef
function returns a reference to the geometry of the feature. You should not destroy this geometry directly; it is managed by the feature itself.