[GIS] Getting Field value for a given coordinate out of ESRI Shapefile using GDAL/OGR

cgdalogrshapefile

I have a bunch of ESRI shapefiles that contain Land Cover data across Canada (provided by Geobase). I need to query the files and obtain the value of a certain field (called COVTYPE) in a given location specified either by lat/lon or UTM coordinates. I can open a file in Quantum GIS and find the needed values manually, but this process needs to be done automatically for a large number of values so I'm using C++ and GDAL.

I'm very new to the whole GIS area and I'm just starting to learn GDAL. So far I've learned how to loop over layers, features, fields etc, but I can't figure out how to relate coordinates to features. I went through the official GDAL/OGR tutorials, but I'm still stuck. Any pointers would be appreciated!

Update:
Just to clarify. My input data would be coordinates (lat/lon or UTM). So the way I imagine this should work is:

  1. I find which feature the given point is located within
  2. read the field value in that feature

I know how to do step 2, but I'm stuck at step 1.

Final solution
Technically, the update to Ragi's answer comes very close to what I need to do, but I'll post here a quick summary of how I ended up using it. My way is easier for constructing a point geometry object.

So leaving all the boilerplate code out, the essential part is:

OGRPoint* point = new OGRPoint(some_longitude, some_latitude);
layer->SetSpatialFilter(point); //getting only the feature intercepting the point
OGRFeature* feature = layer->GetNextFeature();
int value = feature->GetFieldAsInteger(0); //getting the value - DONE!
//in my case it's 1st field, hence the 0th index

Best Answer

To find which feature the coordinate is near, you first need to build an R-Tree index of bounding boxes or envelope of each feature. A popular library for this is libspatialindex.

Secondly, you would then need to know for each of the matched features from your R-tree, which ones match. GDAL/OGR does have some operations based on GEOS to see if the geometry "contains" the point of interest, and you can extract the field info. See the OGRGeometry Class Reference for Contains, Touches, Within, etc. that can perform the geometry relation operator.


Personally I wouldn't do any of the above, because it would take me too long to figure out the coding, and I know there are faster ways. (I would loading all shapefiles in a PostGIS database, then query the locations using SQL.) However, it is understandable if this GIS functionality needs to be embedded in an existing project without adding more complicated dependencies, such as a database server.