public void FeatureCollectionConstructorTest1() { Collection<IFeature> features = new Collection<IFeature> {new Feature()}; FeatureCollection target = new FeatureCollection(features); Assert.IsInstanceOfType(typeof(FeatureCollection), target); Assert.AreEqual(features, target.Features); }
public static FeatureCollection FromFlatGeobuf(byte[] bytes) { var fc = new NetTopologySuite.Features.FeatureCollection(); var bb = new ByteBuffer(bytes); var headerSize = (ulong)ByteBufferUtil.GetSizePrefix(bb); bb.Position = FlatBufferConstants.SizePrefixLength; var header = Header.GetRootAsHeader(bb); var count = header.FeaturesCount; var featuresSize = header.FeaturesSize; var nodeSize = header.IndexNodeSize; bb.Position += (int)headerSize; var index = new PackedHilbertRTree(count, nodeSize); var indexData = bytes.Skip((int)(headerSize + featuresSize)).Take((int)index.Size).ToArray(); index.Load(indexData); while (count-- > 0) { var featureLength = ByteBufferUtil.GetSizePrefix(bb); bb.Position += FlatBufferConstants.SizePrefixLength; var feature = FeatureConversions.FromByteBuffer(bb, header); fc.Add(feature); bb.Position += featureLength; } return(fc); }
public void AddTest() { FeatureCollection target = new FeatureCollection(); IFeature feature = new Feature(); target.Add(feature); Assert.AreEqual(feature, target.Features[0]); }
public FeatureCollection ToGeoJson(gpxType gpx) { var collection = new FeatureCollection(); var points = gpx.wpt ?? new wptType[0]; var pointsFeatures = points.Select(point => new Feature(new Point(CreateGeoPosition(point)), CreateNameProperties(point.name))); pointsFeatures.ToList().ForEach(f => collection.Features.Add(f)); var routes = gpx.rte ?? new rteType[0]; var routesFeatures = routes.Select(route => new Feature(new LineString(route.rtept.Select(CreateGeoPosition).ToArray()), CreateNameProperties(route.name))); routesFeatures.ToList().ForEach(f => collection.Features.Add(f)); foreach (var track in gpx.trk ?? new trkType[0]) { if (track.trkseg.Length == 1) { var lineStringFeature = new Feature(new LineString(track.trkseg[0].trkpt.Select(CreateGeoPosition).ToArray()), CreateNameProperties(track.name)); collection.Features.Add(lineStringFeature); continue; } var lineStringList = track.trkseg.Select(segment => new LineString(segment.trkpt.Select(CreateGeoPosition).ToArray()) as ILineString).ToArray(); var feature = new Feature(new MultiLineString(lineStringList), CreateMultiLineProperties(track.name, gpx.creator)); collection.Features.Add(feature); } return collection; }
/// <summary> /// Writes the specified feature collection. /// </summary> /// <param name="featureCollection">The feature collection.</param> /// <returns></returns> public string Write(FeatureCollection featureCollection) { JsonSerializer g = new GeoJsonSerializer(); StringBuilder sb = new StringBuilder(); using (StringWriter sw = new StringWriter(sb)) g.Serialize(sw, featureCollection); return sb.ToString(); }
public void RemoveAtTest() { IFeature feature = new Feature(); FeatureCollection target = new FeatureCollection(new Collection<IFeature> { feature }); const int index = 0; target.RemoveAt(index); Assert.AreEqual(0, target.Count); }
public void GeoJsonWriterWriteFeatureCollectionTest() { AttributesTable attributes = new AttributesTable(); attributes.AddAttribute("test1", "value1"); IFeature feature = new Feature(new Point(23, 56), attributes); FeatureCollection featureCollection = new FeatureCollection(new Collection<IFeature> { feature }) { CRS = new NamedCRS("name1") }; string actual = new GeoJsonWriter().Write(featureCollection); Assert.AreEqual("{\"features\":[{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[23.0,56.0]},\"properties\":{\"test1\":\"value1\"}}],\"type\":\"FeatureCollection\",\"crs\":{\"type\":\"name\",\"properties\":{\"name\":\"name1\"}}}", actual); }
public void RemoveTest() { IFeature feature = new Feature(); FeatureCollection target = new FeatureCollection(new Collection<IFeature> { feature }); const bool expected = true; bool actual = target.Remove(feature); Assert.AreEqual(expected, actual); Assert.AreEqual(0, target.Count); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) return null; reader.Read(); FeatureCollection fc = new FeatureCollection(); while (reader.TokenType != JsonToken.EndObject) { if (reader.TokenType != JsonToken.PropertyName) throw new ArgumentException("Expected a property name."); string val = (string)reader.Value; if (val == "features") { reader.Read(); if (reader.TokenType != JsonToken.StartArray) throw new ArgumentException("Expected token '[' not found."); reader.Read(); while (reader.TokenType != JsonToken.EndArray) fc.Add(serializer.Deserialize<Feature>(reader)); reader.Read(); continue; } if (val == "type") { reader.Read(); if (reader.TokenType != JsonToken.String && (string) reader.Value != "FeatureCollection") throw new ArgumentException("Expected value 'FeatureCollection' not found."); reader.Read(); continue; } if (val == "bbox") { reader.Read(); if (reader.TokenType != JsonToken.StartArray) throw new ArgumentException("Expected token '{' not found."); // read the values but for now discard them var env = serializer.Deserialize<double[]>(reader); if (reader.TokenType != JsonToken.EndArray) throw new ArgumentException("Expected token '}' not found."); reader.Read(); continue; } if (val == "crs") { reader.Read(); fc.CRS = serializer.Deserialize<ICRSObject>(reader); continue; } // additional members are ignored: see https://code.google.com/p/nettopologysuite/issues/detail?id=186 reader.Read(); // read property value reader.Read(); // move next } return fc; }
public static FeatureCollection Deserialize(byte[] bytes) { var fc = new NetTopologySuite.Features.FeatureCollection(); foreach (var feature in Deserialize(new MemoryStream(bytes))) { fc.Add(feature); } return(fc); }
public static FeatureCollection FromFlatGeobuf(byte[] bytes) { var fc = new NetTopologySuite.Features.FeatureCollection(); var bb = new ByteBuffer(bytes); var headerSize = ByteBufferUtil.GetSizePrefix(bb); bb.Position = FlatBufferConstants.SizePrefixLength; var header = Header.GetRootAsHeader(bb); var count = header.FeaturesCount; var nodeSize = header.IndexNodeSize; var geometryType = header.GeometryType; var dimensions = header.Dimensions; IList <ColumnMeta> columns = null; if (header.ColumnsLength > 0) { columns = new List <ColumnMeta>(); for (int i = 0; i < header.ColumnsLength; i++) { var column = header.Columns(i).Value; columns.Add(new ColumnMeta() { Name = column.Name, Type = column.Type }); } } bb.Position += headerSize; if (nodeSize > 0) { var index = new PackedHilbertRTree(count, nodeSize); var indexData = bytes.Skip(headerSize).Take((int)index.Size).ToArray(); index.Load(indexData); bb.Position += (int)index.Size + (int)count * 8; } while (bb.Position < bb.Length) { var featureLength = ByteBufferUtil.GetSizePrefix(bb); bb.Position += FlatBufferConstants.SizePrefixLength; var feature = FeatureConversions.FromByteBuffer(bb, geometryType, dimensions, columns); fc.Add(feature); bb.Position += featureLength; } return(fc); }
/// <summary> /// Converts DotSpatial features into a NetTopologySuite feature collection. /// </summary> /// <param name="features">DotSpatial features.</param> /// <param name="outSR">The EPSG identifier for a spatial reference system.</param> /// <param name="omittedFields">Names of fields that will be omitted.</param> /// <param name="aliases">This parameter allows you to provide aliases for the field names.</param> /// <returns>A NetTopologySuite feature collection</returns> public static FeatureCollection ToNtsFeatureCollection(this IEnumerable<DotSpatial.Data.IFeature> features, int outSR, IEnumerable<string> omittedFields = null, IDictionary<string, string> aliases = null) { var featureCollection = new FeatureCollection(); // Omit CRS for WGS 84, which is the default for GeoJSON. if (outSR != 4326) { featureCollection.CRS = new NamedCRS(string.Format("urn:ogc:def:crs:EPSG::{0}", outSR)); } foreach (var f in features.AsNtsFeatures(omittedFields, aliases)) { featureCollection.Add(f); } return featureCollection; }
public void GeoJsonSerializerFeatureCollectionTest() { StringBuilder sb = new StringBuilder(); StringWriter writer = new StringWriter(sb); AttributesTable attributes = new AttributesTable(); attributes.AddAttribute("test1", "value1"); IFeature feature = new Feature(new Point(23, 56), attributes); FeatureCollection featureCollection = new FeatureCollection(new Collection<IFeature> {feature}) {CRS = new NamedCRS("name1")}; GeoJsonSerializer serializer = new GeoJsonSerializer(); serializer.Serialize(writer, featureCollection); writer.Flush(); Assert.AreEqual("{\"features\":[{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[23.0,56.0]},\"properties\":{\"test1\":\"value1\"}}],\"type\":\"FeatureCollection\",\"crs\":{\"type\":\"name\",\"properties\":{\"name\":\"name1\"}}}", sb.ToString()); }
public async Task<DataContainer> PostConvertSearchResults(JObject content) { var name = "israelHiking"; var feature = content.ToObject<Feature>(new GeoJsonSerializer()); if (feature.Attributes.GetNames().Contains("name")) { name = feature.Attributes["name"].ToString(); } var featureCollection = new FeatureCollection(new Collection<IFeature> {feature}); var dataContainer = await _dataContainerConverterService.ToDataContainer(featureCollection.ToBytes(), name + ".geojson"); foreach (var latLngZ in dataContainer.routes.SelectMany(routeData => routeData.segments.SelectMany(routeSegmentData => routeSegmentData.latlngzs))) { latLngZ.z = await _elevationDataStorage.GetElevation(latLngZ); } return dataContainer; }
public gpxType ToGpx(FeatureCollection collection) { return new gpxType { creator = collection.Features.FirstOrDefault(f => f.Attributes.GetNames().Contains(CREATOR))?.Attributes[CREATOR]?.ToString() ?? string.Empty, wpt = collection.Features.Where(f => f.Geometry is Point) .Select(CreateWayPoint) .Union(collection.Features.Where(f => f.Geometry is MultiPoint) .SelectMany(CreateWayPointsFromMultiPoint)) .ToArray(), rte = collection.Features.Where(f => f.Geometry is LineString) .Select(CreateRouteFromLineString) .Union(collection.Features.Where(f => f.Geometry is Polygon).Select(CreateRouteFromPolygon)) .Union(collection.Features.Where(f => f.Geometry is MultiPolygon).SelectMany(CreateRoutesFromMultiPolygon)) .ToArray(), trk = collection.Features.Where(f => f.Geometry is MultiLineString) .SelectMany(CreateTracksFromMultiLineString) .ToArray() }.UpdateBounds(); }
public void ToGpx_WithAllTypesOffeatures_ShouldBeConverted() { var converter = new GpxGeoJsonConverter(); var geojson = new FeatureCollection(); var table = new AttributesTable(); geojson.Features.Add(new Feature(new Point(new Coordinate(1, 1)), table)); geojson.Features.Add(new Feature(new MultiPoint(new[] { new Point(new Coordinate(2,2)) as IPoint }), table)); geojson.Features.Add(new Feature(new Polygon(new LinearRing(new [] { new Coordinate(3,3), new Coordinate(4,4), new Coordinate(5,5), new Coordinate(3,3) })), table)); geojson.Features.Add(new Feature(new LineString(new[] { new Coordinate(6, 6), new Coordinate(7, 7) }), table)); geojson.Features.Add(new Feature(new MultiPolygon(new IPolygon[] { new Polygon(new LinearRing(new [] { new Coordinate(8,8), new Coordinate(9, 9), new Coordinate(10, 10), new Coordinate(8, 8) }))}), table)); geojson.Features.Add(new Feature(new MultiLineString(new ILineString[] { new LineString(new[] { new Coordinate(11, 11), new Coordinate(12, 12)}), new LineString(new[] { new Coordinate(12, 12), new Coordinate(13, 13)}), new LineString(new[] { new Coordinate(14, 14), new Coordinate(15, 15)}), }), table)); var gpx = converter.ToGpx(geojson); Assert.AreEqual(2, gpx.wpt.Length); Assert.AreEqual(3, gpx.rte.Length); Assert.AreEqual(2, gpx.trk.Length); }
public void Serialize(FeatureCollection featureCollection) { Writer.WriteStartObject(); Writer.WritePropertyName("type"); Writer.WriteValue("FeatureCollection"); if (featureCollection.CRS != null) { Writer.WritePropertyName("crs"); Writer.WriteStartObject(); switch (featureCollection.CRS.Type) { case CRSTypes.Name: SerializeNamedCRS(featureCollection.CRS); break; case CRSTypes.Link: SerializeLinkedCRS(featureCollection.CRS); break; default: throw new Exception(String.Format("Don't know how to serialize {0} CRS type", featureCollection.CRS)); } Writer.WriteEndObject(); } Writer.WritePropertyName("features"); Writer.WriteStartArray(); foreach (var feature in featureCollection.Features) { SerializeFeature(feature); } Writer.WriteEndArray(); Writer.WriteEndObject(); }
public void CountTest() { IFeature feature = new Feature(); FeatureCollection target = new FeatureCollection(new Collection<IFeature> { feature }); Assert.AreEqual(1, target.Count); }
private FeatureCollection CreateCollection(TopoObject[] data) { IFeature[] features = new IFeature[data.Length]; for (int i = 0; i < data.Length; i++) { TopoObject component = data[i]; FeatureCollection coll = Create(component); features[i] = coll[0]; } FeatureCollection collection = new FeatureCollection(); foreach (IFeature feature in features) collection.Add(feature); return collection; }
public List <Object> CalculateDataTable(string polyfile) { //List<GeoAPI.Geometries.IGeometry> polys = new List<GeoAPI.Geometries.IGeometry>(); List <GeoAPI.Geometries.IGeometry> squares = new List <GeoAPI.Geometries.IGeometry>(); ArrayList polys = new ArrayList(); List <Object> infoTable = new List <Object>(); double squareArea = 0;//0.015625; double gridArea = 0; double polygonArea = 0; string catchmentID = ""; ////////////// string gridfile = @"M:\DotSpatTopology\tests\NLDAS_Grid_Reference.shp";//""; string gridproj = @"M:\DotSpatTopology\tests\NLDAS_Grid_Reference.prj"; ////////////// Guid gid = Guid.NewGuid(); string directory = @"M:\\TransientStorage\\" + gid.ToString() + "\\"; //This block is for getting and setting shapefiles for NLDAS Grid /** * client.DownloadFile("https://ldas.gsfc.nasa.gov/nldas/gis/NLDAS_Grid_Reference.zip", @"M:\\TransientStorage\\NLDAS.zip"); * ZipFile.ExtractToDirectory(@"M:\\TransientStorage\\NLDAS.zip", @"M:\\TransientStorage\\NLDAS"); * unzippedLocation = (@"M:\\TransientStorage\\NLDAS"); * foreach (string file in Directory.GetFiles(unzippedLocation)) * { * if (Path.GetExtension(file).Equals(".shp")) * { * gridfile = file; * } * else if (Path.GetExtension(file).Equals(".prj")) * { * gridproj = file; * } * } * client.Dispose();**/ ShapefileDataReader reader2 = new ShapefileDataReader(gridfile, NetTopologySuite.Geometries.GeometryFactory.Default); while (reader2.Read()) { squares.Add(reader2.Geometry); gridArea += reader2.Geometry.Area; } reader2.Dispose(); //if (polyfile.StartsWith(@"{""type"": ""FeatureCollection""")) if (polyfile.StartsWith(@"{""type"":"))//.geojson { Boolean version1 = true; string[] featureParams = new string[3]; string jsonfile = polyfile; var readera = new NetTopologySuite.IO.GeoJsonReader(); NetTopologySuite.Features.FeatureCollection result = readera.Read <NetTopologySuite.Features.FeatureCollection>(jsonfile); if (result[0].Attributes.GetNames().Contains("HUC_8")) { version1 = false; featureParams[0] = "OBJECTID"; featureParams[1] = "HUC_8"; featureParams[2] = "HUC_12"; } else if (result[0].Attributes.GetNames().Contains("HUC8")) { version1 = true; featureParams[0] = "COMID"; featureParams[1] = "HUC8"; featureParams[2] = "HUC12"; } else { version1 = false; featureParams[0] = null; featureParams[1] = null; featureParams[2] = null; } List <Object> huc8Table = new List <Object>(); huc8Table.Add(new KeyValuePair <string, string>("HUC 8 ID: ", result[0].Attributes[featureParams[1]].ToString())); for (int i = 0; i < result.Count; i++) { List <Object> huc12Table = new List <Object>(); if (version1) { huc12Table.Add(new KeyValuePair <string, string>("HUC 12 ID: ", null)); } else { huc12Table.Add(new KeyValuePair <string, string>("HUC 12 ID: ", result[i].Attributes["HUC_12"].ToString())); } catchmentID = result[i].Attributes[featureParams[0]].ToString(); huc12Table.Add(new KeyValuePair <string, string>("Catchment ID: ", catchmentID)); foreach (GeoAPI.Geometries.IGeometry s in squares) { double interArea = 0.0; squareArea = s.Area; if (result[i].Geometry.Intersects(s)) { GeoAPI.Geometries.IGeometry intersection = result[i].Geometry.Intersection(s); interArea += intersection.Area; double percent2 = (interArea / squareArea) * 100; Dictionary <string, string> catchTable = new Dictionary <string, string>(); //catchTable.Add("catchmentID", catchmentID); catchTable.Add("latitude", s.Centroid.X.ToString()); catchTable.Add("longitude", s.Centroid.Y.ToString()); catchTable.Add("cellArea", squareArea.ToString()); catchTable.Add("containedArea", interArea.ToString()); catchTable.Add("percentArea", percent2.ToString()); huc12Table.Add(catchTable); } } huc8Table.Add(huc12Table); } infoTable.Add(huc8Table); } else //Huc ID { catchmentID = polyfile; string ending = polyfile + ".zip"; WebClient client = new WebClient(); DirectoryInfo di = Directory.CreateDirectory(directory); client.DownloadFile("ftp://newftp.epa.gov/exposure/NHDV1/HUC12_Boundries/" + ending, directory + ending); string projfile = ""; string dataFile = ""; ZipFile.ExtractToDirectory(directory + ending, directory + polyfile); string unzippedLocation = (directory + polyfile + "\\" + polyfile); //+ "\\NHDPlus" + polyfile + "\\Drainage"); foreach (string file in Directory.GetFiles(unzippedLocation)) { if (Path.GetExtension(file).Equals(".shp")) { polyfile = file; } else if (Path.GetExtension(file).Equals(".prj")) { projfile = file; } else if (Path.GetExtension(file).Equals(".dbf")) { dataFile = file; } } //This block is for setting projection parameters of input shapefile and projecting it to NLDAS grid //Reprojecting of coordinates is not needed for NHDPlus V2 string line = System.IO.File.ReadAllText(projfile); string[] projParams = { "PARAMETER", @"PARAMETER[""latitude_Of_origin"",0]," };//@"PARAMETER[""false_easting"",0],", @"PARAMETER[""false_northing"",0],", @"PARAMETER[""central_meridian"",0],", @"PARAMETER[""standard_parallel_1"",0],", @"PARAMETER[""standard_parallel_2"",0],", @"PARAMETER[""latitude_Of_origin"",0]," }; int ptr = 0; foreach (string x in projParams) { if (line.Contains(x)) { ptr = line.IndexOf(x); } else if (!line.Contains(x) && !x.Equals("PARAMETER")) { line = line.Insert(ptr, x); } } string line2 = System.IO.File.ReadAllText(gridproj); IProjectedCoordinateSystem pcs = CoordinateSystemWktReader.Parse(line) as IProjectedCoordinateSystem; IGeographicCoordinateSystem gcs = GeographicCoordinateSystem.WGS84 as IGeographicCoordinateSystem; CoordinateTransformationFactory ctfac = new CoordinateTransformationFactory(); ICoordinateTransformation transformTo = ctfac.CreateFromCoordinateSystems(pcs, gcs); IMathTransform inverseTransformTo = transformTo.MathTransform; //Read geometries from both shapefiles and store in array lists //As well as calculate shapefile areas ahead of time ShapefileDataReader reader = new ShapefileDataReader(polyfile, NetTopologySuite.Geometries.GeometryFactory.Default); while (reader.Read()) { //Reprojection not needed for NHDPLUSV2 CoordinateList cordlist = new CoordinateList(); foreach (Coordinate coord in reader.Geometry.Coordinates) { double[] newCoord = { coord.X, coord.Y }; newCoord = inverseTransformTo.Transform(newCoord); Coordinate newpt = new Coordinate(newCoord[0], newCoord[1]); cordlist.Add(newpt); } Coordinate[] listofpts = cordlist.ToCoordinateArray(); IGeometryFactory geoFactory = new NetTopologySuite.Geometries.GeometryFactory(); NetTopologySuite.Geometries.LinearRing linear = (NetTopologySuite.Geometries.LinearRing) new GeometryFactory().CreateLinearRing(listofpts); Polygon projPoly = new Polygon(linear, null, geoFactory); polys.Add(projPoly); polygonArea += projPoly.Area; } reader.Dispose(); List <Object> huc8Table = new List <Object>(); huc8Table.Add(new KeyValuePair <string, string>("HUC 8 ID: ", catchmentID)); foreach (Polygon p in polys) { List <Object> huc12Table = new List <Object>(); huc12Table.Add(new KeyValuePair <string, string>("HUC 12 ID: ", null)); catchmentID = null;//result[i].Attributes["OBJECTID"].ToString(); huc12Table.Add(new KeyValuePair <string, string>("Catchment ID: ", catchmentID)); foreach (GeoAPI.Geometries.IGeometry s in squares) { double interArea = 0.0; squareArea = s.Area; if (p.Intersects(s)) { GeoAPI.Geometries.IGeometry intersection = p.Intersection(s); interArea += intersection.Area; double percent2 = (interArea / squareArea) * 100; Dictionary <string, string> catchTable = new Dictionary <string, string>(); //catchTable.Add("catchmentID", catchmentID); catchTable.Add("latitude", s.Centroid.X.ToString()); catchTable.Add("longitude", s.Centroid.Y.ToString()); catchTable.Add("cellArea", squareArea.ToString()); catchTable.Add("containedArea", interArea.ToString()); catchTable.Add("percentArea", percent2.ToString()); huc12Table.Add(catchTable); } } huc8Table.Add(huc12Table); } infoTable.Add(huc8Table); } //System.IO.DirectoryInfo del = new DirectoryInfo(directory); /* * foreach (FileInfo file in del.GetFiles()) * { * file.Delete(); * } * foreach (DirectoryInfo dir in del.GetDirectories()) * { * dir.Delete(true); * }*/ //del.Delete(true); ///// //infoTable.Add(new List<Object>() { elapsedTime, elapsedTime, elapsedTime, elapsedTime }); ////// return(infoTable); }
private FeatureCollection ParseFeatureCollection() { var res = new FeatureCollection(); AssertRead(JsonToken.PropertyName); if ((string)Reader.Value == "crs") { CRSBase crs; AssertRead(JsonToken.StartObject); AssertRead(JsonToken.PropertyName); AssertValue("type"); AssertRead(JsonToken.String); var type = (string)Reader.Value; switch (type) { case "name": crs = ParseNamedCRS(); break; case "link": crs = ParseLinkedCRS(); break; default: throw new Exception(String.Format("Don't know how to parse CRS type {0}", type)); } AssertRead(JsonToken.EndObject); res.CRS = crs; AssertRead(JsonToken.PropertyName); } Assert((string)Reader.Value == "features"); AssertRead(JsonToken.StartArray); while (Reader.Read()) { if (Reader.TokenType == JsonToken.StartObject) { res.Features.Add((Feature)ParseUnknown(true)); } else if (Reader.TokenType == JsonToken.EndArray) { break; } else { throw new Exception(); } } //TODO: Read endobject? return res; }
public List <Object> CalculateDataTable(string polyfile) { //Calling EPA WATERS: //https://ofmpub.epa.gov/waters10/SpatialAssignment.Service?pGeometry=POINT(-76.7498+37.5)&pLayer=NHDPLUS_CATCHMENT&pAssignmentHint=9894716&pReturnGeometry=TRUE //List<GeoAPI.Geometries.IGeometry> polys = new List<GeoAPI.Geometries.IGeometry>(); List <GeoAPI.Geometries.IGeometry> squares = new List <GeoAPI.Geometries.IGeometry>(); ArrayList polys = new ArrayList(); ArrayList polyfeats = new ArrayList(); List <Object> infoTable = new List <Object>(); double squareArea = 0;//0.015625; double gridArea = 0; double polygonArea = 0; string catchmentID = ""; ////////////// string gridfile = @"M:\DotSpatTopology\tests\NLDAS_Grid_Reference.shp";//""; string gridproj = @"M:\DotSpatTopology\tests\NLDAS_Grid_Reference.prj"; ////////////// Guid gid = Guid.NewGuid(); string directory = @"M:\\TransientStorage\\" + gid.ToString() + "\\"; //This block is for getting and setting shapefiles for NLDAS Grid /** * client.DownloadFile("https://ldas.gsfc.nasa.gov/nldas/gis/NLDAS_Grid_Reference.zip", @"M:\\TransientStorage\\NLDAS.zip"); * ZipFile.ExtractToDirectory(@"M:\\TransientStorage\\NLDAS.zip", @"M:\\TransientStorage\\NLDAS"); * unzippedLocation = (@"M:\\TransientStorage\\NLDAS"); * foreach (string file in Directory.GetFiles(unzippedLocation)) * { * if (Path.GetExtension(file).Equals(".shp")) * { * gridfile = file; * } * else if (Path.GetExtension(file).Equals(".prj")) * { * gridproj = file; * } * } * client.Dispose();**/ ShapefileDataReader reader2 = new ShapefileDataReader(gridfile, NetTopologySuite.Geometries.GeometryFactory.Default); while (reader2.Read()) { squares.Add(reader2.Geometry); gridArea += reader2.Geometry.Area; } reader2.Dispose(); //if (polyfile.StartsWith(@"{""type"": ""FeatureCollection""")) if (polyfile.StartsWith(@"{""type"":"))//.geojson { Boolean version1 = true; string[] featureParams = new string[3]; string jsonfile = polyfile; var readera = new NetTopologySuite.IO.GeoJsonReader(); NetTopologySuite.Features.FeatureCollection result = readera.Read <NetTopologySuite.Features.FeatureCollection>(jsonfile); if (result[0].Attributes.GetNames().Contains("HUC_8")) { version1 = false; featureParams[0] = "OBJECTID"; featureParams[1] = "HUC_8"; featureParams[2] = "HUC_12"; } else if (result[0].Attributes.GetNames().Contains("HUC8")) { version1 = true; featureParams[0] = "COMID"; featureParams[1] = "HUC8"; featureParams[2] = "HUC12"; } else { version1 = false; featureParams[0] = null; featureParams[1] = null; featureParams[2] = null; } List <Object> huc8Table = new List <Object>(); Dictionary <string, string> h8 = new Dictionary <string, string>(); h8.Add("HUC 8 ID: ", result[0].Attributes[featureParams[1]].ToString()); huc8Table.Add(h8); //huc8Table.Add(new KeyValuePair<string, string>("HUC 8 ID: ", result[0].Attributes[featureParams[1]].ToString())); for (int i = 0; i < result.Count; i++) { List <Object> huc12Table = new List <Object>(); if (version1) { huc12Table.Add(new KeyValuePair <string, string>("HUC 12 ID: ", null)); } else { Dictionary <string, string> h12 = new Dictionary <string, string>(); h12.Add("HUC 12 ID: ", result[i].Attributes["HUC_12"].ToString()); huc12Table.Add(h12); //huc12Table.Add(new KeyValuePair<string, string>("HUC 12 ID: ", result[i].Attributes["HUC_12"].ToString())); } catchmentID = result[i].Attributes[featureParams[0]].ToString(); Dictionary <string, string> cm = new Dictionary <string, string>(); cm.Add("Catchment ID: ", catchmentID); huc12Table.Add(cm); //huc12Table.Add(new KeyValuePair<string, string>("Catchment ID: ", catchmentID)); foreach (GeoAPI.Geometries.IGeometry s in squares) { double interArea = 0.0; squareArea = s.Area; if (result[i].Geometry.Intersects(s)) { GeoAPI.Geometries.IGeometry intersection = result[i].Geometry.Intersection(s); interArea += intersection.Area; double percent2 = (interArea / squareArea) * 100; Dictionary <string, string> catchTable = new Dictionary <string, string>(); //catchTable.Add("catchmentID", catchmentID); catchTable.Add("latitude", s.Centroid.X.ToString()); catchTable.Add("longitude", s.Centroid.Y.ToString()); catchTable.Add("cellArea", squareArea.ToString()); catchTable.Add("containedArea", interArea.ToString()); catchTable.Add("percentArea", percent2.ToString()); huc12Table.Add(catchTable); } } huc8Table.Add(huc12Table); } infoTable.Add(huc8Table); } else //Huc ID { catchmentID = polyfile; string ending = polyfile + ".zip"; WebClient client = new WebClient(); DirectoryInfo di = Directory.CreateDirectory(directory); client.DownloadFile("ftp://newftp.epa.gov/exposure/NHDV1/HUC12_Boundries/" + ending, directory + ending); string projfile = ""; string dataFile = ""; ZipFile.ExtractToDirectory(directory + ending, directory + polyfile); string unzippedLocation = (directory + polyfile + "\\" + polyfile); //+ "\\NHDPlus" + polyfile + "\\Drainage"); foreach (string file in Directory.GetFiles(unzippedLocation)) { if (Path.GetExtension(file).Equals(".shp")) { polyfile = file; } else if (Path.GetExtension(file).Equals(".prj")) { projfile = file; } else if (Path.GetExtension(file).Equals(".dbf")) { dataFile = file; } } //This block is for setting projection parameters of input shapefile and projecting it to NLDAS grid //Reprojecting of coordinates is not needed for NHDPlus V2 string line = System.IO.File.ReadAllText(projfile); //string line = @"PROJCS[""unnamed"",GEOGCS[""unnamed ellipse"",DATUM[""unknown"",SPHEROID[""unnamed"",6378137,0]],PRIMEM[""Greenwich"",0],UNIT[""degree"",0.0174532925199433]],PROJECTION[""Mercator_2SP""],PARAMETER[""latitude_of_origin"",0],PARAMETER[""standard_parallel_1"",0],PARAMETER[""central_meridian"",0],PARAMETER[""false_easting"",0],PARAMETER[""false_northing"",0],UNIT[""Meter"",1]]";//System.IO.File.ReadAllText(projfile); string[] projParams = { "PARAMETER", @"PARAMETER[""latitude_of_origin"",0]," };//@"PARAMETER[""false_easting"",0],", @"PARAMETER[""false_northing"",0],", @"PARAMETER[""central_meridian"",0],", @"PARAMETER[""standard_parallel_1"",0],", @"PARAMETER[""standard_parallel_2"",0],", @"PARAMETER[""latitude_Of_origin"",0]," }; int ptr = 0; foreach (string x in projParams) { if (line.Contains(x)) { ptr = line.IndexOf(x); } else if (!line.Contains(x) && !x.Equals("PARAMETER")) { line = line.Insert(ptr, x); } } string line2 = System.IO.File.ReadAllText(gridproj); IProjectedCoordinateSystem pcs = CoordinateSystemWktReader.Parse(line) as IProjectedCoordinateSystem; IGeographicCoordinateSystem gcs = GeographicCoordinateSystem.WGS84 as IGeographicCoordinateSystem; CoordinateTransformationFactory ctfac = new CoordinateTransformationFactory(); ICoordinateTransformation transformTo = ctfac.CreateFromCoordinateSystems(pcs, gcs); IMathTransform inverseTransformTo = transformTo.MathTransform; //Read geometries from both shapefiles and store in array lists ShapefileDataReader reader = new ShapefileDataReader(polyfile, NetTopologySuite.Geometries.GeometryFactory.Default); DbaseFileHeader header = reader.DbaseHeader; string huc8 = ""; while (reader.Read()) { //Reprojection not needed for NHDPLUSV2 CoordinateList cordlist = new CoordinateList(); foreach (Coordinate coord in reader.Geometry.Coordinates) { double[] newCoord = { coord.X, coord.Y }; newCoord = inverseTransformTo.Transform(newCoord); Coordinate newpt = new Coordinate(newCoord[0], newCoord[1]); cordlist.Add(newpt); } Coordinate[] listofpts = cordlist.ToCoordinateArray(); IGeometryFactory geoFactory = new NetTopologySuite.Geometries.GeometryFactory(); NetTopologySuite.Geometries.LinearRing linear = (NetTopologySuite.Geometries.LinearRing) new GeometryFactory().CreateLinearRing(listofpts); Feature feature = new Feature(); AttributesTable attributesTable = new AttributesTable(); string[] keys = new string[header.NumFields]; IGeometry geometry = (Geometry)reader.Geometry; for (int i = 0; i < header.NumFields; i++) { DbaseFieldDescriptor fldDescriptor = header.Fields[i]; keys[i] = fldDescriptor.Name; attributesTable.AddAttribute(fldDescriptor.Name, reader.GetValue(i)); } feature.Geometry = geometry; feature.Attributes = attributesTable; polyfeats.Add(feature.Attributes); huc8 = attributesTable.GetValues()[5].ToString(); Polygon projPoly = new Polygon(linear, null, geoFactory); polys.Add(projPoly); polygonArea += projPoly.Area; } reader.Dispose(); List <Object> huc8Table = new List <Object>(); Dictionary <string, string> h8 = new Dictionary <string, string>(); h8.Add("HUC 8 ID: ", catchmentID); huc8Table.Add(h8); int j = 0; foreach (Polygon p in polys) { List <Object> huc12Table = new List <Object>(); Dictionary <string, string> cm = new Dictionary <string, string>(); // AttributesTable tab = (AttributesTable)polyfeats[j]; object[] valuesl = tab.GetValues(); cm.Add("HUC 12 ID: ", valuesl[17].ToString()); huc12Table.Add(cm); //huc12Table.Add(new KeyValuePair<string, string>("HUC 12 ID: ", null)); catchmentID = null;//result[i].Attributes["OBJECTID"].ToString(); Dictionary <string, string> cm2 = new Dictionary <string, string>(); cm2.Add("Catchment ID: ", catchmentID); huc12Table.Add(cm2); //huc12Table.Add(new KeyValuePair<string, string>("Catchment ID: ", catchmentID)); foreach (GeoAPI.Geometries.IGeometry s in squares) { double interArea = 0.0; squareArea = s.Area; if (p.Intersects(s)) { GeoAPI.Geometries.IGeometry intersection = p.Intersection(s); interArea += intersection.Area; double percent2 = (interArea / squareArea) * 100; Dictionary <string, string> catchTable = new Dictionary <string, string>(); //catchTable.Add("catchmentID", catchmentID); catchTable.Add("latitude", s.Centroid.X.ToString()); catchTable.Add("longitude", s.Centroid.Y.ToString()); catchTable.Add("cellArea", squareArea.ToString()); catchTable.Add("containedArea", interArea.ToString()); catchTable.Add("percentArea", percent2.ToString()); huc12Table.Add(catchTable); } } huc8Table.Add(huc12Table); j++; } infoTable.Add(huc8Table); } //System.IO.DirectoryInfo del = new DirectoryInfo(directory); /* * foreach (FileInfo file in del.GetFiles()) * { * file.Delete(); * } * foreach (DirectoryInfo dir in del.GetDirectories()) * { * dir.Delete(true); * }*/ //del.Delete(true); return(infoTable); }
public void FeatureCollectionConstructorTest() { FeatureCollection target = new FeatureCollection(); Assert.IsInstanceOfType(typeof(FeatureCollection), target); }
/// <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 static FeatureCollection CleanerFeatureCollection(this FeatureCollection featureCollection) {
public void GeoJsonWriterWriteAnyObjectTest() { AttributesTable attributes = new AttributesTable(); DateTime Date = new DateTime(2012, 8, 8).Date; GeoJsonSerializer g = new GeoJsonSerializer(); StringBuilder sb = new StringBuilder(); using (StringWriter sw = new StringWriter(sb)) g.Serialize(sw, Date); string expectedDateString = sb.ToString(); string expectedResult = "{\"featureCollection\":{\"features\":[{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[23.0,56.0]},\"properties\":{\"test1\":\"value1\"}}],\"type\":\"FeatureCollection\",\"crs\":{\"type\":\"name\",\"properties\":{\"name\":\"name1\"}}},\"Date\":" + expectedDateString + "}"; attributes.AddAttribute("test1", "value1"); IFeature feature = new Feature(new Point(23, 56), attributes); FeatureCollection featureCollection = new FeatureCollection(new Collection<IFeature> { feature }) { CRS = new NamedCRS("name1") }; string actual = new GeoJsonWriter().Write(new { featureCollection, Date = Date }); Assert.AreEqual(expectedResult, actual); }
public void ConvertGeoJsonToDataContainer_ShouldConvertToDataContainer() { var collection = new FeatureCollection { Features = { new Feature(new Point(new Coordinate(1, 2, 3)), new AttributesTable()) } }; var dataContainer = _converterService.ToDataContainer(collection.ToBytes(), "geojson").Result; Assert.AreEqual(0, dataContainer.routes.Count); Assert.AreEqual(1, dataContainer.markers.Count); }
private static FeatureCollection FeatureCollection(string geoJson) { var reader = new GeoJsonReader(); var featureCollection = new FeatureCollection(); try { featureCollection = reader.Read<FeatureCollection>(geoJson); if (featureCollection.Count == 0) { var feature = reader.Read<Feature>(geoJson); featureCollection.Add(feature); } } catch (Exception) { var feature = reader.Read<Feature>(geoJson); featureCollection.Add(feature); } return featureCollection; }
public void ItemTest() { IFeature feature = new Feature(); FeatureCollection target = new FeatureCollection(new Collection<IFeature> { feature }); IFeature actual = target[0]; Assert.AreSame(feature, actual); }
public void TypeTest() { FeatureCollection target = new FeatureCollection(); Assert.AreEqual("FeatureCollection", target.Type); }
public static string ToGeoJson(IEnumerable<System.Data.Entity.Spatial.DbGeometry> dbGeometrys, ProjectionInfo pStart, DataTable dataTable) { var pEnd = Definitions.WorldProjection; var dbGeometrys1 = dbGeometrys as IList<System.Data.Entity.Spatial.DbGeometry> ?? dbGeometrys.ToList(); var reader = new WKTReader(); var featureCollection = new FeatureCollection(); var columns = (from DataColumn column in dataTable.Columns select column.ColumnName).ToList(); for (var i = 0; i < dbGeometrys1.Count(); i++) { var geometry = GeometryHelper.Project(dbGeometrys1[i].MakeValid(), pStart, pEnd); var read = reader.Read(geometry.WellKnownValue.WellKnownText); var table = new AttributesTable(); foreach (var column in columns) { table.AddAttribute(column, dataTable.Rows[i][column]); } featureCollection.Add(new Feature(read, table)); } var geoJsonWriter = new GeoJsonWriter(); return geoJsonWriter.Write(featureCollection); }