Draw object import-export examples

From Maria GDK Wiki
Jump to navigation Jump to search

This page contains code examples on how to use the ImportExport library.

Datasource examples

Open datasource

var ds = new DataSourceImport();
if (ds == null) return;

var filepath = "d:\\maps\\geofiles\\geodata.kml";
var open = ds.OpenDataSource(filepath);
if (!open) return;

Import datasource

var ds = new DataSourceImport();
if (ds == null) return;

var filepath = "d:\\maps\\geofiles\\geodata.gml";
var open = ds.OpenDataSource(filepath);
if (!open) return;

//only import points and attributes. Use default Wkt if spatial is missing on imported objects.
ds.ImportSetup = (long) (DataSourceImportBase.ImportSettingEnum.ImportPointObjects | 
            DataSourceImportBase.ImportSettingEnum.ImportAttributes |
            DataSourceImportBase.ImportSettingEnum.ImportUseDefaultWktWhenNoSpatialReference);

//turn on logging
ds.LogConvert = true;

var success = ds.ConvertFromSource();
if (!success) return;

var convertedObjects = ds.DrawObjects;
if (convertedObjects.Count == 0) return;

//any errors?
if (ds.ErrorInformation.Count > 0)
{
    //handle information
}

//log information can be retrieved from ds.LogInformation

Import selection examples

Example of selection XML

The import of draw objects can be limited by selections defined as XML and the content is set using the ISourceImportDriver::DrawObjectSelectionObject object. The selection criteria is checked against entries in the Fields property. This example will accept imported objects with 'extrude' equal to 1 OR 'visibility' equal to -1. The xml content can have several conditioncategory contents so that different selections can be selected by IDrawObjectSelection::SelectionCategory.

<?xml version="1.0" encoding="utf-8" ?>
<conditionset name="Default">
  <conditioncategory name="DrawObjects">
    <condition>
      <fieldcondition field="extrude" op="Eq" value="1" />
    </condition>
    <condition>
      <fieldcondition field="visibility" op="Eq" value="-1" />
    </condition>
  </conditioncategory>
</conditionset>

Select objects when importing based on selection criterias.

This example shows how to use XML selection when importing from a datasource.

var ds = new DataSourceImport {ImportSetup = DefaultImportSetting};

var filepath = "d:\\maps\\geofiles\\geodata.kml";
if (!ds.OpenDataSource(filepath)) return;

var driver = ds.CurrentSource;
if (driver == null) return;

//first, import all objects without selections
if (!ds.ConvertFromSource()) return;
var convertedObjects = ds.DrawObjects;

//use this selection xml file
var xmlPath = "d:\\maps\\geofiles\\conditions.xml");

//now reimport using selection, first get the driver's selection object
var selectionObject = driver.DrawObjectSelectionObject;
if (selectionObject == null) return;

//initialize selection and then reimport
selectionObject.SelectionXmlFile = xmlPath;
selectionObject.SelectionActivated = true;
if (!ds.ConvertFromSource()) return;
var selectedConvertedObjects = ds.DrawObjects;

//only for comparison, run same selection on the objects previously imported without selection
var outsideSelectionObject = new DrawObjectSelection();
outsideSelectionObject.SelectionXmlFile = xmlPath;

//the selectedConvertedObjects.Count should be the same as resultOutside.Count. 
var resultOutside = outsideSelectionObject.Select(convertedObjects);

Add spatial filter to import of datasource

This example shows how to limit import from a datasource to a given spatial area.

var ds = new DataSourceImport();

var filepath = "d:\\maps\\geofiles\\geodata.kml";
if (!ds.OpenDataSource(filepath)) return;

var driver = ds.CurrentSource;
if (driver == null) return;

//Lat for lower left corner is -116
//Lon for lower left corner is 32
//Lat for upper right corner is -114
//Lon for upper right corner is 33
driver.SpatialFilterRect = new Rect(new Point(-116, 32), new Point(-114, 33));

//will only import objects in the spatial area
if (!ds.ConvertFromSource()) return;
var convertedObjects = ds.DrawObjects;

Test the import selection without creating proper draw objects

The import can be tested using a simplified faster convert method if the purpose only is to test the effect of a selection.

var ds = new DataSourceImport();

var filepath = "d:\\maps\\geofiles\\geodata.kml";
if (!ds.OpenDataSource(filepath)) return;

