Getting started with gdal OGR

Source: Internet
Author: User
Tags gety
This document describes how to read and write data from a file using the ogr c ++ class. Before reading this document, we strongly recommend that you first read the introduction to the OGR architecture, which introduces the main classes in OGR and their functions. To read data from OGR and describe how to read data through OGR, we compile a small example to read data from the OGR file and output the data in a certain format. First, we need to register all the formats we desire to read. This can be easily done by calling ogrregisterall (). This function registers all formats supported by gdal/OGR. # I nclude "ogrsf_frmts.h" int main (){
Ogrregisterall (); Next we will open the input OGR data file. Data files can be files, relational databases, file paths, or even remote network services, depending on the driver we use. However, the data source name is usually a simple string. In this case, we compile Program . The second parameter (flalse) tells the ogrsfdriverregistrar: open () function that we do not need update access. If a failure occurs, null is returned and an error is returned. Ogrdatasource * pods; pods = ogrsfdriverregistrar: open ("point. SHP", false );
If (pods = NULL)
{
Printf ("Open failed. \ n ");
Exit (1 );
} An ogrdatasource may contain many layers. We can obtain the number of contained layers by calling ogrdatasource: getlayercount (), and each of them is obtained by calling ogrdatasource: getlayer () using the index. However, we now use the layer name. Ogrlayer * polayer; polayer = pods-> getlayerbyname ("point"); now we start to read features in the layer. Before getting started, we need to specify an attribute or spatial filter to strictly control our feature. But now we just get all features. Since we started fresh with this layer, it has not been so strict. It is wise to call layer: resetreading () to ensure that we start from the beginning of the layer. We constantly call the ogrlayer: getnextfeature () function to traverse all features. After traversing all features, null is returned. Ogrfeature * pofeature; polayer-> resetreading ();
While (pofeature = polayer-> getnextfeature ())! = NULL)
{To get all the attributes of a feature fields, it is very convenient to call ogrfeaturedefn. This is an object associated with a layer that contains all fields definitions. After completing all fields, we can obtain and display the attribute data. Ogrfeaturedefn * pofdefn = polayer-> getlayerdefn ();
Int ifield; For (ifield = 0; ifield <pofdefn-> getfieldcount (); ifield ++)
{
Ogrfielddefn * pofielddefn = pofdefn-> getfielddefn (ifield); If (pofielddefn-> GetType () = oftinteger)
Printf ("% d,", pofeature-> getfieldasinteger (ifield ));
Else if (pofielddefn-> GetType () = oftreal)
Printf ("%. 3f,", pofeature-> getfieldasdouble (ifield ));
Else if (pofielddefn-> GetType () = oftstring)
Printf ("% s,", pofeature-> getfieldasstring (ifield ));
Else
Printf ("% s,", pofeature-> getfieldasstring (ifield ));
} In reality, the field type is more than the one listed above, but we can extract it by calling the ogrfeature: getfieldasstring () method. In fact, if we use ogrfeature: getfieldasstring (), the program will be shorter. Next, we want to extract the geometry data from the feature, and mark the X and Y coordinates of N. Geometric data is returned through a unified ogrgeometry pointer. Then we determine the type of the geometric data. If it is a vertex, we mark it as a vertex and operate it. If it is another introspection, we write the placeholder. Ogrgeometry * pogeometry; pogeometry = pofeature-> getgeometryref ();
If (pogeometry! = NULL
& Wkbflatten (pogeometry-> getgeometrytype () = wkbpoint)
{
Ogrpoint * popoint = (ogrpoint *) pogeometry; printf ("%. 3f, % 3. f \ n", popoint-> getx (), popoint-> Gety ());
}
Else
{
Printf ("No point geometry \ n ");
} The preceding wkbflatten () macro is used to convert a wkbpoint25d (point with zcoordinates) to a 2D-based type (wkbpoint ). Each 2D geometric type has a type code of 2.5D. However, we only have 2D and 3D C ++ classes. Therefore, our Code It can completely process 2D or 3D examples. Note ogrfeature: getgeometryref () returns a pointer to the internal geometric data of ogrfeature. We have not actually deleted the returned geometric data. However, the ogrlayer: getnextfeature () function returns a copy of our current feature. Therefore, after use, we need to release this feature. We can just "delete" it, but this can cause problems in Windows builds where the gdal dll has a different "Heap" from the main program. to ensure security, we use a gdal function to delete it. Ogrfeature: destroyfeature (pofeature );
} Ogrdatasource: The ogrlayer returned by the getlayerbyname () function is a layer in ogrdatasource. Therefore, we do not need to delete it, but we need to delete this data file to close the input file. Once again, we use this custom Delete to avoid Win32 heap problems. Ogrdatasource: destroydatasource (pods );
} Put all the above together. Our program is as follows: # I nclude "ogrsf_frmts.h" int main (){
Ogrregisterall (); ogrdatasource * pods; pods = ogrsfdriverregistrar: open ("point. SHP", false );
If (pods = NULL)
{
Printf ("Open failed. \ n % s ");
Exit (1 );
} Ogrlayer * polayer; polayer = pods-> getlayerbyname ("point"); 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)
Printf ("% d,", pofeature-> getfieldasinteger (ifield ));
Else if (pofielddefn-> GetType () = oftreal)
Printf ("%. 3f,", pofeature-> getfieldasdouble (ifield ));
Else if (pofielddefn-> GetType () = oftstring)
Printf ("% s,", pofeature-> getfieldasstring (ifield ));
Else
Printf ("% s,", pofeature-> getfieldasstring (ifield ));
} Ogrgeometry * pogeometry; pogeometry = pofeature-> getgeometryref ();
If (pogeometry! = NULL
& Wkbflatten (pogeometry-> getgeometrytype () = wkbpoint)
{
Ogrpoint * popoint = (ogrpoint *) pogeometry; printf ("%. 3f, % 3. f \ n", popoint-> getx (), popoint-> Gety ());
}
Else
{
Printf ("No point geometry \ n ");
}
Ogrfeature: destroyfeature (pofeature );
} Ogrdatasource: destroydatasource (pods );
} Writing to OGR as an example written using OGR, we roughly followed the program mentioned above. This applet uses OGR to write the comma-separated values entered from the file to a shapefile vertex file. Generally, we register all the drivers at the beginning, and then obtain the shapefile driver to create our output file. # I nclude "ogrsf_frmts.h" int main ()
{
Const char * pszdrivername = "ESRI shapefile ";
Ogrsfdriver * podriver; ogrregisterall (); podriver = ogrsfdriverregistrar: getregistrar ()-> getdriverbyname (
Pszdrivername );
If (podriver = NULL)
{
Printf ("% s driver not available. \ n", pszdrivername );
Exit (1 );
} Next, create a data file (datasource ). The ESRI shapefile driver allows us to create a path full of shapefiles or a separate shapefile. Here we create a separate file by including the extension in the name. The processing of other types of drivers is different. The second parameter is a set of parameter values, but the default value is used in this example. The detailed value varies with the format. Ogrdatasource * pods; pods = podriver-> createdatasource ("point_out.shp", null );
If (pods = NULL)
{
Printf ("creation of output file failed. \ n ");
Exit (1 );
} Now we can create an output layer. In this example, it is only a separate file, so we only need to create a layer. We use wkpoint to specify the geometric types supported by this layer. In this example, we do not transmit any coordinate system information or other special layer creation information. Ogrlayer * polayer; polayer = pods-> createlayer ("point_out", null, wkbpoint, null );
If (polayer = NULL)
{
Printf ("layer creation failed. \ n ");
Exit (1 );
} Now that the layer has been created, we need to create any attribute fields that may appear in the layer. Fields must be added to the layer before writing features. To create a field, we use the ogrfield that contains the field information. In the shapefiles file, the width and precision of the field are very important to the output. DBF file ., So we set it, although it is OK by default. In this example, we only have one attribute, the name strings associated with X and Y. Make sure that the ogrfield template we pass to createfidld () is copied internally. We keep the ownership of this oject. Ogrfielddefn ofield ("name", oftstring); ofield. setwidth (32); If (polayer-> createfield (& ofield )! = Ogrerr_none)
{
Printf ("creating Name field failed. \ n ");
Exit (1 );
} \ The loop structure below the encoding (encode) reads the "x, y, name" value from the standard input and analyzes them. The following snipping loops reading lines of the form "X, Y, name" from stdin, and parsing them. \ code double X, Y;
Char szname [33]; while (! Feof (stdin)
& Fscanf (stdin, "% lf, % lf, % 32 s", & X, & Y, szname) = 3)
{To write a feature to a disk, we must create a local ogrfeature, Set Properties and load geometric information before attempting to write it to a layer. Note that this feature must be consistent with the case given by ogrfeaturedefn of the layer to be written. Ogrfeature * pofeature; pofeature = new ogrfeature (polayer-> getlayerdefn ());
Pofeature-> setfield ("name", szname); we create a local geometric file and direct it to feature. The difference between ogrfeature: setgeometrydirectly () and ogrfeature: setgeometry () is that the former gives the feature ownership of geometric data. This is generally more efficient as it avoids an extra deep object copy of the geometry. ogrpoint * popoint = new ogrpoint ();

Popoint-> setx (X );
Popoint-> sety (y );

Pofeature-> setgeometrydirectly (popoint );

Now we have created a feature in this file. The ogrlayer: createfeature () does not cancel the ownership of the feature. Therefore, we need to clear the feature after it is created. If (polayer-> createfeature (pofeature )! = Ogrerr_none)
{
Printf ("failed to create feature in shapefile. \ n ");
Exit (1 );
} Delete pofeature;
} Finally we need to close down the datasource in order to ensure headers are written out in an orderly way and all resources are recovered. ogrdatasource: destroydatasource (pods );
} The same program all in one block looks like this: # I nclude "ogrsf_frmts.h" int main ()
{
Const char * pszdrivername = "ESRI shapefile ";
Ogrsfdriver * podriver; ogrregisterall (); podriver = ogrsfdriverregistrar: getregistrar ()-> getdriverbyname (
Pszdrivername );
If (podriver = NULL)
{
Printf ("% s driver not available. \ n", pszdrivername );
Exit (1 );
} Ogrdatasource * pods; pods = podriver-> createdatasource ("point_out.shp", null );
If (pods = NULL)
{
Printf ("creation of output file failed. \ n ");
Exit (1 );
} Ogrlayer * polayer; polayer = pods-> createlayer ("point_out", null, wkbpoint, null );
If (polayer = NULL)
{
Printf ("layer creation failed. \ n ");
Exit (1 );
} Ogrfielddefn ofield ("name", oftstring); ofield. setwidth (32); If (polayer-> createfield (& ofield )! = Ogrerr_none)
{
Printf ("creating Name field failed. \ n ");
Exit (1 );
} Double X, Y;
Char szname [33]; while (! Feof (stdin)
& Fscanf (stdin, "% lf, % lf, % 32 s", & X, & Y, szname) = 3)
{
Ogrfeature * pofeature; pofeature = new ogrfeature (polayer-> getlayerdefn ());
Pofeature-> setfield ("name", szname); ogrpoint * popoint = new ogrpoint ();

Popoint-> setx (X );
Popoint-> sety (y );

Pofeature-> setgeometrydirectly (popoint );

If (polayer-> createfeature (pofeature )! = Ogrerr_none)
{
Printf ("failed to create feature in shapefile. \ n ");
Exit (1 );
} Delete pofeature;
} Ogrdatasource: destroydatasource (pods );
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.