Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Aspose.GIS for .NET
This Gist contains code snippets from examples of Aspose.GIS for .NET
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
private class AttributesConverterExample : IAttributesConverter
{
public void ModifyAttribute(FeatureAttribute attribute, AttributesConverterActions actions)
{
switch (attribute.Name)
{
case "name":
// rename and adjust width
attribute.Name = "nickname";
attribute.Width = 10;
break;
case "age":
// change type and adjust width
attribute.DataType = AttributeDataType.String;
attribute.Width = 3;
attribute.Precision = 0;
break;
case "dob":
// exclude attribute from destination file.
actions.Exclude = true;
break;
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
ConversionOptions options = new ConversionOptions();
options.AttributesConverter = new AttributesConverterExample();
VectorLayer.Convert(dataDir + "input.json", Drivers.GeoJson, dataDir + "ConvertGeoJSONToShapeFileWithAttributeAdjustment_out.shp", Drivers.Shapefile, options);
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
string sampleGeoJsonPath = RunExamples.GetDataDir() + "sample.geojson";
var outputFilePath = RunExamples.GetDataDir() + "convertedSample_out.topojson";
VectorLayer.Convert(sampleGeoJsonPath, Drivers.GeoJson, outputFilePath, Drivers.TopoJson);
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
string sampleGeoJsonPath = RunExamples.GetDataDir() + "sample.geojson";
var outputFilePath = RunExamples.GetDataDir() + "convertedSampleWithObjectName_out.topojson";
var options = new ConversionOptions
{
DestinationDriverOptions = new TopoJsonOptions
{
// specify the name of the object where features should be written
DefaultObjectName = "name_of_the_object",
}
};
VectorLayer.Convert(sampleGeoJsonPath, Drivers.GeoJson, outputFilePath, Drivers.TopoJson, options);
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
string sampleGeoJsonPath = RunExamples.GetDataDir() + "sample.geojson";
var outputFilePath = RunExamples.GetDataDir() + "convertedSampleWithGrouping_out.topojson";
var options = new ConversionOptions
{
DestinationDriverOptions = new TopoJsonOptions
{
// we set the attribute in GeoJSON layer by which we are going to group into objects
ObjectNameAttribute = "group",
// if value of "group" is unknown for some feature it should be placed into object with name "unnamed".
DefaultObjectName = "unnamed",
}
};
VectorLayer.Convert(sampleGeoJsonPath, Drivers.GeoJson, outputFilePath, Drivers.TopoJson, options);
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
// convert GeoJSON to TopoJSON with quantization - transforming doubles to integers
// to reduce file size.
string SampleGeoJsonPath = RunExamples.GetDataDir() + "sample.geojson";
var outputFilePath = RunExamples.GetDataDir() + "convertedSampleWithQuantization_out.topojson";
var options = new ConversionOptions
{
DestinationDriverOptions = new TopoJsonOptions
{
// There are two ways to set quantization parameters - with Transform property or
// with quantization number. Here we specify quantization number.
// Quantization number specifies number of expressible values per dimension in a result
// coordinates.
QuantizationNumber = 100_000,
// Alternatively, 'Transform' property can be set (but not simultaneously with quantization number).
// Refer to TopoJSON specification for more details on transform object and quantization.
//
// Transform = new TopoJsonTransform(
// xTranslate: 0,
// yTranslate: 0,
// xScale: 0.0001000010000100001,
// yScale: 0.0001000010000100001),
}
};
VectorLayer.Convert(SampleGeoJsonPath, Drivers.GeoJson, outputFilePath, Drivers.TopoJson, options);
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
VectorLayer.Convert(shapefilePath, Drivers.Shapefile, jsonPath, Drivers.GeoJson);
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
var sampleTopoJsonPath = RunExamples.GetDataDir() + "sample.topojson";
var outputFilePath = RunExamples.GetDataDir() + "convertedSample_out.geojson";
VectorLayer.Convert(sampleTopoJsonPath, Drivers.TopoJson, outputFilePath, Drivers.GeoJson);
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
ILineString readOnlyLine = (ILineString)Geometry.FromText("LINESTRING (1 1, 2 2)");
// Interfaces inherited from IGeometry represent read-only geometries, while
// concrete classes inherited from Geometry represent editable geometries.
// If you need to edit a geometry represented by an interface, 'ToEditable' method should be used to
// get an editable copy.
LineString editableLine = readOnlyLine.ToEditable();
// Line can be edited now
editableLine.AddPoint(3, 3);
Console.WriteLine(editableLine.AsText()); // LINESTRING (1 1, 2 2, 3 3)
// Initial geometry did not change
Console.WriteLine(readOnlyLine.AsText()); // LINESTRING (1 1, 2 2)
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
Point point = new Point(40.7128, -74.006);
LineString line = new LineString();
line.AddPoint(78.65, -32.65);
line.AddPoint(-98.65, 12.65);
GeometryCollection geometryCollection = new GeometryCollection();
geometryCollection.Add(point);
geometryCollection.Add(line);
int geometriesCount = geometryCollection.Count;
Console.WriteLine(geometriesCount); // 2
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
LineString line = new LineString();
line.AddPoint(78.65, -32.65);
line.AddPoint(-98.65, 12.65);
int pointsCount = line.Count;
Console.WriteLine(pointsCount); // 2
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
string path = RunExamples.GetDataDir() + "CreateCircularString_out.shp";
using (VectorLayer layer = VectorLayer.Create(path, Drivers.Shapefile))
{
var feature = layer.ConstructFeature();
// create a circle with center at (1,0) and radius 1.
var circularString = new CircularString();
circularString.AddPoint(0, 0);
circularString.AddPoint(1, 1);
circularString.AddPoint(2, 0);
circularString.AddPoint(1, -1);
circularString.AddPoint(0, 0);
feature.Geometry = circularString;
layer.Add(feature);
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
string path = RunExamples.GetDataDir() + "CreateCompoundCurve_out.shp";
using (VectorLayer layer = VectorLayer.Create(path, Drivers.Shapefile))
{
var feature = layer.ConstructFeature();
// create an 'S' letter (starts at bottom left end)
var compoundCurve = new CompoundCurve();
var bottom = (ILineString)Geometry.FromText("LineString (0 0, 3 0)");
var firstArc = (ICircularString)Geometry.FromText("CircularString (3 0, 4 1, 3 2)");
var middle = (ILineString)Geometry.FromText("LineString (3 2, 1 2)");
var secondArc = (ICircularString)Geometry.FromText("CircularString (1 2, 0 3, 1 4)");
var top = (ILineString)Geometry.FromText("LineString (1 4, 4 4)");
compoundCurve.AddCurve(bottom);
compoundCurve.AddCurve(firstArc);
compoundCurve.AddCurve(middle);
compoundCurve.AddCurve(secondArc);
compoundCurve.AddCurve(top);
feature.Geometry = compoundCurve;
layer.Add(feature);
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
string path = RunExamples.GetDataDir() + "CreateCurvePolygon_out.shp";
using (VectorLayer layer = VectorLayer.Create(path, Drivers.Shapefile))
{
var feature = layer.ConstructFeature();
// create a torus with center at (0,0), radius equal to 2 and hole radius equal to 1
var curvePolygon = new CurvePolygon();
var exterior = new CircularString();
exterior.AddPoint(-2, 0);
exterior.AddPoint(0, 2);
exterior.AddPoint(2, 0);
exterior.AddPoint(0, -2);
exterior.AddPoint(-2, 0);
curvePolygon.ExteriorRing = exterior;
var interior = new CircularString();
interior.AddPoint(-1, 0);
interior.AddPoint(0, 1);
interior.AddPoint(1, 0);
interior.AddPoint(0, -1);
interior.AddPoint(-1, 0);
curvePolygon.AddInteriorRing(interior);
feature.Geometry = curvePolygon;
layer.Add(feature);
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
Point point = new Point(40.7128, -74.006);
LineString line = new LineString();
line.AddPoint(78.65, -32.65);
line.AddPoint(-98.65, 12.65);
GeometryCollection geometryCollection = new GeometryCollection();
geometryCollection.Add(point);
geometryCollection.Add(line);
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
LineString line = new LineString();
line.AddPoint(78.65, -32.65);
line.AddPoint(-98.65, 12.65);
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
string path = RunExamples.GetDataDir() + "CreateMultiCurve_out.shp";
using (VectorLayer layer = VectorLayer.Create(path, Drivers.Shapefile))
{
var feature = layer.ConstructFeature();
var multiCurve = new MultiCurve();
multiCurve.Add(Geometry.FromText("LineString (0 0, 1 0)"));
multiCurve.Add(Geometry.FromText("CircularString (2 2, 3 3, 4 2)"));
multiCurve.Add(Geometry.FromText("CompoundCurve ((0 1, 0 0), CircularString (0 0, 3 3, 6 0))"));
feature.Geometry = multiCurve;
layer.Add(feature);
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
LineString firstLine = new LineString();
firstLine.AddPoint(7.5, -3.5);
firstLine.AddPoint(-9.6, 12.6);
LineString secondLine = new LineString();
secondLine.AddPoint(8.5, -2.6);
secondLine.AddPoint(-8.6, 1.5);
MultiLineString multiLineString = new MultiLineString();
multiLineString.Add(firstLine);
multiLineString.Add(secondLine);
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
MultiPoint multipoint = new MultiPoint();
multipoint.Add(new Point(1, 2));
multipoint.Add(new Point(3, 4));
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
LinearRing firstRing = new LinearRing();
firstRing.AddPoint(8.5, -2.5);
firstRing.AddPoint(-8.5, 2.5);
firstRing.AddPoint(8.5, -2.5);
Polygon firstPolygon = new Polygon(firstRing);
LinearRing secondRing = new LinearRing();
secondRing.AddPoint(7.6, -3.6);
secondRing.AddPoint(-9.6, 1.5);
secondRing.AddPoint(7.6, -3.6);
Polygon secondPolygon = new Polygon(secondRing);
MultiPolygon multiPolygon = new MultiPolygon();
multiPolygon.Add(firstPolygon);
multiPolygon.Add(secondPolygon);
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
string path = RunExamples.GetDataDir() + "CreateMultiSurface_out.json";
using (VectorLayer layer = VectorLayer.Create(path, Drivers.GeoJson))
{
var feature = layer.ConstructFeature();
var multiSurface = new MultiSurface();
var polygon = Geometry.FromText("Polygon ((0 0, 0 1, 1 1, 1 0, 0 0))");
multiSurface.Add(polygon);
var curvePolygon = Geometry.FromText("CurvePolygon (CircularString (-2 0, 0 2, 2 0, 0 -2, -2 0))");
multiSurface.Add(curvePolygon);
feature.Geometry = multiSurface;
layer.Add(feature);
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
Point point = new Point(40.7128, -74.006);
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
Polygon polygon = new Polygon();
LinearRing ring = new LinearRing();
ring.AddPoint(50.02, 36.22);
ring.AddPoint(49.99, 36.26);
ring.AddPoint(49.97, 36.23);
ring.AddPoint(49.98, 36.17);
ring.AddPoint(50.02, 36.22);
polygon.ExteriorRing = ring;
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
Polygon polygon = new Polygon();
LinearRing ring = new LinearRing();
ring.AddPoint(50.02, 36.22);
ring.AddPoint(49.99, 36.26);
ring.AddPoint(49.97, 36.23);
ring.AddPoint(49.98, 36.17);
ring.AddPoint(50.02, 36.22);
LinearRing hole = new LinearRing();
hole.AddPoint(50.00, 36.22);
hole.AddPoint(49.99, 36.20);
hole.AddPoint(49.98, 36.23);
hole.AddPoint(50.00, 36.24);
hole.AddPoint(50.00, 36.22);
polygon.ExteriorRing = ring;
polygon.AddInteriorRing(hole);
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
var geometry1 = new MultiLineString
{
new LineString(new [] { new Point(0, 0), new Point(1, 1) }),
new LineString(new [] { new Point(1, 1), new Point(2, 2) }),
};
var geometry2 = new LineString(new[]
{
new Point(0, 0), new Point(2, 2),
});
Console.WriteLine(geometry1.SpatiallyEquals(geometry2)); // True
geometry2.AddPoint(3, 3);
Console.WriteLine(geometry1.SpatiallyEquals(geometry2)); // False
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
var geometry1 = new LineString();
geometry1.AddPoint(0, 0);
geometry1.AddPoint(2, 2);
var geometry2 = new LineString();
geometry2.AddPoint(1, 1);
geometry2.AddPoint(3, 3);
Console.WriteLine(geometry1.Crosses(geometry2)); // False
var geometry3 = new LineString();
geometry3.AddPoint(0, 2);
geometry3.AddPoint(2, 0);
Console.WriteLine(geometry1.Crosses(geometry3)); // True
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
var geometry1 = new Polygon(new LinearRing(new[]
{
new Point(0, 0),
new Point(0, 3),
new Point(3, 3),
new Point(3, 0),
new Point(0, 0),
}));
var geometry2 = new Polygon(new LinearRing(new[]
{
new Point(1, 1),
new Point(1, 4),
new Point(4, 4),
new Point(4, 1),
new Point(1, 1),
}));
Console.WriteLine(geometry1.Intersects(geometry2)); // True
Console.WriteLine(geometry2.Intersects(geometry1)); // True
// 'Disjoint' is opposite to 'Intersects'
Console.WriteLine(geometry1.Disjoint(geometry2)); // False
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
var geometry1 = new LineString();
geometry1.AddPoint(0, 0);
geometry1.AddPoint(0, 2);
var geometry2 = new LineString();
geometry2.AddPoint(0, 2);
geometry2.AddPoint(0, 3);
Console.WriteLine(geometry1.Overlaps(geometry2)); // False
var geometry3 = new LineString();
geometry3.AddPoint(0, 1);
geometry3.AddPoint(0, 3);
Console.WriteLine(geometry1.Overlaps(geometry3)); // True
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
var geometry1 = new LineString();
geometry1.AddPoint(0, 0);
geometry1.AddPoint(2, 2);
var geometry2 = new LineString();
geometry2.AddPoint(2, 2);
geometry2.AddPoint(3, 3);
Console.WriteLine(geometry1.Touches(geometry2)); // True
Console.WriteLine(geometry2.Touches(geometry1)); // True
var geometry3 = new Point(2, 2);
Console.WriteLine(geometry1.Touches(geometry3)); // True
var geometry4 = new LineString();
geometry4.AddPoint(1, 1);
geometry4.AddPoint(4, 4);
Console.WriteLine(geometry1.Touches(geometry4)); // False
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
var geometryWithoutCurves = Geometry.FromText(@"GeometryCollection (LineString (0 0, 1 1, 2 0),CompoundCurve ((4 0, 5 1), (5 1, 6 2, 7 1)))");
// geometry does not contain circular string, so HasCurveGeometry returns false.
Console.WriteLine(geometryWithoutCurves.HasCurveGeometry); // False
var geometry = Geometry.FromText(@"GeometryCollection (LineString (0 0, 1 1, 2 0),CompoundCurve ((4 0, 5 1), CircularString (5 1, 6 2, 7 1)))");
// geometry contains circular string, so HasCurveGeometry returns true.
Console.WriteLine(geometry.HasCurveGeometry); // True
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
var geometry1 = new Polygon();
geometry1.ExteriorRing = new LinearRing(new[]
{
new Point(0, 0),
new Point(0, 4),
new Point(4, 4),
new Point(4, 0),
new Point(0, 0),
});
geometry1.AddInteriorRing(new LinearRing(new[]
{
new Point(1, 1),
new Point(1, 3),
new Point(3, 3),
new Point(3, 1),
new Point(1, 1),
}));
var geometry2 = new Point(2, 2);
Console.WriteLine(geometry1.SpatiallyContains(geometry2)); // False
var geometry3 = new Point(0.5, 0.5);
Console.WriteLine(geometry1.SpatiallyContains(geometry3)); // True
// 'a.SpatiallyContains(b)' equals to 'b.Within(a)'
Console.WriteLine(geometry3.Within(geometry1)); // True
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
var line = new LineString();
line.AddPoint(0, 0);
line.AddPoint(1, 1);
var point = new Point(0, 0);
Console.WriteLine(line.Covers(point)); // True
Console.WriteLine(point.CoveredBy(line)); // True
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
var geometry1 = new LineString();
geometry1.AddPoint(0, 0);
geometry1.AddPoint(0, 2);
var geometry2 = new LineString();
geometry2.AddPoint(0, 1);
geometry2.AddPoint(0, 3);
// Relate method takes a string representation of DE-9IM matrix
// (Dimensionally Extended Nine-Intersection Model matrix).
// see Simple Feature Access specification for more details on DE-9IM.
// this is the equivalent of 'geometry1.SpatiallyEquals(geometry2)'
Console.WriteLine(geometry1.Relate(geometry2, "T*F**FFF*")); // False
// this is the equivalent of 'geometry1.Disjoint(geometry2)'
Console.WriteLine(geometry1.Relate(geometry2, "FF*FF****")); // False
// this is the equivalent of 'geometry1.Overlaps(geometry2)'
Console.WriteLine(geometry1.Relate(geometry2, "1*T***T**")); // True
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
// find intersection, union, difference and symmetric difference of two geometries.
var polygon1 = new Polygon();
polygon1.ExteriorRing = new LinearRing(new[]
{
new Point(0, 0),
new Point(0, 2),
new Point(2, 2),
new Point(2, 0),
new Point(0, 0),
});
var polygon2 = new Polygon();
polygon2.ExteriorRing = new LinearRing(new[]
{
new Point(1, 1),
new Point(1, 3),
new Point(3, 3),
new Point(3, 1),
new Point(1, 1),
});
var intersection = polygon1.Intersection(polygon2);
Console.WriteLine("Intersection type is {0}", intersection.GeometryType); // Polygon
PrintRing(((IPolygon)intersection).ExteriorRing);
// [0] - (1 1)
// [1] - (1 2)
// [2] - (2 2)
// [3] - (2 1)
// [4] - (1 1)
var union = polygon1.Union(polygon2);
Console.WriteLine("Union type is {0}", union.GeometryType); // Polygon
PrintRing(((IPolygon)union).ExteriorRing);
// [0] - (0 0)
// [1] - (0 2)
// [2] - (1 2)
// [3] - (1 3)
// [4] - (3 3)
// [5] - (3 1)
// [6] - (2 1)
// [7] - (2 0)
// [8] - (0 0)
var difference = polygon1.Difference(polygon2);
Console.WriteLine("Difference type is {0}", difference.GeometryType); // Polygon
PrintRing(((IPolygon)difference).ExteriorRing);
// [0] - (0 0)
// [1] - (0 2)
// [2] - (1 2)
// [3] - (1 1)
// [4] - (2 1)
// [5] - (2 0)
// [6] - (0 0)
var symDifference = polygon1.SymDifference(polygon2);
Console.WriteLine("Symmetric Difference type is {0}", symDifference.GeometryType); // MultiPolygon
var multiPolygon = (IMultiPolygon)symDifference;
Console.WriteLine("Polygons count is {0}", multiPolygon.Count); // 2
PrintRing(((IPolygon)multiPolygon[0]).ExteriorRing);
// [0] - (0 0)
// [1] - (0 2)
// [2] - (1 2)
// [3] - (1 1)
// [4] - (2 1)
// [5] - (2 0)
// [6] - (0 0)
PrintRing(((IPolygon)multiPolygon[1]).ExteriorRing);
// [0] - (1 2)
// [1] - (1 3)
// [2] - (3 3)
// [3] - (3 1)
// [4] - (2 1)
// [5] - (2 2)
// [6] - (1 2)
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
LineString lineString = new LineString();
bool simple = lineString.IsSimple; // simple == true
lineString.AddPoint(0, 0);
lineString.AddPoint(1, 0);
simple = lineString.IsSimple; // simple == true
lineString.AddPoint(0.5, 0);
simple = lineString.IsSimple; // simple == false (line string crosses itself)
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
LinearRing linearRing = new LinearRing();
linearRing.AddPoint(0, 0);
linearRing.AddPoint(0, 1);
linearRing.AddPoint(1, 0);
bool valid = linearRing.IsValid; // valid == false
linearRing.AddPoint(0, 0);
valid = linearRing.IsValid; // valid == true
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
var exteriorRing = new LinearRing();
exteriorRing.AddPoint(0, 0);
exteriorRing.AddPoint(0, 1);
exteriorRing.AddPoint(1, 1);
exteriorRing.AddPoint(1, 0);
exteriorRing.AddPoint(0, 0);
var interiorRing = new LinearRing();
interiorRing.AddPoint(0.5, 0.5);
interiorRing.AddPoint(1, 0.5);
interiorRing.AddPoint(1, 1);
interiorRing.AddPoint(0.5, 1);
interiorRing.AddPoint(0.5, 0.5);
var invalidPolygon = new Polygon();
invalidPolygon.ExteriorRing = exteriorRing;
invalidPolygon.AddInteriorRing(interiorRing);
// invalidPolygon.IsValid == false, since polygon rings share segments (have infinite number of intersection points)
GeoJsonOptions options = new GeoJsonOptions();
options.ValidateGeometriesOnWrite = false; // false is default
File.Delete(dataDir + "not_validated_data_out.shp");
using (var nonValidatingLayer = Drivers.GeoJson.CreateLayer(dataDir + "not_validated_data_out.shp", options))
{
Feature feature = nonValidatingLayer.ConstructFeature();
feature.Geometry = invalidPolygon;
// no exception is thrown, since ValidateGeometriesOnWrite == false, and GeoJson specification doesn't say that rings of polygon can't share segments.
nonValidatingLayer.Add(feature);
}
options.ValidateGeometriesOnWrite = true;
File.Delete(dataDir + "validated_data_out.shp");
using (var validatingLayer = Drivers.GeoJson.CreateLayer(dataDir + "validated_data_out.shp", options))
{
Feature feature = validatingLayer.ConstructFeature();
feature.Geometry = invalidPolygon;
try
{
validatingLayer.Add(feature); // GisException is thrown, since polygon is not valid
}
catch (GisException e)
{
Console.WriteLine(e.Message);
}
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
LineString lineStrinWithOnePoint = new LineString();
lineStrinWithOnePoint.AddPoint(0, 0);
GeoJsonOptions options = new GeoJsonOptions();
options.ValidateGeometriesOnWrite = false;
using (var layer = Drivers.GeoJson.CreateLayer(dataDir + "ValidateOnWriteObeyingSpecifications_out.json", options))
{
Feature feature = layer.ConstructFeature();
// GeoJSON specification says that line string must have at least two coordinates.
feature.Geometry = lineStrinWithOnePoint;
try
{
// Geometry of feature doesn't match data format specification, so exception is thrown
// regardless what ValidateGeometriesOnWrite option is.
layer.Add(feature);
}
catch (GisException e)
{
Console.WriteLine(e.Message);
}
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
var triangleRing = new LinearRing();
triangleRing.AddPoint(4, 6);
triangleRing.AddPoint(1, 3);
triangleRing.AddPoint(8, 7);
triangleRing.AddPoint(4, 6);
var triangle = new Polygon(triangleRing);
var squareRing = new LinearRing();
squareRing.AddPoint(0, 9);
squareRing.AddPoint(0, 7);
squareRing.AddPoint(2, 7);
squareRing.AddPoint(2, 9);
squareRing.AddPoint(0, 9);
var square = new Polygon(squareRing);
var multiPolygon = new MultiPolygon { triangle, square };
Console.WriteLine("{0:F}", triangle.GetArea()); // 4.50
Console.WriteLine("{0:F}", square.GetArea()); // 4.00
Console.WriteLine("{0:F}", multiPolygon.GetArea()); // 8.50
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
var polygon = new Polygon();
polygon.ExteriorRing = new LinearRing(new[]
{
new Point(1, 0),
new Point(2, 2),
new Point(0, 4),
new Point(5, 5),
new Point(6, 1),
new Point(1, 0),
});
IPoint centroid = polygon.GetCentroid();
Console.WriteLine("{0:F} {1:F}", centroid.X, centroid.Y); // 3.33 2.58
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
var geometry = new MultiPoint
{
new Point(3, 2),
new Point(0, 0),
new Point(6, 5),
new Point(5, 10),
new Point(10, 0),
new Point(8, 2),
new Point(4, 3),
};
var convexHull = geometry.GetConvexHull();
// [0] = (0 0)
// [1] = (5 10)
// [2] = (10 0)
// [3] = (0 0)
var ring = (ILinearRing)convexHull;
for (int i = 0; i < ring.Count; ++i)
{
Console.WriteLine("[{0}] = ({1} {2})", i, ring[i].X, ring[i].Y);
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
var polygon = new Polygon();
polygon.ExteriorRing = new LinearRing(new[]
{
new Point(0, 0),
new Point(0, 1),
new Point(1, 1),
new Point(1, 0),
new Point(0, 0),
});
var line = new LineString();
line.AddPoint(2, 0);
line.AddPoint(1, 3);
double distance = polygon.GetDistanceTo(line);
Console.WriteLine(distance.ToString("F")); // 0.63
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
var line = new LineString();
line.AddPoint(0, 0);
line.AddPoint(3, 3);
// buffer with positive distance contains all points whose distance to input geometry is less or equal to 'distance' argument.
var lineBuffer = line.GetBuffer(distance: 1);
Console.WriteLine(lineBuffer.SpatiallyContains(new Point(1, 2))); // True
Console.WriteLine(lineBuffer.SpatiallyContains(new Point(3.1, 3.1))); // True
var polygon = new Polygon();
polygon.ExteriorRing = new LinearRing(new[]
{
new Point(0, 0),
new Point(0, 3),
new Point(3, 3),
new Point(3, 0),
new Point(0, 0),
});
// buffer with negative distance 'shrinks' geometry.
var polygonBuffer = (IPolygon)polygon.GetBuffer(distance: -1);
// [0] = (1 1)
// [1] = (1 2)
// [2] = (2 2)
// [3] = (2 1)
// [4] = (1 1)
var ring = polygonBuffer.ExteriorRing;
for (int i = 0; i < ring.Count; ++i)
{
Console.WriteLine("[{0}] = ({1} {2})", i, ring[i].X, ring[i].Y);
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
Point point = new Point(40.7128, -74.006);
GeometryType geometryType = point.GeometryType;
Console.WriteLine(geometryType); // Point
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
var line = new LineString();
line.AddPoint(0, 0);
line.AddPoint(2, 2);
line.AddPoint(2, 0);
Console.WriteLine("{0:F}", line.GetLength()); // 4.83
var rectangle = new Polygon(new LinearRing(new[]
{
new Point(0, 0),
new Point(0, 1),
new Point(1, 1),
new Point(1, 0),
new Point(0, 0),
}));
// GetLength() returns perimeter for polygons
Console.WriteLine("{0:F}", rectangle.GetLength()); // 4.00
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
var polygon = new Polygon();
polygon.ExteriorRing = new LinearRing(new[]
{
new Point(0, 0),
new Point(0, 1),
new Point(1, 1),
new Point(0, 0),
});
IPoint pointOnSurface = polygon.GetPointOnSurface();
// point on surface is guaranteed to be inside a polygon.
Console.WriteLine(polygon.SpatiallyContains(pointOnSurface)); // True
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
Point pointGeometry = new Point(40.7128, -74.006);
LineString lineGeometry = new LineString();
lineGeometry.AddPoint(78.65, -32.65);
lineGeometry.AddPoint(-98.65, 12.65);
GeometryCollection geometryCollection = new GeometryCollection();
geometryCollection.Add(pointGeometry);
geometryCollection.Add(lineGeometry);
foreach (Geometry geometry in geometryCollection)
{
switch (geometry.GeometryType)
{
case GeometryType.Point:
Point point = (Point)geometry;
break;
case GeometryType.LineString:
LineString line = (LineString)geometry;
break;
}
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
LineString line = new LineString();
line.AddPoint(78.65, -32.65);
line.AddPoint(-98.65, 12.65);
foreach (IPoint point in line)
{
Console.WriteLine(point.X + "," + point.Y);
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
string path = RunExamples.GetDataDir() + "LimitPrecisionWhenReadingGeometries_out.shp";
using (VectorLayer layer = VectorLayer.Create(path, Drivers.Shapefile))
{
var feature = layer.ConstructFeature();
feature.Geometry = new Point(1.10234, 2.09743);
layer.Add(feature);
}
var options = new ShapefileOptions();
// read data as-is.
options.XYPrecisionModel = PrecisionModel.Exact;
using (VectorLayer layer = VectorLayer.Open(path, Drivers.Shapefile, options))
{
var point = (IPoint)layer[0].Geometry;
// 1.10234, 2.09743
Console.WriteLine("{0}, {1}", point.X, point.Y);
}
// truncate all X and Y, so only two fractional digits are left.
options.XYPrecisionModel = PrecisionModel.Rounding(2);
using (VectorLayer layer = VectorLayer.Open(path, Drivers.Shapefile, options))
{
var point = (IPoint)layer[0].Geometry;
// 1.1, 2.1
Console.WriteLine("{0}, {1}", point.X, point.Y);
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
var options = new GeoJsonOptions
{
// write only 3 fractional digits of X and Y coordinates.
XYPrecisionModel = PrecisionModel.Rounding(3),
// write all fractional digits of Z coordinate (the default, you don't have to specify it)
ZPrecisionModel = PrecisionModel.Exact
};
var path = RunExamples.GetDataDir() + "LimitPrecisionWhenWritingGeometries_out.json";
using (VectorLayer layer = VectorLayer.Create(path, Drivers.GeoJson, options))
{
var point = new Point();
point.X = 1.8888888;
point.Y = 1.00123;
point.Z = 1.123456789;
Feature feature = layer.ConstructFeature();
feature.Geometry = point;
layer.Add(feature);
}
using (VectorLayer layer = VectorLayer.Open(path, Drivers.GeoJson))
{
var point = (IPoint)layer[0].Geometry;
// 1.889, 1.001, 1.123456789
Console.WriteLine("{0}, {1}, {2}", point.X, point.Y, point.Z);
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
string path = RunExamples.GetDataDir() + "LinearizeGeometry_out.kml";
using (var layer = Drivers.Kml.CreateLayer(path))
{
var feature = layer.ConstructFeature();
var geometry = Geometry.FromText(@"GeometryCollection (LineString (0 0, 1 1, 2 0),CompoundCurve ((4 0, 5 1), CircularString (5 1, 6 2, 7 1)))");
// creates linear geometry that approximates input geometry
var linear = geometry.ToLinearGeometry();
feature.Geometry = linear;
layer.Add(feature);
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
Point point = new Point(1.344, 2.345, 3.345, 4.345);
point.RoundXY(digits: 2);
// 1.34, 2.35, 3.345, 4.345
Console.WriteLine("{0}, {1}, {2}, {3}", point.X, point.Y, point.Z, point.M);
point.RoundZ(digits: 1);
// 1.34, 2.35, 3.3, 4.345
Console.WriteLine("{0}, {1}, {2}, {3}", point.X, point.Y, point.Z, point.M);
LineString line = new LineString();
line.AddPoint(1.2, 2.3);
line.AddPoint(2.4, 3.1);
line.RoundXY(digits: 0);
// 1, 2
Console.WriteLine("{0}, {1}", line[0].X, line[0].Y);
// 2, 3
Console.WriteLine("{0}, {1}", line[1].X, line[1].Y);
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
// If file format does not support curve geometries, we linearize them on write.
// This example shows how to specify tolerance of the linearization.
var options = new GeoJsonOptions
{
// linearized geometry must be within 1e-4 from curve geometry
LinearizationTolerance = 1e-4,
};
string path = RunExamples.GetDataDir() + "SpecifyLinearizationTolerance_out.json";
using (VectorLayer layer = VectorLayer.Create(path, Drivers.GeoJson, options))
{
var curveGeometry = Geometry.FromText("CircularString (0 0, 1 1, 2 0)");
var feature = layer.ConstructFeature();
feature.Geometry = curveGeometry;
// geometry is linearized with tolerance 1e-4
layer.Add(feature);
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
IGeometry geometry = Geometry.FromText("LINESTRING (1.2 3.4, 5.6 7.8)");
byte[] wkb = geometry.AsBinary(WkbVariant.ExtendedPostGis);
File.WriteAllBytes(Path.Combine(RunExamples.GetDataDir(), "EWkbFile.ewkb"), wkb);
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
Point point = new Point(23.5732, 25.3421) { M = 40.3 };
point.SpatialReferenceSystem = SpatialReferenceSystem.Wgs84;
Console.WriteLine(point.AsText(WktVariant.Iso)); // POINT M (23.5732, 25.3421, 40.3)
Console.WriteLine(point.AsText(WktVariant.SimpleFeatureAccessOutdated)); // POINT (23.5732, 25.3421)
Console.WriteLine(point.AsText(WktVariant.ExtendedPostGis)); // SRID=4326;POINTM (23.5732, 25.3421, 40.3)
// to get max a decimal precision
Console.WriteLine("G17 : " + point.AsText(WktVariant.Iso, NumericFormat.General(17))); // POINT M (23.5732 25.342099999999999 40.299999999999997)
Console.WriteLine("R : " + point.AsText(WktVariant.Iso, NumericFormat.RoundTrip)); // POINT M (23.5732 25.3421 40.3)
// to trim a decimal precision
Console.WriteLine("G3 : " + point.AsText(WktVariant.Iso, NumericFormat.General(3))); // POINT M (23.6 25.3 40.3)
Console.WriteLine("Flat3: " + point.AsText(WktVariant.Iso, NumericFormat.Flat(3))); // POINT M (23.573 25.342 40.3)
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
string path = Path.Combine(RunExamples.GetDataDir(), "WkbFile.wkb");
byte[] wkb = File.ReadAllBytes(path);
IGeometry geometry = Geometry.FromBinary(wkb);
Console.WriteLine(geometry.AsText()); // LINESTRING (1.2 3.4, 5.6 7.8)
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
ILineString line = (ILineString)Geometry.FromText("LINESTRING Z (0.1 0.2 0.3, 1 2 1, 12 23 2)");
Console.WriteLine(line.Count); // 3
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
IGeometry geometry = Geometry.FromText("LINESTRING (1.2 3.4, 5.6 7.8)");
byte[] wkb = geometry.AsBinary();
//File.WriteAllBytes(Path.Combine(TestConfiguration.TestOutputPath, "file.wkb"), wkb);
File.WriteAllBytes(Path.Combine(RunExamples.GetDataDir(), "WkbFile.wkb"), wkb);
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
Point point = new Point(23.5732, 25.3421);
Console.WriteLine(point.AsText()); // POINT (23.5732, 25.3421)
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
string sampleTopoJsonPath = RunExamples.GetDataDir() + "sample.topojson";
StringBuilder builder = new StringBuilder();
using (VectorLayer layer = VectorLayer.Open(sampleTopoJsonPath, Drivers.TopoJson))
{
foreach (Feature feature in layer)
{
// get id property
int id = feature.GetValue<int>("id");
// get name of the object that contains this feature
string objectName = feature.GetValue<string>("topojson_object_name");
// get name attribute property, located inside 'properties' object
string name = feature.GetValue<string>("name");
// get geometry of the feature.
string geometry = feature.Geometry.AsText();
builder.AppendFormat("Feature with ID {0}:\n", id);
builder.AppendFormat("Object Name = {0}\n", objectName);
builder.AppendFormat("Name = {0}\n", name);
builder.AppendFormat("Geometry = {0}\n", geometry);
}
}
Console.WriteLine("Output:");
Console.WriteLine(builder.ToString());
// Output:
// Feature with ID 0:
// Object Name = named_object_1
// Name = point_feature
// Geometry = POINT (102 0.5)
// Feature with ID 1:
// Object Name = named_object_1
// Name = line_feature
// Geometry = LINESTRING (102 0, 103 1, 104 0, 105 1)
// Feature with ID 2:
// Object Name = named_object_2
// Name = polygon_feature
// Geometry = POLYGON ((100 0, 100 1, 101 1, 101 0, 100 0))
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
// -- copy test dataset, to avoid modification of test data.
var path = RunExamples.GetDataDir() + "ThreeLayers.gdb";
var datasetPath = RunExamples.GetDataDir() + "AddLayerToFileGdbDataset_out.gdb";
RunExamples.CopyDirectory(path, datasetPath);
// --
using (var dataset = Dataset.Open(datasetPath, Drivers.FileGdb))
{
Console.WriteLine(dataset.CanCreateLayers); // True
using (var layer = dataset.CreateLayer("data", SpatialReferenceSystem.Wgs84))
{
layer.Attributes.Add(new FeatureAttribute("Name", AttributeDataType.String));
var feature = layer.ConstructFeature();
feature.SetValue("Name", "Name_1");
feature.Geometry = new Point(12.21, 23.123, 20, -200);
layer.Add(feature);
}
using (var layer = dataset.OpenLayer("data"))
{
Console.WriteLine(layer.Count); // 1
Console.WriteLine(layer[0].GetValue<string>("Name")); // "Name_1"
}
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
var geoJsonPath = RunExamples.GetDataDir() + "ConvertGeoJsonLayerToLayerInFileGdbDataset_out.json";
using (VectorLayer layer = VectorLayer.Create(geoJsonPath, Drivers.GeoJson))
{
layer.Attributes.Add(new FeatureAttribute("name", AttributeDataType.String));
layer.Attributes.Add(new FeatureAttribute("age", AttributeDataType.Integer));
Feature firstFeature = layer.ConstructFeature();
firstFeature.Geometry = new Point(33.97, -118.25);
firstFeature.SetValue("name", "John");
firstFeature.SetValue("age", 23);
layer.Add(firstFeature);
Feature secondFeature = layer.ConstructFeature();
secondFeature.Geometry = new Point(35.81, -96.28);
secondFeature.SetValue("name", "Mary");
secondFeature.SetValue("age", 54);
layer.Add(secondFeature);
}
// --
// -- copy test dataset, to avoid modification of test data.
var sourceFile = RunExamples.GetDataDir() + "ThreeLayers.gdb";
var destinationFile = RunExamples.GetDataDir() + "ThreeLayersCopy_out.gdb";
RunExamples.CopyDirectory(sourceFile, destinationFile);
// --
using (var geoJsonLayer = VectorLayer.Open(geoJsonPath, Drivers.GeoJson))
{
using (var fileGdbDataset = Dataset.Open(destinationFile, Drivers.FileGdb))
using (var fileGdbLayer = fileGdbDataset.CreateLayer("new_layer", SpatialReferenceSystem.Wgs84))
{
fileGdbLayer.CopyAttributes(geoJsonLayer);
foreach (var feature in geoJsonLayer)
{
fileGdbLayer.Add(feature);
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
using (VectorLayer source = VectorLayer.Open(dataDir + "PolygonShapeFile.shp", Drivers.Shapefile))
{
using (VectorLayer destination = VectorLayer.Create(dataDir + "PolygonShapeFileToLineShapeFile_out.shp", Drivers.Shapefile))
{
foreach (Feature sourceFeature in source)
{
Polygon polygon = (Polygon)sourceFeature.Geometry;
LineString line = new LineString(polygon.ExteriorRing);
Feature destinationFeature = destination.ConstructFeature();
destinationFeature.Geometry = line;
destination.Add(destinationFeature);
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
Console.WriteLine(Drivers.FileGdb.CanCreateDatasets); // True
var path = RunExamples.GetDataDir() + "CreateFileGdbDataset_out.gdb";
using (var dataset = Dataset.Create(path, Drivers.FileGdb))
{
Console.WriteLine(dataset.LayersCount); // 0
using (var layer = dataset.CreateLayer("layer_1"))
{
layer.Attributes.Add(new FeatureAttribute("value", AttributeDataType.Integer));
for (int i = 0; i < 10; ++i)
{
var feature = layer.ConstructFeature();
feature.SetValue("value", i);
feature.Geometry = new Point(i, i);
layer.Add(feature);
}
}
using (var layer = dataset.CreateLayer("layer_2"))
{
var feature = layer.ConstructFeature();
feature.Geometry = new LineString(new[]
{
new Point(1, 2),
new Point(3, 4),
});
layer.Add(feature);
}
Console.WriteLine(dataset.LayersCount); // 2
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
var path = RunExamples.GetDataDir() + "CreateFileGdbDatasetWithSingleLayer_out.gdb";
var options = new FileGdbOptions();
using (var layer = VectorLayer.Create(path, Drivers.FileGdb, options, SpatialReferenceSystem.Wgs84))
// this 'using' is equivalent to
// using (var dataset = Dataset.Create(path, Drivers.FileGdb))
// using (var layer = Dataset.CreateLayer("layer"))
{
var feature = layer.ConstructFeature();
feature.Geometry = new LineString(new[]
{
new Point(1, 2),
new Point(3, 4),
});
layer.Add(feature);
}
using (var dataset = Dataset.Open(path, Drivers.FileGdb))
using (var layer = dataset.OpenLayer("layer"))
{
Console.WriteLine("Features count: {0}", layer.Count); // 1
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
using (var layer = Drivers.Kml.CreateLayer(dataDir + "Kml_File_out.kml"))
{
layer.Attributes.Add(new FeatureAttribute("string_data", AttributeDataType.String));
layer.Attributes.Add(new FeatureAttribute("int_data", AttributeDataType.Integer));
layer.Attributes.Add(new FeatureAttribute("bool_data", AttributeDataType.Boolean));
layer.Attributes.Add(new FeatureAttribute("float_data", AttributeDataType.Double));
Feature feature = layer.ConstructFeature();
feature.SetValue("string_data", "string value");
feature.SetValue("int_data", 10);
feature.SetValue("bool_data", true);
feature.SetValue("float_data", 3.14);
feature.Geometry = new LineString(new[] { new Point(0, 0), new Point(1, 1) });
layer.Add(feature);
Feature feature2 = layer.ConstructFeature();
feature2.SetValue("string_data", "string value2");
feature2.SetValue("int_data", 100);
feature2.SetValue("bool_data", false);
feature2.SetValue("float_data", 3.1415);
feature2.Geometry = Geometry.Null;
layer.Add(feature2);
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
using (VectorLayer layer = VectorLayer.Create(dataDir + "NewShapeFile_out.shp", Drivers.Shapefile))
{
// add attributes before adding features
layer.Attributes.Add(new FeatureAttribute("name", AttributeDataType.String));
layer.Attributes.Add(new FeatureAttribute("age", AttributeDataType.Integer));
layer.Attributes.Add(new FeatureAttribute("dob", AttributeDataType.DateTime));
// case 1: sets values
Feature firstFeature = layer.ConstructFeature();
firstFeature.Geometry = new Point(33.97, -118.25);
firstFeature.SetValue("name", "John");
firstFeature.SetValue("age", 23);
firstFeature.SetValue("dob", new DateTime(1982, 2,5, 16, 30,0));
layer.Add(firstFeature);
Feature secondFeature = layer.ConstructFeature();
secondFeature.Geometry = new Point(35.81, -96.28);
secondFeature.SetValue("name", "Mary");
secondFeature.SetValue("age", 54);
secondFeature.SetValue("dob", new DateTime(1984, 12, 15, 15, 30, 0));
layer.Add(secondFeature);
// case 2: sets new values for all of the attributes.
Feature thirdFeature = layer.ConstructFeature();
secondFeature.Geometry = new Point(34.81, -92.28);
object[] data = new object[3] {"Alex", 25, new DateTime(1989, 4, 15, 15, 30, 0)};
secondFeature.SetValues(data);
layer.Add(thirdFeature);
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
var parameters = new ProjectedSpatialReferenceSystemParameters
{
Name = "WGS 84 / World Mercator",
Base = SpatialReferenceSystem.Wgs84,
ProjectionMethodName = "Mercator_1SP",
LinearUnit = Unit.Meter,
XAxis = new Axis("Easting", AxisDirection.East),
YAxis = new Axis("Northing", AxisDirection.North),
AxisesOrder = ProjectedAxisesOrder.XY,
};
parameters.AddProjectionParameter("central_meridian", 0);
parameters.AddProjectionParameter("scale_factor", 1);
parameters.AddProjectionParameter("false_easting", 0);
parameters.AddProjectionParameter("false_northing", 0);
var projectedSrs = SpatialReferenceSystem.CreateProjected(parameters, Identifier.Epsg(3395));
using (var layer = Drivers.Shapefile.CreateLayer(dataDir + "filepath_out.shp", new ShapefileOptions(), projectedSrs))
{
var feature = layer.ConstructFeature();
feature.Geometry = new Point(1, 2);
layer.Add(feature);
feature = layer.ConstructFeature();
feature.Geometry = new Point(1, 2) { SpatialReferenceSystem = SpatialReferenceSystem.Nad83 };
try
{
layer.Add(feature); // geometry of feature has different SRS - exception is thrown
}
catch (GisException e)
{
Console.WriteLine(e.Message);
}
}
using (var layer = Drivers.Shapefile.OpenLayer(dataDir + "filepath_out.shp"))
{
var srsName = layer.SpatialReferenceSystem.Name; // "WGS 84 / World Mercator"
layer.SpatialReferenceSystem.IsEquivalent(projectedSrs); // true
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
using (var layer = Drivers.Kml.CreateLayer(dataDir + "Kml_Styles_out.kml"))
{
var style = new KmlFeatureStyle
{
Line = new KmlLineStyle() { Width = 2.0 },
Polygon = new KmlPolygonStyle() { Outline = false },
Icon = new KmlIconStyle() {Resource = new KmlIconResource() {Href = "url"}},
Label = new KmlLabelStyle() {Color = Color.Green},
Balloon = new KmlBalloonStyle() { BackgroundColor = Color.Aqua, Text = "Example" },
List = new KmlListStyle() { ItemType = KmlItemTypes.RadioFolder },
};
Feature feature = layer.ConstructFeature();
feature.Geometry = new LineString(new[] { new Point(0, 0), new Point(1, 1) });
layer.Add(feature, style);
Feature feature2 = layer.ConstructFeature();
feature2.Geometry = new Point(5, 5);
layer.Add(feature2, style);
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
using (VectorLayer inputLayer = VectorLayer.Open(dataDir + "InputShapeFile.shp", Drivers.Shapefile))
{
using (VectorLayer outputLayer = VectorLayer.Create(dataDir + "ExtractFeaturesFromShapeFileToGeoJSON_out.json", Drivers.GeoJson))
{
outputLayer.CopyAttributes(inputLayer);
foreach (Feature inputFeature in inputLayer)
{
DateTime? date = inputFeature.GetValue<DateTime?>("dob");
if (date == null || date < new DateTime(1982, 1, 1))
{
continue;
}
//Construct a new feature
Feature outputFeature = outputLayer.ConstructFeature();
outputFeature.Geometry = inputFeature.Geometry;
outputFeature.CopyValues(inputFeature);
outputLayer.Add(outputFeature);
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
using (VectorLayer layer = VectorLayer.Open(dataDir + "InputShapeFile.shp", Drivers.Shapefile))
{
// all features with the date value in the attribute "dob" later than 1982-01-01.
foreach (Feature feature in layer.WhereGreater("dob", new DateTime(1982, 1, 1, 0, 0, 0)))
{
Console.WriteLine(feature.GetValue<DateTime>("dob").ToShortDateString());
}
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
using (var layer = VectorLayer.Open(path, Drivers.Shapefile))
{
// Use index files to speed up filtering by attribute's value or spatial extent.
var attributeIndexPath = Path.ChangeExtension(path, "sov_a3_out.ix");
layer.UseAttributesIndex(attributeIndexPath, "sov_a3");
var spatialIndexPath = Path.ChangeExtension(path, ".spatial_out.ix");
layer.UseSpatialIndex(spatialIndexPath);
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
var path = DataDir + "temp_out.shp";
// -- generate sample data
var values = new (string name, int age)[]
{
("Anna", 12),
("John", 15),
("Mary", 20),
("James", 10),
("Bob", 19),
("Fred", 1),
("Alex", 14),
};
using (var layer = VectorLayer.Create(path, Drivers.Shapefile))
{
layer.Attributes.Add(new FeatureAttribute("name", AttributeDataType.String));
layer.Attributes.Add(new FeatureAttribute("age", AttributeDataType.Integer));
foreach (var (name, age) in values)
{
var feature = layer.ConstructFeature();
feature.SetValue("name", name);
feature.SetValue("age", age);
layer.Add(feature);
}
}
// --
using (var layer = VectorLayer.Open(path, Drivers.Shapefile))
{
// Use index files to speed up filtering by attribute's value.
// Index is automatically created if it doesn't exist. Any path can be used.
var nameIndexPath = Path.ChangeExtension(path, "name_out.ux");
var ageIndexPath = Path.ChangeExtension(path, "age_out.ix");
layer.UseAttributesIndex(nameIndexPath, "name");
layer.UseAttributesIndex(ageIndexPath, "age");
// Select features with 'age' in range [13, 19]
var teens = layer.WhereGreater("age", 12).WhereSmallerOrEqual("age", 19);
foreach (var feature in teens)
{
Console.WriteLine(feature.GetValue<string>("name"));
}
// Select features with 'name' that starts with 'A' and 'age' greater than '12'.
var firstInAlphabet = layer.WhereGreaterOrEqual("name", "A")
.WhereSmaller("name", "B")
.WhereGreater("age", 12);
foreach (var feature in firstInAlphabet)
{
Console.WriteLine(feature.GetValue<string>("name"));
}
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
using (var layer = VectorLayer.Open(citiesPath, Drivers.GeoJson))
{
// Select features based on values of the attribute. This code enumerates all features in the layer
// and selects all features that match a condition.
var features = layer.WhereGreaterOrEqual("population", 2000).WhereSmaller("population", 5000);
// Print results.
Console.WriteLine("Cities where population >= 2000 and population < 5000:");
foreach (var feature in features)
{
var name = feature.GetValue<string>("name");
var population = feature.GetValue<int>("population");
Console.WriteLine(name + ", " + population);
}
Console.WriteLine();
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
using (var layer = VectorLayer.Open(path, Drivers.GeoJson))
{
// Use spatial index to speed up spatial queries.
// Aspose.GIS builds a new index if it doesn't exist, otherwise existing index is reused.
// Any path can be used.
var spatialIndexPath = Path.ChangeExtension(path, ".spatial_out.ix");
layer.UseSpatialIndex(spatialIndexPath);
var point = new Point(12.30, 50.33);
// Since we use spatial index, nearest-to finds the closest feature much faster.
var nearest = layer.NearestTo(point);
Console.WriteLine("City nearest to (12.30 50.33) is " + nearest.GetValue<string>("name"));
Console.WriteLine();
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
using (var layer = VectorLayer.Open(path, Drivers.GeoJson))
{
// Use spatial index to speed up 'WhereIntersects'.
var spatialIndexPath = Path.ChangeExtension(path, ".spatial_out.ix");
layer.UseSpatialIndex(spatialIndexPath);
var polygon = Geometry.FromText("Polygon((12.30 50.33, 22.49 54.87, 21.92 42.53, 12.30 50.33))");
var intersecting = layer.WhereIntersects(polygon);
Console.WriteLine("Cities within " + polygon.AsText() + ":");
foreach (var feature in intersecting)
{
var name = feature.GetValue<string>("name");
var location = (IPoint) feature.Geometry;
Console.WriteLine($"{name} at ({location.X}, {location.Y})");
}
Console.WriteLine();
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
using (var layer = VectorLayer.Open(citiesPath, Drivers.GeoJson))
{
// Use attribute index to speed up search by 'population' attribute.
// Aspose.GIS builds a new index if it doesn't exist, otherwise existing index is reused.
// Any path can be used.
var attributeIndexPath = Path.ChangeExtension(citiesPath, "population_out.ix");
layer.UseAttributesIndex(attributeIndexPath, "population");
// Select features based on values of the attribute. Since we use attribute index it is not necessary to
// test all features of the layer and filtering time is reduced significantly.
var towns = layer.WhereGreaterOrEqual("population", 2000).WhereSmaller("population", 5000);
// Print results.
Console.WriteLine("Cities where population >= 2000 and population < 5000:");
foreach (var town in towns)
{
var name = town.GetValue<string>("name");
var population = town.GetValue<int>("population");
Console.WriteLine(name + ", " + population);
}
Console.WriteLine();
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
using (var map = new Map(600, 400))
using (var cities = VectorLayer.Open(citiesPath, Drivers.GeoJson))
{
map.Padding = 20;
// Use attribute index to speed up search by 'population' attribute.
var attributeIndexPath = Path.ChangeExtension(citiesPath, "population_out.ix");
cities.UseAttributesIndex(attributeIndexPath, "population");
// Render all cities with population greater than 2000.
map.Add(cities.WhereGreater("population", 2000), new SimpleMarker { FillColor = Color.Red });
map.Render(outputPath, Renderers.Svg);
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
using (var layer = VectorLayer.Open(citiesPath, Drivers.GeoJson))
{
// Use attribute index to speed up search by 'population' attribute.
var attributeIndexPath = Path.ChangeExtension(citiesPath, "population_out.ix");
layer.UseAttributesIndex(attributeIndexPath, "population");
// Save all features with population between 2000 and 5000 to the output file.
layer.WhereGreaterOrEqual("population", 2000)
.WhereSmaller("population", 5000)
.SaveTo(DataDir + "towns_out.shp", Drivers.Shapefile);
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
using (VectorLayer layer = VectorLayer.Open(dataDir + "InputShapeFile.shp", Drivers.Shapefile))
{
Console.WriteLine("Total Features in this file: " + layer.Count);
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
using (VectorLayer layer = VectorLayer.Open(dataDir + "InputShapeFile.shp", Drivers.Shapefile))
{
Console.WriteLine("The layer has {0} attributes defined.\n", layer.Attributes.Count);
foreach (FeatureAttribute attribute in layer.Attributes)
{
Console.WriteLine("Name: {0}", attribute.Name);
Console.WriteLine("Data type: {0}", attribute.DataType);
Console.WriteLine("Can be null: {0}", attribute.CanBeNull);
}
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
using (VectorLayer layer = VectorLayer.Open(dataDir + "InputShapeFile.shp", Drivers.Shapefile))
{
for (int i = 0; i < layer.Count; i++)
{
Feature feature = layer[i];
Console.WriteLine("Entry {0} information\n ========================", i);
// case 1
string nameValue = feature.GetValue<string>("name"); // attribute name is case-sensitive
int ageValue = feature.GetValue<int>("age");
string dobValue = feature.GetValue<DateTime>("dob").ToString();
Console.WriteLine("Attribute value for feature #{0} is: {1}, {2}", nameValue, ageValue, dobValue);
// case 2
var objName = feature.GetValue("name"); // attribute name is case-sensitive
var objAge = feature.GetValue("age");
var objDob = feature.GetValue("dob");
Console.WriteLine("Attribute object for feature #{0} is: {1}, {2}", objName, objAge, objDob);
}
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
using (VectorLayer layer = VectorLayer.Open(dataDir + "InputShapeFile.shp", Drivers.Shapefile))
{
int index = 0;
foreach (Feature feature in layer)
{
DateTime? date = feature.GetValue<DateTime?>("dob");
Console.WriteLine("Feature #{0}", index);
Console.WriteLine("\tAttribute value present: {0}", date.HasValue);
if (date.HasValue)
{
Console.WriteLine("\tAttribute value: {0}", date.Value);
}
index++;
}
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
//You can set default value for a feature of attribute in a layer
using (var layer = Drivers.GeoJson.CreateLayer(dataDir + "data1_out.json"))
{
var attribute = new FeatureAttribute("attribute", AttributeDataType.Integer);
attribute.CanBeNull = true;
attribute.CanBeUnset = true;
layer.Attributes.Add(attribute);
Feature feature = layer.ConstructFeature();
int? nullValue = feature.GetValueOrDefault<int?>("attribute"); // value == null
var defValue1 = feature.GetValueOrDefault<int?>("attribute", 10); // value == 10
var defValue2 = feature.GetValueOrDefault("attribute", 25); // value == 10
Console.WriteLine($"'{nullValue}' vs '{defValue1}' vs '{defValue2}'");
}
//Another example where we set the default value to 100
using (var layer = Drivers.GeoJson.CreateLayer(dataDir + "data2_out.json"))
{
var attribute = new FeatureAttribute("attribute", AttributeDataType.Double);
attribute.CanBeNull = false;
attribute.CanBeUnset = false;
attribute.DefaultValue = 100;
layer.Attributes.Add(attribute);
Feature feature = layer.ConstructFeature();
double defValue1 = feature.GetValueOrDefault<double>("attribute"); // value == 100
var defValue2 = feature.GetValueOrDefault("attribute"); // value == 100
feature.SetValue("attribute", 50);
var newValue = feature.GetValueOrDefault<double>("attribute"); // value == 50
Console.WriteLine($"'{defValue1}' vs '{defValue2}' vs '{newValue}'");
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
using (VectorLayer layer = VectorLayer.Open(dataDir + "InputShapeFile.shp", Drivers.Shapefile))
{
foreach (var feature in layer)
{
// reads all the attributes into an array.
object[] all = new object[3];
feature.GetValues(all);
Console.WriteLine("all : {0}, {1}, {2}", all);
// reads several the attributes into an array.
object[] several = new object[2];
feature.GetValues(several);
Console.WriteLine("several: {0}, {1}", several);
// reads the attributes as dump of objects.
var dump = feature.GetValuesDump();
Console.WriteLine("dump : {0}, {1}, {2}", dump);
Console.WriteLine();
}
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
// First, we create the connection to the PostgreSQL with Npgsql library (https://www.nuget.org/packages/Npgsql/)
using (var connection = new NpgsqlConnection(postgreSqlConnectionString))
{
connection.Open();
// Then, we pass this connection to Dataset.Open method in order to access tables in the PostgreSQL.
using (var ds = Dataset.Open(connection, Drivers.PostGis))
{
// create table with the name "features_table" and fill it with data.
using (var layer = ds.CreateLayer("features_table"))
{
layer.Attributes.Add(new FeatureAttribute("name", AttributeDataType.String) { Width = 50 });
var feature = layer.ConstructFeature();
feature.SetValue("name", "Name1");
feature.Geometry = Geometry.FromText("POINT (10 20 30)");
layer.Add(feature);
feature = layer.ConstructFeature();
feature.SetValue("name", "Name2");
feature.Geometry = Geometry.FromText("POINT (-10 -20 -30)");
layer.Add(feature);
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
var outputPath = Path.Combine(RunExamples.GetDataDir(), "postgres_out.shp");
// First, we create the connection to the PostgreSQL with Npgsql library (https://www.nuget.org/packages/Npgsql/)
// Then, we pass this connection to Dataset.Open method in order to access tables in the PostgreSQL.
using (var connection = new NpgsqlConnection(postgreSqlConnectionString))
{
connection.Open();
using (var ds = Dataset.Open(connection, Drivers.PostGis))
{
// open table with the name "features_table" in Postgres database and save it to the shapefile.
using (var table = ds.OpenLayer("features_table"))
{
table.SaveTo(outputPath, Drivers.Shapefile);
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
// First, we create the connection to the PostgreSQL with Npgsql library (https://www.nuget.org/packages/Npgsql/)
// Then, we pass this connection to Dataset.Open method in order to access tables in the PostgreSQL.
using (var connection = new NpgsqlConnection(postgreSqlConnectionString))
{
connection.Open();
using (var ds = Dataset.Open(connection, Drivers.PostGis))
{
// Only spatial tables are exported as layers, so the following code will list all tables
// that have geometry column.
for (int i = 0; i < ds.LayersCount; ++i)
{
Console.WriteLine(ds.GetLayerName(i));
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
string filesPath = RunExamples.GetDataDir();
using (var layer = Drivers.GeoTiff.OpenLayer(Path.Combine(filesPath, "raster50x50.tif")))
{
// get all values
var dump = layer.GetValuesDump(layer.Bounds);
// use LINQ
// we compute cells count where values in all bands are 'no data'
var nodataCount = dump.Count(t => t.EqualsNoData(0) && t.EqualsNoData(1) && t.EqualsNoData(2));
// we compute cells count where values like a blue color (<35, <35, >235)
var likeBlueCount = dump.Count(t => t[0] < 35 && t[1] < 35 && t[2] > 235);
Console.WriteLine("");
Console.WriteLine("we use LINQ ");
Console.WriteLine($"no data count: {nodataCount}");
Console.WriteLine($"like blue color count: {likeBlueCount}");
// we use the 'GetValuesOnExpression' method to avoid additional memory allocation.
var nodata = 0;
var likeBlue = 0;
layer.GetValuesOnExpression(layer.Bounds, (context, values) =>
{
if (values.EqualsNoData(0) && values.EqualsNoData(1) && values.EqualsNoData(2))
nodata++;
if (values[0] < 35 && values[1] < 35 && values[2] > 235)
likeBlue++;
});
Console.WriteLine("");
Console.WriteLine("we use the 'GetValuesOnExpression' ");
Console.WriteLine($"no data counter: {nodata}");
Console.WriteLine($"like blue color counter: {likeBlue}");
}
// For complete examples and data files, please go to https://github.com/aspose-gis/Aspose.GIS-for-.NET
string filesPath = RunExamples.GetDataDir();
using (var layer = Drivers.GeoTiff.OpenLayer(Path.Combine(filesPath, "raster50x50.tif")))
{
// read and print raster
var cellSize = layer.CellSize;
var extent = layer.GetExtent();