var driver = ds.CurrentSource;
if (driver == null) return;

var xmlPath = "d:\\maps\\geofiles\\conditions.xml");

//import using selection
var selectionObject = driver.DrawObjectSelectionObject;
selectionObject.SelectionXmlFile = xmlPath;
selectionObject.SelectionActivated = true;

//how many objects match this selection?
var count = driver.TrySimpleConvertFromSource();

//now add layer selection, will be in addition to the xml selection already being used.
driver.LayerImportSelection = new List<string>() {"Placemarks", "Paths"};

//re-check selection
count = driver.TrySimpleConvertFromSource();

Datasource layer examples

Get layer information

var ds = new DataSourceImport();
Assert.IsNotNull(ds);

var path = Path.Combine(_importTestDir, "c:\\maps\\geofiles\\shape.shp");
Assert.IsTrue(ds.OpenDataSource(path));

var driver = ds.CurrentSource;
Assert.NotNull(driver, "Driver not opened!");

var count = driver.LayerCount;
Assert.AreEqual(1, count, "Invalid layer count!");
var layerName = driver.LayerName(0);
Assert.AreEqual("shape", layerName, "Invalid layer name!");

var fields = driver.LayerFieldDefinitions(0);
Assert.AreEqual(3, fields.Count, "Invalid field count!");
Assert.AreEqual("scalerank", fields.Keys.ElementAt(0), "Invalid field!");
Assert.AreEqual(TPG.DrawObjects.Data.ImportExport.Interface.FieldType.OFTInteger, fields.Values.ElementAt(0), "Invalid field!");

var geoms = driver.LayerGeometryDefinitions(0, -1);
Assert.AreEqual(TPG.DrawObjects.Data.ImportExport.Interface.GeometryType.wkbPolygon, geoms.First().Key, "Invalid field count!");
Assert.AreEqual(3, geoms.First().Value, "Invalid field count!");

ds.CloseDataSource();

Import from selected layers

The draw objects can be imported from selected layers.

var ds = new DataSourceImport();

var filepath = "d:\\maps\\geofiles\\geodata.kml";
if (!ds.OpenDataSource(filepath)) return;

var driver = ds.CurrentSource;
if (driver == null) return;

driver.LayerImportSelection = new List<string>() {"Placemarks", "Paths"};
if (!ds.ConvertFromSource()) return;

Get information about layer in datasource

It is possible to get information about the selected GDAL datasource. These features are not supported by the NVG-driver.

var ds = new DataSourceImport();

var filepath = "d:\\maps\\geofiles\\geodata.kml";
if (!ds.OpenDataSource(filepath)) return;

var driver = ds.CurrentSource;
if (driver == null) return;

//get layer count in datasource
var count = driver.LayerCount;

//get layer name for layer #0
var layerName = driver.LayerName(0);

//get fields in Layer #0
var fields = driver.LayerFieldDefinitions(0);

//get nuber of fields in layer
var count = fields.Count;

//get name of first field
var fieldName = fields.Keys.ElementAt(0);

//get type of field, example of type could be TPG.DrawObjects.Data.ImportExport.Interface.FieldType.OFTInteger.
var type = fields.Values.ElementAt(0);

//get geometries in layer #0
var geoms = driver.LayerGeometryDefinitions(0, -1);

//get first geometry. Example can ve TPG.DrawObjects.Data.ImportExport.Interface.GeometryType.wkbPolygon. 
var geom = geoms.First().Key;

//get number of first geometries
var geomCount = geoms.First().Value;

Add layer name to imported draw objects

This example shows how to add layer names to imported draw objects.

var ds = new DataSourceImport();
var filepath = "d:\\maps\\geofiles\\geodata.kml";
var open = ds.OpenDataSource(filepath); 

var driver = ds.CurrentSource;
driver.DriverImportSettings = (long) (DriverImportSetting.AddLayerNameAsAttribute);

ds.ConvertFromSource();
ds.CloseDataSource();
var convertedObjects = ds.DrawObjects;

//The IDrawObjectData.Fields property in each draw object should now have an entry with Key = "LayerName" and Value equal to the name of the layer it was imported from.

IDrawObjectData attributes examples

Override filtering of well-known properties

When importing datasource, any properties in the datasource that matches well-known IDrawObjectData Fields keys will not be added to converted draw objects. This feature can be overriden by the AllowTheseKnownFieldNames property.

