public void Test() { var features = new List<Features.IFeature>(); var seq = DotSpatialAffineCoordinateSequenceFactory.Instance.Create(1, Ordinates.XY); seq.SetOrdinate(0, Ordinate.X, -91.0454); seq.SetOrdinate(0, Ordinate.Y, 32.5907); var pt = new GeometryFactory(DotSpatialAffineCoordinateSequenceFactory.Instance).CreatePoint(seq); var attr = new Features.AttributesTable(); attr.AddAttribute("FirstName", "John"); attr.AddAttribute("LastName", "Doe"); features.Add(new Features.Feature(pt, attr)); var fileName = Path.GetTempFileName(); fileName = fileName.Substring(0, fileName.Length - 4); var shpWriter = new ShapefileDataWriter(fileName, features[0].Geometry.Factory) { Header = ShapefileDataWriter.GetHeader(features[0], features.Count) }; shpWriter.Write(features); bool isTrue; using (var reader = new ShapefileDataReader(fileName, pt.Factory)) @isTrue = reader.ShapeHeader.ShapeType.ToString() == "Point"; foreach (var file in Directory.GetFiles(Path.GetTempPath(), Path.GetFileName(fileName) + ".*" )) { File.Delete(file); } Assert.IsTrue(@isTrue); }
/// <summary> /// /// </summary> /// <param name="fileName"></param> /// <returns></returns> private static IGeometry CheckShapefile(string fileName) { //int count = 0; var geoms = new List<IGeometry>(); using (ShapefileDataReader reader = new ShapefileDataReader(fileName, GeometryFactory.Floating)) { while (reader.Read()) { IGeometry current = reader.Geometry; if (!current.IsValid) { Debug.WriteLine("Imvalid geometry found: " + current); continue; } geoms.Add(current); //if (result == null) // result = current; //else result = result.Union(current); //Debug.WriteLine("Iteration => " + ++count); } } IGeometry result = UnaryUnionOp.Union(geoms); var write = new WKTWriter {Formatted = true, MaxCoordinatesPerLine = 3, Tab = 2}; Debug.WriteLine("Operation result: " + write.Write(result)); return result; }
private void TestWriteZMValuesShapeFile(bool testM) { var points = new Coordinate[3]; points[0] = new Coordinate(0, 0); points[1] = new Coordinate(1, 0); points[2] = new Coordinate(1, 1); var csFactory = NetTopologySuite.Geometries.Implementation.DotSpatialAffineCoordinateSequenceFactory.Instance; var sequence = csFactory.Create(3, Ordinates.XYZM); for (var i = 0; i < 3; i ++) { sequence.SetOrdinate(i, Ordinate.X, points[i].X); sequence.SetOrdinate(i, Ordinate.Y, points[i].Y); sequence.SetOrdinate(i, Ordinate.Z, 1 + i); if (testM) sequence.SetOrdinate(i, Ordinate.M, 11 + i); } var lineString = Factory.CreateLineString(sequence); var attributes = new AttributesTable(); attributes.AddAttribute("FOO", "Trond"); var feature = new Feature(Factory.CreateMultiLineString(new[] { lineString }), attributes); var features = new Feature[1]; features[0] = feature; var shpWriter = new ShapefileDataWriter("ZMtest", Factory) { Header = ShapefileDataWriter.GetHeader(features[0], features.Length) }; shpWriter.Write(features); // Now let's read the file and verify that we got Z and M back var factory = new GeometryFactory(NetTopologySuite.Geometries.Implementation.DotSpatialAffineCoordinateSequenceFactory.Instance); using (var reader = new ShapefileDataReader("ZMtest", factory)) { reader.Read(); var geom = reader.Geometry; for (var i = 0; i < 3; i++) { var c = geom.Coordinates[i]; Assert.AreEqual(i + 1, c.Z); } if (testM) { sequence = ((ILineString) geom).CoordinateSequence; for (var i = 0; i < 3; i++) { Assert.AreEqual(sequence.GetOrdinate(i, Ordinate.M), 11 + i); } } // Run a simple attribute test too var v = reader.GetString(0); Assert.AreEqual(v, "Trond"); } }
private IEnumerable<KeyValuePair<string, IGeometry>> ReadShapes(string filePath, string nameColumnIdentifier) { using (var reader = new ShapefileDataReader(filePath, GeometryFactory.Default)) { while (reader.Read()) { yield return new KeyValuePair<string, IGeometry>((string)reader[nameColumnIdentifier], reader.Geometry); } } }
public override void Open() { if (IsOpened) throw new Exception(string.Format("Cannot open before to close the resource {0}", Path)); if (string.IsNullOrEmpty(Path)) throw new Exception("Cannot open a null or empty path"); #if USE_SFDR reader = Shapefile.CreateDataReader(Path, new GeometryFactory()); var s1 = reader.ShapeHeader; var h = reader.DbaseHeader; #else var shpReader = new ShapefileReader(Path); shpProvider = shpReader.GetEnumerator(); var dbfReader = new DbaseFileReader(IoManager.File.ChangeExtension(Path, ".dbf")); var h = dbfReader.GetHeader(); dbfProvider = dbfReader.GetEnumerator(); #endif foreach (var f in h.Fields) { var lf = new LayerField(); lf.Name = f.Name; switch (f.DbaseType) { case 'L': // logical data type, one character (T,t,F,f,Y,y,N,n) lf.FieldType = GisFieldType.GisFieldTypeBoolean; break; case 'C': // char or string lf.FieldType = GisFieldType.GisFieldTypeString; break; case 'D': // date lf.FieldType = GisFieldType.GisFieldTypeDate; break; case 'N': // numeric if (f.DecimalCount > 0) lf.FieldType = GisFieldType.GisFieldTypeFloat; else lf.FieldType = GisFieldType.GisFieldTypeNumber; break; case 'F': // double lf.FieldType = GisFieldType.GisFieldTypeNumber; break; default: throw new NotSupportedException("Do not know how to parse Field type " + f.DbaseType); } Fields.Add(lf); } }
public void TestIssue175_ReadingShapeFileUsingShpExtension() { using (ShapefileDataReader reader = new ShapefileDataReader("crustal_test.shp", Factory)) { int length = reader.DbaseHeader.NumFields; while (reader.Read()) { Debug.WriteLine(reader.GetValue(length - 1)); } } }
public void TestReadingAaaShapeFile() { using (ShapefileDataReader reader = new ShapefileDataReader("aaa", Factory)) { int length = reader.DbaseHeader.NumFields; while (reader.Read()) { Debug.WriteLine(reader.GetValue(length - 1)); } } Assert.Fail(); }
public void TestLoadShapeFileWithEncoding() { ShapefileDataReader reader = new ShapefileDataReader("encoding_sample.shp", GeometryFactory.Default); DbaseFileHeader header = reader.DbaseHeader; Assert.AreEqual(header.Encoding.WindowsCodePage, 1252, "Invalid encoding!"); Assert.AreEqual(header.Fields[1].Name, "Test"); Assert.AreEqual(header.Fields[2].Name, "Ålder"); Assert.AreEqual(header.Fields[3].Name, "Ödestext"); Assert.IsTrue(reader.Read(), "Error reading file"); Assert.AreEqual(reader["Test"], "Testar"); Assert.AreEqual(reader["Ödestext"], "Lång text med åäö etc"); }
public static ShapefileDataReader CreateDataReader(IStreamProviderRegistry streamProviderRegistry, GeometryFactory geometryFactory) { if (streamProviderRegistry == null) { throw new ArgumentNullException("streamProviderRegistry"); } if (geometryFactory == null) { throw new ArgumentNullException("geometryFactory"); } var shpDataReader = new ShapefileDataReader(streamProviderRegistry, geometryFactory); return(shpDataReader); }
public void TestReadingShapeFileWithNulls() { using (ShapefileDataReader reader = new ShapefileDataReader("AllNulls", Factory)) { while (reader.Read()) { IGeometry geom = reader.Geometry; Assert.IsNotNull(geom); object[] values = new object[5]; int result = reader.GetValues(values); Assert.IsNotNull(values); } } }
/// <summary> /// Creates a DataTable representing the information in a shape file. /// </summary> /// <param name="filename">The filename (minus the . and extension) to read.</param> /// <param name="tableName">The name to give to the table.</param> /// <param name="geometryFactory">The geometry factory to use when creating the objects.</param> /// <returns>DataTable representing the data </returns> public static DataTable CreateDataTable(string filename, string tableName, GeometryFactory geometryFactory) { if (filename == null) throw new ArgumentNullException("filename"); if (tableName == null) throw new ArgumentNullException("tableName"); if (geometryFactory == null) throw new ArgumentNullException("geometryFactory"); ShapefileDataReader shpfileDataReader = new ShapefileDataReader(filename, geometryFactory); DataTable table = new DataTable(tableName); // use ICustomTypeDescriptor to get the properies/ fields. This way we can get the // length of the dbase char fields. Because the dbase char field is translated into a string // property, we lost the length of the field. We need to know the length of the // field when creating the table in the database. IEnumerator enumerator = shpfileDataReader.GetEnumerator(); bool moreRecords = enumerator.MoveNext(); ICustomTypeDescriptor typeDescriptor = (ICustomTypeDescriptor)enumerator.Current; foreach (PropertyDescriptor property in typeDescriptor.GetProperties()) { ColumnStructure column = (ColumnStructure)property; Type fieldType = column.PropertyType; DataColumn datacolumn = new DataColumn(column.Name, fieldType); if (fieldType == typeof(string)) // use MaxLength to pass the length of the field in the dbase file datacolumn.MaxLength = column.Length; table.Columns.Add(datacolumn); } // add the rows - need a do-while loop because we read one row in order to determine the fields int iRecordCount = 0; object[] values = new object[shpfileDataReader.FieldCount]; do { iRecordCount++; shpfileDataReader.GetValues(values); table.Rows.Add(values); moreRecords = enumerator.MoveNext(); } while (moreRecords); return table; }
public void BuildStradeFixed() { var path = "strade" + shp; Assert.IsTrue(File.Exists(path)); var reader = new ShapefileDataReader(path, factory); var features = new List<IFeature>(reader.RecordCount); while (reader.Read()) { var feature = new Feature(reader.Geometry, new AttributesTable()); var values = new object[reader.FieldCount - 1]; reader.GetValues(values); for (var i = 0; i < values.Length; i++) { var name = reader.GetName(i + 1); var value = values[i]; feature.Attributes.AddAttribute(name, value); } features.Add(feature); } Assert.AreEqual(703, features.Count); var shapepath = "strade_fixed"; if (File.Exists(shapepath + shp)) File.Delete(shapepath + shp); Assert.IsFalse(File.Exists(shapepath + shp)); if (File.Exists(shapepath + shx)) File.Delete(shapepath + shx); Assert.IsFalse(File.Exists(shapepath + shx)); if (File.Exists(shapepath + dbf)) File.Delete(shapepath + dbf); Assert.IsFalse(File.Exists(shapepath + dbf)); var header = reader.DbaseHeader; var writer = new ShapefileDataWriter(shapepath, factory) {Header = header}; writer.Write(features); Assert.IsTrue(File.Exists(shapepath + shp)); Assert.IsTrue(File.Exists(shapepath + shx)); Assert.IsTrue(File.Exists(shapepath + dbf)); }
public void TestReadingCrustalTestShapeFile() { // Original file with characters '°' in NAME field. using (ShapefileDataReader reader = new ShapefileDataReader("crustal_test_bugged", Factory)) { int length = reader.DbaseHeader.NumFields; while (reader.Read()) { Debug.WriteLine(reader.GetValue(length - 1)); } } // Removed NAME field characters using (ShapefileDataReader reader = new ShapefileDataReader("crustal_test", Factory)) { int length = reader.DbaseHeader.NumFields; while (reader.Read()) { Debug.WriteLine(reader.GetValue(length - 1)); } } }
public void TestIssue161() { var testFileDataDirectory = Path.Combine( AppDomain.CurrentDomain.BaseDirectory, string.Format("..{0}..{0}..{0}NetTopologySuite.Samples.Shapefiles", Path.DirectorySeparatorChar)); //SETUP var filePath = Path.Combine(testFileDataDirectory, "LSOA_2011_EW_BGC.shp"); if (!File.Exists(filePath)) Assert.Ignore("File '{0}' not present", filePath); //ATTEMPT using (var reader = new ShapefileDataReader(filePath, GeometryFactory.Default)) { var header = reader.ShapeHeader; while (reader.Read())//&& count++ < 3) { object val; Assert.DoesNotThrow(()=> val = reader["LSOA11CD"]); } } }
/// <summary> /// Returns MarkerType property for legend. /// </summary> /// <param name="colorRepo"></param> /// <param name="resultDir"></param> /// <param name="fi"></param> /// <param name="resultName"></param> /// <returns></returns> private static void ProcessVectorFile(IColorRepository colorRepo, DirectoryInfo resultDir, FileInfo fi, string resultName) { string localFileName = fi.Name; string localResultName = resultName; Console.WriteLine(string.Format("Processing {0} into {1}...", localFileName, localResultName)); StringBuilder bldr = new StringBuilder(); NetTopologySuite.IO.ShapefileDataReader dataReader = new NetTopologySuite.IO.ShapefileDataReader(fi.FullName, new GeometryFactory()); NetTopologySuite.Features.FeatureCollection featureCollection = new NetTopologySuite.Features.FeatureCollection(); List<string> csvHdr = dataReader.DbaseHeader.Fields.Select(a => a.Name).ToList(); csvHdr.Add(appColorNamspace); bldr.AppendLine(string.Join(",", csvHdr)); //write csv file header while (dataReader.Read()) { NetTopologySuite.Features.Feature feature = new NetTopologySuite.Features.Feature(); feature.Geometry = dataReader.Geometry; int numFields = dataReader.DbaseHeader.NumFields + 1; string[] keys = new string[numFields]; int colorValueField = -1; for (int i = 0; i < numFields - 1; i++) { keys[i] = dataReader.DbaseHeader.Fields[i].Name; if (keys[i].Equals(colorRepo.ColorFieldForOutput(localFileName, localResultName))) { colorValueField = i; } } //add attributes from source attribute table feature.Attributes = new AttributesTable(); List<string> csvLine = new List<string>(); for (int i = 0; i < numFields - 1; i++) { object val = dataReader.GetValue(i); feature.Attributes.AddAttribute(keys[i], val); csvLine.Add(val.ToString()); } if (colorRepo.MapColorsToThisResult(localFileName, localResultName)) { //mark outline colors in a different attribute than fill colors string colorNs = colorRepo.IsOutlinedNotFilled(localFileName, localResultName) ? appOutlineNamespace : appColorNamspace; keys[numFields - 1] = colorNs; //add additional attribute for color binding string hexClr = colorRepo.SingleColorForFile(localFileName, localResultName); //only path where colorValueField, i.e. ColorMap.clrField can be unpopulated. if (string.IsNullOrEmpty(hexClr) && colorValueField > -1) { if (colorRepo.IsCategoricalMap(localFileName, resultName)) { //categorical color map hexClr = colorRepo.ColorsOfValueInFile(localFileName, localResultName, dataReader.GetString(colorValueField)).HexColor; } else { //numerical range color map hexClr = colorRepo.ColorsOfValueInFile(localFileName, localResultName, dataReader.GetDouble(colorValueField)).HexColor; } } if (string.IsNullOrEmpty(hexClr)) // else if (string.IsNullOrEmpty(hexClr) && colorValueField < 0) { throw new NotSupportedException("Cannot color a file with no attributes to bind to and no single-color given."); } csvLine.Add(hexClr); feature.Attributes.AddAttribute(colorNs, hexClr); } bldr.AppendLine(string.Join(",", csvLine)); featureCollection.Add(feature); } GeoJsonWriter wtr = new GeoJsonWriter(); string layerJson = wtr.Write(featureCollection); File.WriteAllText(resultDir.FullName + localResultName, layerJson); File.WriteAllText(resultDir.FullName + localResultName.Replace(".json", ".csv"), bldr.ToString()); }
public bool ImportShapes(List<string> files, bool latlon, bool useShapeProps, bool useElev, bool elevFeet) { GeometryFactory factory; ShapefileDataReader shapeFileDataReader; ArrayList features; Feature feature; AttributesTable attributesTable; string[] keys; Geometry geometry; DbaseFieldDescriptor fldDescriptor; int polyCount = (int)dal.GetPolyCount(); GpsPoint gps; int index = 0; _Polygons = new Dictionary<string, TtPolygon>(); _Points = new List<TtPoint>(); List<TtPoint> tmpPoints = new List<TtPoint>(); try { foreach (string file in files) { //polyCount = 1; factory = new GeometryFactory(); shapeFileDataReader = new ShapefileDataReader(file, factory); DbaseFileHeader header = shapeFileDataReader.DbaseHeader; features = new ArrayList(); while (shapeFileDataReader.Read()) { feature = new Feature(); attributesTable = new AttributesTable(); keys = new string[header.NumFields]; geometry = (Geometry)shapeFileDataReader.Geometry; for (int i = 0; i < header.NumFields; i++) { fldDescriptor = header.Fields[i]; keys[i] = fldDescriptor.Name; attributesTable.AddAttribute(fldDescriptor.Name, shapeFileDataReader.GetValue(i)); } feature.Geometry = geometry; feature.Attributes = attributesTable; features.Add(feature); } bool areAllPoints = true; foreach (Feature feat in features) { if (feat.Geometry.GeometryType.ToLower() != "point") { areAllPoints = false; break; } } //if all features are points if (areAllPoints) { tmpPoints.Clear(); _Poly = new TtPolygon(1000 * polyCount + 10); _Poly.Name = Path.GetFileNameWithoutExtension(file); index = 0; foreach (Feature feat in features) { //if features is only a point there should only be 1 coord foreach (Coordinate coord in feat.Geometry.Coordinates) { gps = new GpsPoint(); gps.OnBnd = true; gps.Index = index; index++; gps.MetaDefCN = _Meta.CN; if (tmpPoints.Count > 0) gps.PID = PointNaming.NamePoint(tmpPoints.Last(), _Poly); else gps.PID = PointNaming.NameFirstPoint(_Poly); if (latlon) { double x,y; TtUtils.LatLontoUTM(coord.Y, coord.X, _Meta.Zone, out y, out x); gps.UnAdjX = x; gps.UnAdjY = y; } else { gps.UnAdjX = coord.X; gps.UnAdjY = coord.Y; } if (useElev) { if (coord.Z != double.NaN) { if (elevFeet) gps.UnAdjZ = TtUtils.ConvertToMeters(coord.Z, Unit.FEET_TENTH); else gps.UnAdjZ = coord.Z; } else gps.UnAdjZ = 0; } else gps.UnAdjZ = 0; gps.PolyCN = _Poly.CN; gps.PolyName = _Poly.Name; gps.GroupCN = Values.MainGroup.CN; gps.GroupName = Values.MainGroup.Name; tmpPoints.Add(gps); } _Points.AddRange(tmpPoints); } _Polygons.Add(_Poly.CN, _Poly); polyCount++; } else //else get points out of each features { int fidInc = 0; foreach (Feature feat in features) { tmpPoints.Clear(); _Poly = new TtPolygon(1000 * polyCount + 10); if (features.Count < 2) _Poly.Name = Path.GetFileNameWithoutExtension(file); else _Poly.Name = String.Format("{0}-{1}", fidInc++, Path.GetFileNameWithoutExtension(file)); #region Shape Desc Properties if (useShapeProps) { object[] objs = feat.Attributes.GetValues(); string[] names = feat.Attributes.GetNames(); string objv; for (int i = 0; i < feat.Attributes.Count; i++) { if (objs[i] is string) { objv = (string)objs[i]; if (objv.IsEmpty()) continue; switch (names[i].ToLower()) { case "description": case "comment": case "poly": if (_Poly.Description.IsEmpty()) _Poly.Description = objv; else _Poly.Description = String.Format("{0} | {1}", _Poly.Description, objv); break; case "name": case "unit": _Poly.Name = objv; break; } } } } #endregion index = 0; foreach (Coordinate coord in feat.Geometry.Coordinates) { gps = new GpsPoint(); gps.OnBnd = true; gps.Index = index; index++; gps.MetaDefCN = _Meta.CN; if (tmpPoints.Count > 0) gps.PID = PointNaming.NamePoint(tmpPoints.Last(), _Poly); else gps.PID = PointNaming.NameFirstPoint(_Poly); if (latlon) { double x, y; TtUtils.LatLontoUTM(coord.Y, coord.X, _Meta.Zone, out y, out x); gps.UnAdjX = x; gps.UnAdjY = y; } else { gps.UnAdjX = coord.X; gps.UnAdjY = coord.Y; } if (useElev) { if (coord.Z == double.NaN) { if (elevFeet) gps.UnAdjZ = TtUtils.ConvertToMeters(coord.Z, Unit.FEET_TENTH); else gps.UnAdjZ = coord.Z; } else gps.UnAdjZ = 0; } else gps.UnAdjZ = 0; gps.PolyCN = _Poly.CN; gps.PolyName = _Poly.Name; gps.GroupCN = Values.MainGroup.CN; gps.GroupName = Values.MainGroup.Name; tmpPoints.Add(gps); } _Points.AddRange(tmpPoints); _Polygons.Add(_Poly.CN, _Poly); polyCount++; } } //Close and free up any resources shapeFileDataReader.Close(); shapeFileDataReader.Dispose(); } foreach (TtPolygon poly in _Polygons.Values) dal.InsertPolygon(poly); dal.InsertPoints(_Points); PolygonAdjuster.Adjust(dal); } catch (Exception ex) { TtUtils.WriteError(ex.Message, "DataImport:ImportShapes", ex.StackTrace); return false; } return true; }
public void TestSeptPolygones() { const string wktGeom9 = "MULTIPOLYGON ( "+ "((-73.8706030450129 45.425307895968558, -73.8691180248536 45.425712901466682, -73.862907940551338 45.425949154673731, -73.862739188260548 45.423181617104319, -73.864662964375952 45.423384119853267, -73.8654729753718 45.42220285381751, -73.865979232244342 45.421730347403241, -73.866822993698463 45.42088658594912, -73.866485489116826 45.420481580450996, -73.865202971706537 45.42041407953468, -73.864629213917681 45.421325341905117, -73.864156707503412 45.422236604275611, -73.863481698340081 45.422405356566514, -73.863414197423765 45.421899099693974, -73.863414197423765 45.421190340072485, -73.8635491992564 45.4200765749531, -73.864122957045254 45.419165312582606, -73.864797966208585 45.419064061208076, -73.866316736825922 45.419030310749974, -73.867092997363727 45.419266563957194, -73.867295500112789 45.419536567622515, -73.867396751487263 45.420751584116317, -73.867092997363727 45.421527844654122, -73.866384237742238 45.422506607941045, -73.866046733160658 45.423215367562364, -73.8669579955311 45.423721624434904, -73.868881771646556 45.423485371227684, -73.8694555294353 45.423417870311312, -73.8700630376822 45.423991628100168, -73.870434292722109 45.424497884972709, -73.8706030450129 45.425307895968558), "+ "(-73.86921927622808 45.425139143677825, -73.868983023020974 45.424464134514437, -73.868544267064863 45.423991628100168, -73.86813926156691 45.423991628100168, -73.867092997363727 45.423991628100168, -73.86533797353917 45.423620373060317, -73.864966718499375 45.424059129016484, -73.864966718499375 45.424497884972709, -73.865304223081068 45.42534164642683, -73.866451738658668 45.425409147343146, -73.86756550377811 45.425274145510514, -73.86921927622808 45.425139143677825), "+ "(-73.865937695291677 45.419884197388171, -73.865599517078863 45.419585804847259, -73.86432637557175 45.4198046260438, -73.864167232883347 45.4205605538138, -73.864565089604355 45.420500875305606, -73.865937695291677 45.419884197388171)), "+ "((-73.868038010192436 45.424869140012561, -73.866620490949458 45.424869140012561, -73.865844230411653 45.424970391386921, -73.865742979037179 45.42436288314002, -73.865979232244342 45.42402537855844, -73.866687991865717 45.424295382223704, -73.867869257901532 45.424396633598121, -73.868038010192436 45.424869140012561), "+ "(-73.86744733356926 45.424703767127937, -73.867371896498639 45.42446991220919, -73.867002254852821 45.424454824795021, -73.866232796733016 45.424432193673908, -73.866345952338861 45.4246509611786, -73.86744733356926 45.424703767127937)), "+ "((-73.86512208901371 45.419923983060187, -73.864604875276427 45.420301946945074, -73.8644059469159 45.420043340076518, -73.86512208901371 45.419923983060187)))"; IGeometryFactory factory = GeometryFactory.Default; //new GeometryFactory(new PrecisionModel(Math.Pow(10, 13))); WKTReader wktReader = new WKTReader(factory); List<IGeometry> polys = new List<IGeometry>(); using (ShapefileDataReader reader = new ShapefileDataReader("sept_polygones", factory)) { int index = 0; while (reader.Read()) { IGeometry geom = reader.Geometry; Assert.IsNotNull(geom); Assert.IsTrue(geom.IsValid); geom.Normalize(); Debug.WriteLine(String.Format("Geom {0}: {1}", ++index, geom)); polys.Add(geom); } } IGeometry expected = wktReader.Read(wktGeom9); expected.Normalize(); Envelope e1 = expected.EnvelopeInternal; Envelope e2 = polys[8].EnvelopeInternal; Assert.IsTrue(e1.Equals(e2), string.Format("{0}\ndoes not match\n{1}", e1, e2)); Assert.IsTrue(expected.EqualsTopologically(polys[8]), string.Format("{0}\ndoes not match\n{1}", expected, polys[8])); }
public SLShapeFileDataEnumerator(ShapefileDataReader shapefileDataReader) { _shapefileDataReader = shapefileDataReader; }
private void ReadFromShapeFile() { var featureCollection = new ArrayList(); const string filename = @"country"; if (!File.Exists(filename + ".dbf")) throw new FileNotFoundException(filename + " not found at " + Environment.CurrentDirectory); var dataReader = new ShapefileDataReader(filename, new GeometryFactory()); while (dataReader.Read()) { var feature = new Feature {Geometry = dataReader.Geometry}; var length = dataReader.DbaseHeader.NumFields; var keys = new string[length]; for (var i = 0; i < length; i++) keys[i] = dataReader.DbaseHeader.Fields[i].Name; feature.Attributes = new AttributesTable(); for (var i = 0; i < length; i++) { var val = dataReader.GetValue(i); feature.Attributes.AddAttribute(keys[i], val); } featureCollection.Add(feature); } var index = 0; Console.WriteLine("Elements = " + featureCollection.Count); foreach (IFeature feature in featureCollection) { Console.WriteLine("Feature " + index++); var table = feature.Attributes as AttributesTable; foreach (var name in table.GetNames()) Console.WriteLine(name + ": " + table[name]); } //Directory var dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, string.Format(@"..{0}..{0}..{0}NetTopologySuite.Samples.Shapefiles{0}", Path.DirectorySeparatorChar)); // Test write with stub header var file = dir + "testWriteStubHeader"; if (File.Exists(file + ".shp")) File.Delete(file + ".shp"); if (File.Exists(file + ".shx")) File.Delete(file + ".shx"); if (File.Exists(file + ".dbf")) File.Delete(file + ".dbf"); var dataWriter = new ShapefileDataWriter(file); dataWriter.Header = ShapefileDataWriter.GetHeader(featureCollection[0] as IFeature, featureCollection.Count); dataWriter.Write(featureCollection); // Test write with header from a existing shapefile file = dir + "testWriteShapefileHeader"; if (File.Exists(file + ".shp")) File.Delete(file + ".shp"); if (File.Exists(file + ".shx")) File.Delete(file + ".shx"); if (File.Exists(file + ".dbf")) File.Delete(file + ".dbf"); dataWriter = new ShapefileDataWriter(file) { Header = ShapefileDataWriter.GetHeader(dir + "country.dbf") }; dataWriter.Write(featureCollection); }
/// <summary> /// /// </summary> /// <param name="parent"></param> public ShapefileDataReaderEnumerator(ShapefileDataReader parent) { _parent = parent; _parent.Reset(); }
public static ShapefileDataReader CreateDataReader(IStreamProviderRegistry streamProviderRegistry, GeometryFactory geometryFactory) { if (streamProviderRegistry == null) throw new ArgumentNullException("streamProviderRegistry"); if (geometryFactory == null) throw new ArgumentNullException("geometryFactory"); var shpDataReader = new ShapefileDataReader(streamProviderRegistry, geometryFactory); return shpDataReader; }
/// <summary> /// Gets the coordinates from specified district key. /// </summary> /// <returns>The coordinates. Multiple group of coordinates separated by top level array element.</returns> /// <param name="districtKey">District key as country-district-...</param> public static IEnumerable<IEnumerable<Coordinate>> GetCoordinates(String districtKey) { var geo = new List<IEnumerable<Coordinate>>(); if (districtKey == null) return null; var level = 0; var distictKeys = districtKey.Split('-'); if (districtKey != null) level = districtKey.Split('-').Length - 1; var rootKey = distictKeys[0]; if (!shapeFileInfoLookup.ContainsKey(rootKey)) throw new KeyNotFoundException("Key = " + rootKey + " not found from configuration."); var levelMap = shapeFileInfoLookup[rootKey].ShapeFileMaps.FirstOrDefault(m => m.Level == level); if (levelMap == null) { throw new KeyNotFoundException( "No ShapeFile entry for Level = " + level + " computed from: " + districtKey); } var rootPath = shapeFileInfoLookup[rootKey].ShapeFilesRootPath; var fileName = shapeFileInfoLookup[rootKey].ShapeFileMaps[level].FileName; var filePath = rootPath + fileName; var cachePath = coordCachePath; if (HttpContext.Current != null) { filePath = HttpContext.Current.Server.MapPath(filePath); if(cachePath != null) cachePath = HttpContext.Current.Server.MapPath(cachePath + "/" + districtKey); } // Get coordinate from cache instead if found. if (cachePath != null && File.Exists(cachePath)) { try { using (var streamReader = File.OpenText(cachePath)) { String s = streamReader.ReadToEnd(); var coordinates = s.Split('|').Select( ss => { var areas = ss.Split('-').Select( ax => { var p = ax.Split(','); return new Coordinate { X = Double.Parse(p[0]), Y = Double.Parse(p[1]) }; }); return areas; }); if (coordinates.Any(Enumerable.Any)) geo.AddRange(coordinates); } return geo; } catch(Exception ex) { //TODO: Log this exception. Console.WriteLine(ex.Message); } } var factory = new GeometryFactory(); using (var shapeFileDataReader = new ShapefileDataReader(filePath, factory)) { var shapeHeader = shapeFileDataReader.ShapeHeader; var bounds = shapeHeader.Bounds; var header = shapeFileDataReader.DbaseHeader; shapeFileDataReader.Reset(); while (shapeFileDataReader.Read()) { var keys = new string[header.NumFields]; var geometry = shapeFileDataReader.Geometry; var shapeDisticts = new List<String>(); for (var i = 0; i < header.NumFields; i++) { var fieldDescriptor = header.Fields[i]; keys[i] = fieldDescriptor.Name; var fieldValue = shapeFileDataReader.GetValue(i) + ""; for (var j = 0; j <= level; j++) { if (fieldDescriptor.Name == "NAME_" + j) { shapeDisticts.Add(fieldValue.ToLower()); } } } var shapeDistictKey = String.Join("-", shapeDisticts.ToArray()); Console.WriteLine(shapeDistictKey); if (districtKey == shapeDistictKey) { // Find the duplicate coordinates. It is the polygon loop. var endPointLookup = geometry.Coordinates. GroupBy(k => k.X + "," + k.Y). Where(g => g.Count() >= 2). ToLookup(g => g.Key, null); String endPoint = null; var coords = new List<Coordinate>(); try { for (long i = 0; i < geometry.Coordinates.LongLength; i++) { if(geometry.Coordinates[i] == null) continue; var key = geometry.Coordinates[i].X + "," + geometry.Coordinates[i].Y; coords.Add(geometry.Coordinates[i]); if (endPoint == null) { if (endPointLookup.Contains(key)) endPoint = key; } else { if (endPoint == key) { endPoint = null; geo.Add(coords); coords = new List<Coordinate>(); } } } } catch(Exception ex) { Console.WriteLine(ex.Message); throw; } break; } } shapeFileDataReader.Close(); shapeFileDataReader.Dispose(); } // Build cache. if (cachePath != null) { var physicalCachePath = coordCachePath; if (HttpContext.Current != null) physicalCachePath = HttpContext.Current.Server.MapPath(physicalCachePath); if (!Directory.Exists(physicalCachePath)) Directory.CreateDirectory(physicalCachePath); var sb = new StringBuilder(); foreach (var coords in geo) { foreach (var coord in coords) { sb.AppendFormat("{0},{1}", coord.X, coord.Y); sb.Append("-"); } if(sb.Length > 0) sb.Remove(sb.Length - 1, 1); sb.Append("|"); } if(sb.Length > 0) sb.Remove(sb.Length - 1, 1); var coordCache = sb.ToString(); File.WriteAllText(cachePath, coordCache); } return geo; }
public void TestReadingShapeFileAfvalbakken() { IGeometryFactory factory = GeometryFactory.Default; List<IPolygon> polys = new List<IPolygon>(); const int distance = 500; using (ShapefileDataReader reader = new ShapefileDataReader("afvalbakken", factory)) { int index = 0; while (reader.Read()) { IGeometry geom = reader.Geometry; Assert.IsNotNull(geom); Assert.IsTrue(geom.IsValid); Debug.WriteLine(String.Format("Geom {0}: {1}", index++, geom)); IGeometry buff = geom.Buffer(distance); Assert.IsNotNull(buff); polys.Add((IPolygon) geom); } } IMultiPolygon multiPolygon = factory.CreateMultiPolygon(polys.ToArray()); Assert.IsNotNull(multiPolygon); Assert.IsTrue(multiPolygon.IsValid); IMultiPolygon multiBuffer = (IMultiPolygon) multiPolygon.Buffer(distance); Assert.IsNotNull(multiBuffer); Assert.IsTrue(multiBuffer.IsValid); ShapefileWriter.WriteGeometryCollection(@"test_buffer", multiBuffer); }
public void GeometryTransformTest() { #region Init ICoordinateTransformation // RGF93_Lambert_93 const string coordSysRGF93_Lambert_93 = "PROJCS[\"RGF93_Lambert_93\",GEOGCS[\"GCS_RGF_1993\",DATUM[\"D_RGF_1993\",SPHEROID[\"GRS_1980\",6378137.0,298.257222101]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Lambert_Conformal_Conic\"],PARAMETER[\"False_Easting\",700000.0],PARAMETER[\"False_Northing\",6600000.0],PARAMETER[\"Central_Meridian\",3.0],PARAMETER[\"Standard_Parallel_1\",44.0],PARAMETER[\"Standard_Parallel_2\",49.0],PARAMETER[\"Latitude_Of_Origin\",46.5],UNIT[\"Meter\",1.0]]"; // SRID 4326 const string coordSys4326 = "GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.01745329251994328,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4326\"]]"; var csSource = ProjNet.Converters.WellKnownText.CoordinateSystemWktReader.Parse(coordSysRGF93_Lambert_93) as GeoAPI.CoordinateSystems.ICoordinateSystem; var csTarget = ProjNet.Converters.WellKnownText.CoordinateSystemWktReader.Parse(coordSys4326) as GeoAPI.CoordinateSystems.ICoordinateSystem; var transform = new ProjNet.CoordinateSystems.Transformations.CoordinateTransformationFactory().CreateFromCoordinateSystems(csSource, csTarget); var piSource = ProjectionInfo.FromEsriString(coordSysRGF93_Lambert_93); var piTarget = ProjectionInfo.FromEsriString(coordSys4326); var dsTransform = new DotSpatialMathTransform(piSource, piTarget); #endregion Init ICoordinateTransformation using (var shapeDataReader = new ShapefileDataReader(@"..\..\..\NetTopologySuite.Samples.Shapefiles\DEPARTEMENT.SHP", GeometryFactory.Default)) { while (shapeDataReader.Read()) { var outGeomDotSpatial = CoordinateSystems.Transformations.GeometryTransform.TransformGeometry(GeometryFactory.Default, shapeDataReader.Geometry, dsTransform); Assert.IsFalse(outGeomDotSpatial.IsEmpty); Console.WriteLine(outGeomDotSpatial.AsText()); var outGeomProjNet = CoordinateSystems.Transformations.GeometryTransform.TransformGeometry(GeometryFactory.Default, shapeDataReader.Geometry, transform.MathTransform); Assert.IsFalse(outGeomProjNet.IsEmpty); Console.WriteLine(outGeomProjNet.AsText()); var hd = Algorithm.Distance.DiscreteHausdorffDistance.Distance(outGeomProjNet, outGeomDotSpatial); Console.WriteLine(string.Format("\nHaussdorffDistance: {0}", hd)); Console.WriteLine(); } } }
public void TestReadingShapeFileZ() { //Use a factory with a coordinate sequence factor that can handle measure values GeometryFactory factory = new GeometryFactory(DotSpatialAffineCoordinateSequenceFactory.Instance); const int distance = 500; using (ShapefileDataReader reader = new ShapefileDataReader("with_M", factory)) { // "" int index = 0; reader.Read(); IGeometry geom = reader.Geometry; double firstM = geom.GetOrdinates(Ordinate.M).First(); Assert.AreEqual(400, firstM); while (reader.Read()) { geom = reader.Geometry; Assert.IsNotNull(geom); Assert.IsTrue(geom.IsValid); Debug.WriteLine(String.Format("Geom {0}: {1}", index++, geom)); IGeometry buff = geom.Buffer(distance); Assert.IsNotNull(buff); foreach (double m in geom.GetOrdinates(Ordinate.M)) { Assert.IsFalse(Double.IsNaN(m)); } } } }
/// <summary> /// Returns an ShapefileDataReader representing the data in a shapefile. /// </summary> /// <param name="filename">The filename (minus the . and extension) to read.</param> /// <param name="geometryFactory">The geometry factory to use when creating the objects.</param> /// <returns>An ShapefileDataReader representing the data in the shape file.</returns> public static ShapefileDataReader CreateDataReader(string filename, GeometryFactory geometryFactory) { if (filename == null) throw new ArgumentNullException("filename"); if (geometryFactory == null) throw new ArgumentNullException("geometryFactory"); var shpDataReader = new ShapefileDataReader(filename, geometryFactory); return shpDataReader; }