//get all field keys that will be filtered out
var knownFields = DataSourceInformation.KnownDrawObjectFieldAttributes(DataSourceInformationTypes.All);

//to override this, use first value as example. This will make sure that this value will be added to Fields if any imported objects has this property.
ds.AllowTheseKnownFieldNames = new List<string>() { knownFields.First() };

//import data source
var success = ds.ConvertFromSource();

Prefix attributes in imported draw objects

This example shows how to prefix entries in the IDrawObjectData.Fields property to avoid conflicts with predefined MariaGDK attributes.

var ds = new DataSourceImport();
var filepath = "d:\\maps\\geofiles\\geodata.kml";
var open = ds.OpenDataSource(filepath); 

var driver = ds.CurrentSource;
driver.DriverImportSettings = (long) (DriverImportSetting.PrefixAddedAttributes);

//default prefix for gdal driver is "ogr.", but this can be overriden.
driver.PrefixAttributes = "ogrtest.";

ds.ConvertFromSource();
ds.CloseDataSource();
var convertedObjects = ds.DrawObjects;

//All entries in the IDrawObjectData.Fields property which have been imported from the datasource are now prefixed.
//For example, if DriverImportSetting.AddLayerNameAsAttribute is also used then the layer info is added as
//"ogrtest.LayerName".

Import attributes overlapping IDrawObjectData predefined attributes

MariaGDK has many predefined attributes used in IDrawObjectData. When importing draw objects from a datasource, attributes matching the predefined attributes will by default not be imported. This behaviour can be overriden and information about predefined attributes can be retrieved from DataSourceInformation.

//get all predefined MariaGDK attributes
var predefined = DataSourceInformation.KnownDrawObjectFieldAttributes();

//get only tactical predefined attributes
predefined = DataSourceInformation.KnownDrawObjectFieldAttributes(DataSourceInformationTypes.Tactical);

//Check if attribute collide with MariaGDK predefined attributes. Returns true if given attribute is unique.
var okay = DataSourceInformation.AllowDrawObjectFieldAttribute("attribute");

//if there is an overlap, the import can still import the attribute
var ds = new DataSourceImport {ImportSetup = DefaultImportSetting};
ds.AllowTheseKnownFieldNames = new List<string>() { "Name" };

Add specific external attributes to imported draw objects

It is possible to add external attributes. This must bed set up before the import is started.

var ds = new DataSourceImport();

var filepath = "d:\\maps\\geofiles\\geodata.kml";
if (!ds.OpenDataSource(filepath)) return;

var driver = ds.CurrentSource;
if (driver == null) return;
driver.AddAttributesToDrawObject = 
        new Dictionary<string, string>() { { "Name", "Myname" }, { "NewAttribute", "myvalue" } };

if (!ds.ConvertFromSource()) return;

//all created draw objects should now have the given attributes in IDrawObjectData.Fields.

Rename attributes in created draw objects

The attributes in the imported draw objects can be renamed if necessary.

var ds = new DataSourceImport();

var filepath = "d:\\maps\\geofiles\\geodata.kml";
if (!ds.OpenDataSource(filepath)) return;

var driver = ds.CurrentSource;
if (driver == null) return;

//rename these attributes. Key is original attribute and Value is new renamed attribute. 
//Note: the values are not changed.
driver.ConvertDrawObjectAttributes= new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("tessellate", "changedtessellate"),
                new KeyValuePair<string, string>("extrude", "changedextrude"),
                new KeyValuePair<string, string>("visibility", "changedvisibility"),
                new KeyValuePair<string, string>("visibility", "changedvisibilityagain"),
                new KeyValuePair<string, string>("Name", "changedName"),
                new KeyValuePair<string, string>("Name", "changedNameAgain"),
                new KeyValuePair<string, string>("LayerName", "changedLayerName")
            };

ds.ConvertFromSource();

//next, only rename attributes in selected layers

//reset the general rename setup
driver.ConvertDrawObjectAttributes = null;

//also add prefix feature
driver.DriverImportSettings = (long)(DriverImportSetting.PrefixAddedAttributes | 
                                     DriverImportSetting.AddLayerNameAsAttribute);
driver.PrefixAttributes = "ogrtest.";

//only rename in Layers "Paths" and "Google Campus"
 driver.ConvertLayerDrawObjectAttributes = new Dictionary<string, List<KeyValuePair<string, string>>>
            {
                {
                    "Paths", new List<KeyValuePair<string, string>>
                    {
                        new KeyValuePair<string, string>("ogrtest.tessellate", "ogrtestchangedtessellate"),
                        new KeyValuePair<string, string>("ogrtest.tessellate", "ogrtestchangedtessellate2"),
                        new KeyValuePair<string, string>("ogrtest.tessellate", "ogrtestchangedtessellate3"),
                        new KeyValuePair<string, string>("ogrtest.extrude", "ogrtestchangedextrude"),
                        new KeyValuePair<string, string>("ogrtest.visibility", "ogrtestchangedvisibility"),
                        new KeyValuePair<string, string>("Name", "gdkchangedName"),
                        new KeyValuePair<string, string>("Name", "gdkchangedName2"),
                        new KeyValuePair<string, string>("ogrtest.LayerName", "ogrLayerName"),
                    }
                },
                {
                    "Google Campus", new List<KeyValuePair<string, string>>
                    {
                        new KeyValuePair<string, string>("ogrtest.tessellate", "ogrchangedtessellate"),
                        new KeyValuePair<string, string>("ogrtest.extrude", "ogrchangedextrude"),
                        new KeyValuePair<string, string>("ogrtest.extrude", "ogrchangedextrude2"),
                        new KeyValuePair<string, string>("ogrtest.visibility", "ogrchangedvisibility"),
                        new KeyValuePair<string, string>("Name", "gdkkkchangedName"),
                        new KeyValuePair<string, string>("ogrtest.LayerName", "ogrkkkLayerName"),
                        new KeyValuePair<string, string>("ogrtest.LayerName", "ogrkkkLayerName2")
                    }
                }
            };

ds.ConvertFromSource();

//by default, converting an attribute will not overwrite any already existing attribute.
//The following convert will normally not work since Name is an IDrawObjectData predefined attribute.
driver.ConvertDrawObjectAttributes = new List<KeyValuePair<string, string>>
{
    new KeyValuePair<string, string>("ogrtest.visibility", "Name"),
};

//The solution is to allow the convert to overwrite existing attributes.
driver.DriverImportSettings = (long)(DriverImportSetting.OverwriteExistingAttributes) | driver.DriverImportSettings;

Styling examples

The MariaGDK draw objects are drawn based on attributes in the IDrawObjectData.Fields.

Get styles defined in opened datasource

var ds = new DataSourceImport();

var filepath = "d:\\maps\\geofiles\\geodata.kml";
if (!ds.OpenDataSource(filepath)) return;

var driver = ds.CurrentSource;
if (driver == null) return;

//the xml is empty if no styles in datasource. Any xml is formatted as MariaGDK xml style.
var xml = driver.DatasourceStyle();

XML content to style imported draw objects

The following example will set line width and line line color based on the property extrude. Objects which do not match these two conditions can either be ignored or imported with standard draw setup. This is controlled with ISourceImportDriver.DrawObjectStyleSettings.

<?xml version="1.0" encoding="utf-8" ?> 
<styleset name="Default">
  <stylecategory name="DrawObjects">    
    <style>
      <fieldcondition field="extrude" op="Eq" value="1" />
      <compositeitem name="Line">
        <valueitem name="Width" value="5" />
        <valueitem name="Color" value="0,128,50,255"/>
      </compositeitem>     
    </style>
    
    <style>
      <fieldcondition field="extrude" op="Eq" value="2" />
      <compositeitem name="Line">
        <valueitem name="Width" value="6" />
        <valueitem name="Color" value="100,0,50,255"/>
      </compositeitem>     
    </style>

    <style>
       <compositecondition op="And">
        <fieldcondition field="extrude" op="Eq" value="1" />
        <fieldcondition field="visibility" op="Eq" value="1" />
      </compositecondition>

      <compositeitem name="Line">
        <valueitem name="Width" value="2" />
        <valueitem name="Color" value="10,20,150,55"/>
      </compositeitem>     
    </style>
  </stylecategory>
</styleset>

Style selected draw objects in datasource

This example will import draw objects using styles from KML_Samples.xml. Objects not matching any fieldconditions will not be imported.

    var ds = new DataSourceImport {ImportSetup = DefaultImportSetting};
    ds.OpenDataSource("c:\\geofiles\\KML_Samples.kml");
    if (ds == null)
       return;

    var driver = ds.CurrentSource;
    var styler = driver.DrawObjectStyleObject;
    styler.StyleXmlFile = "c:\\geofiles\\KmlStyle.xml");
    styler.StylingActivated = true;
    
    bool converted = ds.ConvertFromSource();
    if (!converted)
        return;
    
    ds.CloseDataSource();
    var convertedObjects = ds.DrawObjects;

Import and style all draw objects in datasource

This example will import draw objects using styles from KML_Samples.xml. Will also import objects that do not match any fieldconditions and these objects will be styled with any defined styles in the datasource.

    var ds = new DataSourceImport {ImportSetup = DefaultImportSetting};
    ds.OpenDataSource("c:\\geofiles\\KML_Samples.kml");
    if (ds == null)
       return;

    var driver = ds.CurrentSource;
    //also import draw objects not matching any fieldconditions. Add any imported styles to these objects.
    driver.DrawObjectStyleSettings = (long) (DrawObjectStyleSetting.AcceptDrawObjectsWithNoMatchingStyle | 
                                             DrawObjectStyleSetting.UseImportedObjectStyle);

    var styler = driver.DrawObjectStyleObject;
    styler.StyleXmlFile = "c:\\geofiles\\KmlStyle.xml");
    styler.StylingActivated = true;
        
    bool converted = ds.ConvertFromSource();
    if (!converted)
        return;
    
    ds.CloseDataSource();
    var convertedObjects = ds.DrawObjects;

Example of MariaGDK style XML:

<?xml version="1.0" encoding="utf-8"?>
<styleset name="Default">
    <stylecategory name="DrawObjects">
        <style>
            <compositeitem name="Line">
                <valueitem name="Width" value="2" />
            </compositeitem>
        </style>
        <style>
            <compositeitem name="Line">
                <valueitem name="Width" value="4" />
                <valueitem name="Color" value="255,0,255,127" />
            </compositeitem>
            <compositeitem name="Fill">
                <valueitem name="ForegroundColor" value="0,255,0,127" />
            </compositeitem>
        </style>        
    </stylecategory>
</styleset>

Manually attach style to draw objects

//prerequisite: a datasource has been imported...
var convertedObjects = ds.DrawObjects;

var polygonStyle = new DataSourceFillStyle();
var lineStyle = new DataSourceLineStyle();
var symbolStyle = new DataSourceSymbolStyle();

if (ImportPolygons)
{
    lineStyle.LineColor = CurrentColorSetup.LineColor;
    lineStyle.LineWidth = LineWidthValue;
    lineStyle.LineDashStyle = DataSourceStyle.GetStyle("Dot");
    polygonStyle.Fill = True;
    polygonStyle.FillColor = CurrentColorSetup.FillColor;
}
if (ImportLines)
{
    lineStyle.LineColor = CurrentColorSetup.LineColorLine;
    lineStyle.LineWidth = CurrentColorSetup.LineWidthLineValue;
    lineStyle.LineDashStyle = DataSourceStyle.GetStyle("DashDotDot);
}
if (ImportSymbols)
{
    symbolStyle.SymbolType = SymbolTypesSelectedValue;
    symbolStyle.SymbolCode = SymbolCodeValue;
}

var errors = new Dictionary<string, int>();
foreach (var drawObject in convertedObjects)
{
    var primitive = drawObject.Primitives.First();

    if (ImportPolygons && primitive is PolygonArea)
        DrawObjectStyle.AttachStyle(drawObject, polygonStyle, ignoreStyles, errors);
    else if (ImportLines && primitive is TPG.DrawObjects.Data.Geo.Primitives.Line)
        DrawObjectStyle.AttachStyle(drawObject, lineStyle, ignoreStyles, errors);
    else if (ImportSymbols && primitive is TPG.DrawObjects.Data.Geo.Primitives.Points.GeoPoint)
        DrawObjectStyle.AttachStyle(drawObject, symbolStyle, ignoreStyles, errors);
}

Import and export KML styles

Styletables in a KML file will automatically be attached to imported draw objects, but the data format LIBKML must be used to export style tables to KML. Note: IDrawObjectData only supports a limited style functionality.

//simple KML import. Will add any styles in kml file to draw objects
var ds = new DataSourceImport();
ds.OpenDataSource("c:\\geofiles\\kml_samples.kml");
ds.ConvertFromSource();
ds.CloseDataSource();

//export to KML including style tables
Var exportTypeSelectedValue = "LIBKML";
var export = new DataSourceExport { LogExport = false };
export.ExportSetting = DataSourceExport.GetDataFormatExportCapability(exportTypeSelectedValue);
export.CreateDataSource(exportTypeSelectedValue, "c:\\export\\kml_exported.kml");
export.ConvertDrawObjectData(drawObjects);
export.CloseDataSource();

GDAL and spatial examples

Get list of supported OGR drivers

var drivers = GdalConfiguration.GetOgrDrivers();

Testcode using external Wkt

private const int setting = (int)(DataSourceImportBase.ImportSettingEnum.ImportPolygonObjects |
                             DataSourceImportBase.ImportSettingEnum.ImportLineObjects |
                             DataSourceImportBase.ImportSettingEnum.ImportPointObjects |
                             DataSourceImportBase.ImportSettingEnum.ImportMultiLineObjects |
                             DataSourceImportBase.ImportSettingEnum.ImportMultiPolygonObjects |
                             DataSourceImportBase.ImportSettingEnum.ImportAttributes);

var filepath = "c:\\maps\\geofiles\\N5000_VegSti_linje.gml";
var ds = new DataSourceImport {ImportSetup = setting};
Assert.NotNull(ds, "No import object!")

var open = ds.OpenDataSource(filepath);
Assert.IsTrue(status, "Failed to open!")

var status = ds.ConvertFromSource();
ds.CloseDataSource();
Assert.IsTrue(status, "Failed to convert!")

//there should be one spatial error. For this test, use object type wkbLineString25D 
var errorinfo = ds.ErrorInformation;
Assert.AreEqual(1, errorinfo.Count, "Invalid error info count");
Assert.IsTrue(errorinfo.ContainsKey("No spatial reference on wkbLineString25D"), "Missing error info");

//use external Wkt
ds.ImportSetup = setting | (long) DataSourceImportBase.ImportSettingEnum.ImportUseDefaultWktWhenNoSpatialReference;

//do it again
var status = ds.ConvertFromSource();
ds.CloseDataSource();
Assert.IsTrue(status, "Failed to convert!")

//there should be no spatial error
errorinfo = ds.ErrorInformation;
Assert.AreEqual(0, errorinfo.Count, "Invalid error info count");

Export examples

Simple export of draw objects

//create export object
 var export = new DataSourceExport { LogExport = false };
            
//set export settings equal to data format's capability
export.ExportSetting = DataSourceExport.GetDataFormatExportCapability("GML");

//Create the output datasource
var outputpath = "d:\\maps\\geofiles\\exported.gml";
var state = export.CreateDataSource("GML", outputpath);
if (!state) return;

//export existing draw objects 
state = export.ConvertDrawObjectData(drawobjects);
export.CloseDataSource();

if (state)
{
    //the export was successful
}

Get list of tested export data formats

var dataformats = DataSourceExport.ExportSupportedDataFormats;

Export of draw objects

This is a more elaborated example.

//this type can be set in UI, use this value as example
var ExportTypeSelectedValue = "ESRI Shapefile";

//the the capability for selected export type
int capability = DataSourceExport.GetDataFormatExportCapability(ExportTypeSelectedValue);

bool multiOk = ((int)(capability & (int)DataSourceExportBase.ExportSettingEnum.ExportMultiLineObjects) > 0);
bool pointOk = ((int)(capability & (int)DataSourceExportBase.ExportSettingEnum.ExportPointObjects) > 0);
bool lineOk = ((int)(capability & (int)DataSourceExportBase.ExportSettingEnum.ExportLineObjects) > 0);
bool polygonOk = ((int)(capability & (int)DataSourceExportBase.ExportSettingEnum.ExportPolygonObjects) > 0);

//IsChecked objects are from UI to select export geometry types
long setting = (long)(((bool)ExportLines.IsChecked && lineOk
                            ? DataSourceExportBase.ExportSettingEnum.ExportLineObjects
                            : 0) |
                        ((bool)ExportPolys.IsChecked && polygonOk
                            ? DataSourceExportBase.ExportSettingEnum.ExportPolygonObjects
                            : 0) |
                        ((bool)ExportSymbols.IsChecked && pointOk
                            ? DataSourceExportBase.ExportSettingEnum.ExportPointObjects
                            : 0) |
                        ((bool)ExportMulti.IsChecked && multiOk
                            ? DataSourceExportBase.ExportSettingEnum.ExportMultiLineObjects
                            : 0) |
                        ((bool)ExportAttributes.IsChecked
                            ? DataSourceExportBase.ExportSettingEnum.ExportAllAttributes
                            : 0) |
                        ((bool)ExportEmptyAttributes.IsChecked
                            ? DataSourceExportBase.ExportSettingEnum.ExportEmptyAttributes
                            : 0) |
                        ((bool)ClipFieldNames.IsChecked
                            ? 0
                            : DataSourceExportBase.ExportSettingEnum.DoNotClipLongFieldNames));

//create export object
var export = new DataSourceExport(setting);

//test first without conversion. This applies to KMZ 
var extension = DataSourceExportBase.GetDataFormatFileExtension(ExportTypeSelectedValue);
if (extension.Length == 0)
    extension = DataSourceExportBase.GetDataFormatFileExtension(DataSourceExportBase.ConvertDataFormatNameIfNecessary(ExportTypeSelectedValue));

//try to create the datasource
var filename = extension.Length > 0 ? "D:\\maps\\geofiles\\exported" + extension : "";
if (!export.CreateDataSource(ExportTypeSelectedValue, filename))
{
    MessageBox.Show("Failed to create data source!");
    return;
}

//get values from UI
int width;
var b = Int32.TryParse(ClipFieldWidth, out width);
if (b && (bool)ClipFieldNames.IsChecked && width > 0)
    export.FieldNameMaxLength = width;

b = Int32.TryParse(ClipValueWidth, out width);
if (b && (bool)ClipFieldValues.IsChecked && width > 0)
    export.FieldValueWidth = width;

//Export draw objects to datasource
bool exportResult = export.ConvertDrawObjectData(drawObjects);
export.CloseDataSource();

Geometry examples

Simplify geometry

The imported geometry might be possible to simplify using Simply or SimplifyPreserveTopology GDAL methods. The default values are -1 which means no simplification. A positive value will run this process on each line or polygon geometry. NOTE: this might not be successful and the ErrorInformation should be checked for information.

The given tolerance is meter and the value will be converted to degrees before usage if the datasource's unit is degrees: degress tolerance = given tolerance * (180/PI) / 637100 where 637100 is Earth radius.

The simplify value can also be set on selected layers based on the layer names.

var ds = new DataSourceImport();

var filepath = "d:\\maps\\geofiles\\geodata.kml";
if (!ds.OpenDataSource(filepath)) return;

var driver = ds.CurrentSource;
if (driver == null) return;

driver.Simplify = 0.1;
driver.PreserveTopologyMode = false; //use GDAL method Simplify
if (!ds.ConvertFromSource()) return;

//how many points was removed? And check ds.ErrorInformation for information about failed simplification
var reducedCount = driver.SimplifiedPointCount;

//now try with the other method
driver.Simplify = 0.1;
driver.PreserveTopologyMode = true; //use GDAL method SimplifyPreserveTopology
if (!ds.ConvertFromSource()) return;

//how many points was removed?
reducedCount = driver.SimplifiedPointCount;

//set a Simplify value for a specific layer. Other layers will use the given Simplify value, in this case 0.1
driver.SimplifyLayers.Add("Kraftlinje", 10);
if (!ds.ConvertFromSource()) return;

//get detailed Simplify information
var layersReduced = driver.SimplifiedLayerPointCount.Count;
var layerNames = driver.SimplifiedLayerPointCount.Keys.ToList();
var pointsReducedInLayers = driver.SimplifiedLayerPointCount.Values.ToList();

//Do not want any meter to degress conversion, use the given value
driver.DriverImportSettings |= (long) DriverImportSetting.KeepGivenSimplify;
driver.Simplify = 0.0001;
driver.SimplifyLayers.Clear();
if (!ds.ConvertFromSource()) return;

NVG examples

Import NVG xml content directly through driver

var ds = new DataSourceImport();
var driver = ds.SelectDriver(new SourceNvgImportDriver().DriverName) as INvgSourceImportDriver;
if (driver == null) return;

var filepath = "d:\\maps\\geofiles\\geodata.nvg";
string xml = GetXml(filepath);
var loaded = driver.Load(xml);
if (!loaded) return;

var convertedObjects = driver.ConvertFromSource();