public static void CorrectionCentroid() { //中心点数据 List <Coordinate> centroidPoints = new List <Coordinate>(80); StreamReader sr = new StreamReader(@"D:\OneDrive\2017研究生毕业设计\数据\项目用数据\中心点80.txt"); sr.ReadLine();//读取标题行 while (!sr.EndOfStream) { string[] line = sr.ReadLine().Split(','); centroidPoints.Add(new Coordinate(double.Parse(line[1]), double.Parse(line[2]))); } sr.Close(); //Bus数据,并且构造KD树 KdTree myKdtree = new KdTree(2); IFeatureSet busFS = FeatureSet.Open(@"D:\OneDrive\2017研究生毕业设计\数据\项目用数据\BusStopGauss.shp"); List <Coordinate> busStopPoints = new List <Coordinate>(busFS.NumRows()); HashSet <int> checkDuplicate = new HashSet <int>(); foreach (var item in busFS.Features) { var c = item.Coordinates[0]; busStopPoints.Add(c); myKdtree.Insert(new double[] { c.X, c.Y }, item); } Console.WriteLine("数据读取完毕,开始纠正数据"); IFeatureSet newCentroid = new FeatureSet(FeatureType.Point); newCentroid.Name = "优化过的中心点"; newCentroid.Projection = ProjectionInfo.FromEpsgCode(GAUSS_EPSG); int count = 0; foreach (var item in centroidPoints) { var nearsestBus = myKdtree.Nearest(new double[] { item.X, item.Y }, 3); bool addSuccess = false; IFeature addFeature = null; for (int i = 0; i < 3; i++) { IFeature f = nearsestBus[i] as IFeature; if (f.Coordinates[0].Distance(item) < 100) { if (checkDuplicate.Add(f.Fid)) { addFeature = newCentroid.AddFeature(f.BasicGeometry); addSuccess = true; } } } if (!addSuccess) { addFeature = newCentroid.AddFeature(new Point(item)); count++; } } Console.WriteLine("数据优化结束,共有{0}个数据没有优化", count); newCentroid.SaveAs("newCentroid2.shp", true); Console.ReadKey(); }
/// <summary> /// Builds a point feature set and adds a column and 3 points. /// </summary> /// <returns>The featureset that was build.</returns> public IFeatureSet BuildFeatureSet() { IFeatureSet fs = new FeatureSet(FeatureType.Point); fs.DataTable.Columns.Add("Test", typeof(string)); IFeature feat = fs.AddFeature(new Point(10, 10)); feat.DataRow["Test"] = "hello"; feat = fs.AddFeature(new Point(10, 20)); feat.DataRow["Test"] = "hello"; feat = fs.AddFeature(new Point(20, 10)); feat.DataRow["Test"] = "here"; return(fs); }
private void addLayer_Click(object sender, EventArgs e) { // Add Coordinate c = new Coordinate(1, 1); Coordinate c1 = new Coordinate(2, 2); FeatureSet fs = new FeatureSet(FeatureType.Point); fs.AddFeature(new DotSpatial.Topology.Point(c)); fs.AddFeature(new DotSpatial.Topology.Point(c1)); env = fs.Extent; MapPointLayer layer = new MapPointLayer(fs); map1.MapFrame.DrawingLayers.Add(layer); map1.Refresh(); }
public void CoordinateTypeWriteOnSaveAs() { var outfile = FileTools.GetTempFileName(".shp"); IFeatureSet fs = new FeatureSet(); var c = new Coordinate(10.1, 20.2, 3.3, 4.4); fs.CoordinateType = CoordinateType.Z; fs.Projection = KnownCoordinateSystems.Geographic.World.WGS1984; fs.DataTable.Columns.Add(new DataColumn("ID", typeof(int))); IFeature f = fs.AddFeature(new Point(c)); f.DataRow.BeginEdit(); f.DataRow["ID"] = 1; f.DataRow.EndEdit(); fs.SaveAs(outfile, true); var actual = FeatureSet.Open(outfile); try { Assert.AreEqual(fs.CoordinateType, actual.CoordinateType); } finally { FileTools.DeleteShapeFile(outfile); } }
public override string CreateFeature(ProjectionInfo proj_info, string directory) { if (FlowRate != null) { string filename = Path.Combine(directory, this.Name + ".shp"); var grid = (Owner as Modflow).Grid as MFGrid; FeatureSet fs = new FeatureSet(FeatureType.Point); fs.Name = this.Name; fs.Projection = proj_info; fs.DataTable.Columns.Add(new DataColumn("CELL_ID", typeof(int))); fs.DataTable.Columns.Add(new DataColumn("Layer", typeof(int))); fs.DataTable.Columns.Add(new DataColumn("Row", typeof(int))); fs.DataTable.Columns.Add(new DataColumn("Column", typeof(int))); fs.DataTable.Columns.Add(new DataColumn("ID", typeof(int))); fs.DataTable.Columns.Add(new DataColumn("Elevation", typeof(float))); for (int i = 0; i < NBDTIM; i++) { fs.DataTable.Columns.Add(new DataColumn("Flux Rate" + (i + 1), typeof(float))); } fs.DataTable.Columns.Add(new DataColumn("Name", typeof(string))); fs.DataTable.Columns.Add(new DataColumn(RegularGrid.ParaValueField, typeof(int))); var mat = FlowRate; for (int i = 0; i < FlowRate.Size[2]; i++) { int layer = (int)mat[0, 0, i]; int row = (int)mat[1, 0, i]; int col = (int)mat[2, 0, i]; var coor = grid.LocateCentroid(col, row); Point geom = new Point(coor); IFeature feature = fs.AddFeature(geom); feature.DataRow.BeginEdit(); feature.DataRow["CELL_ID"] = grid.Topology.GetID(row - 1, col - 1); feature.DataRow["Layer"] = layer; feature.DataRow["Row"] = row; feature.DataRow["Column"] = col; feature.DataRow["ID"] = (i + 1); feature.DataRow["Elevation"] = grid.GetElevationAt(row - 1, col - 1, layer - 1); feature.DataRow["Name"] = "Flow " + (i + 1); for (int j = 0; j < NBDTIM; j++) { feature.DataRow["Flux Rate" + (j + 1)] = mat[j + 4, 0, i]; } feature.DataRow[RegularGrid.ParaValueField] = 0; feature.DataRow.EndEdit(); } fs.SaveAs(filename, true); fs.Close(); return(filename); } else { return(null); } }
/// <summary> /// Creates a specified number of random point features inside a single polygon feature. /// </summary> /// <param name="constrainingFeature">Random points will be generated inside this polygon feature.</param> /// <param name="numberOfPoints">The number of points to be randomly generated.</param> /// <returns>A point feature set with the randomly created features.</returns> public static FeatureSet RandomPoints(Feature constrainingFeature, int numberOfPoints) { // this function generates random points within the boundaries of one polygon feature FeatureSet fsOut = new FeatureSet(FeatureType.Point); Random r = new Random(); int i = 0; while (i < numberOfPoints) { // make a random point somewhere in the rectangular extents of the feature double rndx = r.Next(0, 100000) / 100000.0; double rndy = r.Next(0, 100000) / 100000.0; var env = constrainingFeature.Geometry.EnvelopeInternal; var c = new Coordinate { X = (rndx * (env.Right() - env.MinX)) + env.MinX, Y = (rndy * (env.MaxY - env.Bottom())) + env.Bottom() }; // check if the point falls within the polygon featureset Point p = new Point(c); if (constrainingFeature.Geometry.Intersects(p)) { fsOut.AddFeature(p); i++; } } return(fsOut); }
public static void CentroidToShapefile() { OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "文本文件|*.txt;*.csv"; ofd.RestoreDirectory = true; if (ofd.ShowDialog() == DialogResult.OK) { StreamReader sr = new StreamReader(ofd.FileName); //string[] header = sr.ReadLine().Split(','); IFeatureSet oFS = new FeatureSet(FeatureType.Point); oFS.Projection = ProjectionInfo.FromEpsgCode(4326); oFS.Name = "BusStop"; oFS.DataTable.Columns.Add("Name", typeof(string)); while (!sr.EndOfStream) { string[] line = sr.ReadLine().Split(','); double x = double.Parse(line[2]); double y = double.Parse(line[3]); var xyCorrection = CoordinateTransformUtil.bd09towgs84(x, y); var fe = oFS.AddFeature(new Point(xyCorrection[0], xyCorrection[1])); fe.DataRow.BeginEdit(); fe.DataRow["Name"] = line[0]; fe.DataRow.EndEdit(); } oFS.SaveAs("BusStop.shp", true); sr.Close(); Console.WriteLine("Shapefile转换成功!"); Console.ReadKey(); } }
/// <summary> /// Creates a specified number of random point features inside a single polygon feature. /// </summary> /// <param name="ConstrainingFeature">Random points will be generated inside this polygon feature.</param> /// <param name="NumberOfPoints">The number of points to be randomly generated.</param> /// <returns>A point feature set with the randomly created features.</returns> public static FeatureSet RandomPoints(Feature ConstrainingFeature, int NumberOfPoints) { //This function generates random points within the boundaries of one polygon feature FeatureSet fsOut = new FeatureSet(); fsOut.FeatureType = FeatureType.Point; Coordinate c = new Coordinate(); Random r = new Random(); int i = 0; while (i < NumberOfPoints) { c = new Coordinate(); //make a random point somewhere in the rectangular extents of the feature double rndx = r.Next(0, 100000) / 100000.0; double rndy = r.Next(0, 100000) / 100000.0; c.X = rndx * (ConstrainingFeature.Envelope.Right() - ConstrainingFeature.Envelope.Left()) + ConstrainingFeature.Envelope.Left(); c.Y = rndy * (ConstrainingFeature.Envelope.Top() - ConstrainingFeature.Envelope.Bottom()) + ConstrainingFeature.Envelope.Bottom(); //check if the point falls within the polygon featureset if (ConstrainingFeature.Intersects(c)) { fsOut.AddFeature(new Feature(c)); i++; } } return(fsOut); }
public static void CreatePolygonFeatureSetAnd2AttributeColumns() { // See comments below this code for an updated version. // define the feature type for this file FeatureSet fs = new FeatureSet(FeatureType.Polygon); // Add Some Columns fs.DataTable.Columns.Add(new DataColumn("ID", typeof(int))); fs.DataTable.Columns.Add(new DataColumn("Text", typeof(string))); // create a geometry (square polygon) List <Coordinate> vertices = new List <Coordinate>(); vertices.Add(new Coordinate(0, 0)); vertices.Add(new Coordinate(0, 100)); vertices.Add(new Coordinate(100, 100)); vertices.Add(new Coordinate(100, 0)); Polygon geom = new Polygon(vertices); // add the geometry to the featureset. IFeature feature = fs.AddFeature(geom); // now the resulting features knows what columns it has // add values for the columns feature.DataRow.BeginEdit(); feature.DataRow["ID"] = 1; feature.DataRow["Text"] = "Hello World"; feature.DataRow.EndEdit(); // save the feature set fs.SaveAs("d:\\test.shp", true); }
public PointClassification ClassifyPoint(double latitude, double longitude) { FeatureSet pFeatureSet = new FeatureSet(); pFeatureSet.Projection = KnownCoordinateSystems.Geographic.World.WGS1984; DotSpatial.Topology.Point pPoint = new DotSpatial.Topology.Point(longitude, latitude); FeatureSet pPointFeatureSet = new FeatureSet(DotSpatial.Topology.FeatureType.Point); pPointFeatureSet.Projection = KnownCoordinateSystems.Geographic.World.WGS1984; pPointFeatureSet.AddFeature(pPoint); Extent pAffectedExtent = null; var result = fsWorldCountries.Select(pPointFeatureSet.Extent, out pAffectedExtent); foreach (IFeature feature in result) { PointClassification classification = new PointClassification(); classification.CountryCode = feature.DataRow["ADM0_A3"].ToString(); if (classification.CountryCode.Length == 3) { classification.CountryCode = ConvertISOCountryCode(classification.CountryCode); } classification.CountrySubdivision = feature.DataRow["NAME"].ToString(); classification.CountryName = feature.DataRow["ADMIN"].ToString(); return(classification); } return(null); // System.Diagnostics.Debug.WriteLine(featureL); }
public static IFeatureSet RoadNetworkToShapefile(RoadNetwork rn, string writefilename) { FeatureSet fs = new FeatureSet(FeatureType.Line); string filename = Path.GetFileNameWithoutExtension(writefilename); fs.Name = filename; fs.DataTable.Columns.Add("RoadID", typeof(long)); fs.DataTable.Columns.Add("RoadName", typeof(string)); fs.DataTable.Columns.Add("RoadFunction", typeof(byte)); fs.DataTable.Columns.Add("RoadLength", typeof(double)); fs.DataTable.Columns.Add("RoadAttribute", typeof(string)); for (int i = 0; i < rn.RoadCount; i++) { Road r = rn.GetRoadByIndex(i); var fe = fs.AddFeature(r); fe.DataRow.BeginEdit(); fe.DataRow["RoadID"] = r.RoadID; fe.DataRow["RoadName"] = r.RoadName; fe.DataRow["RoadFunction"] = r.RoadFunction; fe.DataRow["RoadLength"] = r.RoadLength; string attr = string.Empty; for (int j = 0; j < r.RoadAttribute.Count; j++) { attr += r.RoadAttribute[j].RoadFunction.ToString() + r.RoadAttribute[j].RoadAtrribute.ToString(); if (j != r.RoadAttribute.Count - 1) { attr += "|"; } } fe.DataRow["RoadAttribute"] = attr; fe.DataRow.EndEdit(); } fs.SaveAs(writefilename, true); return(fs); }
public void GetShapefile(string filepath) { FeatureSet fs = new FeatureSet(FeatureType.Point); fs.DataTable.Columns.Add(new DataColumn("ID", typeof(string))); fs.DataTable.Columns.Add(new DataColumn("Name", typeof(string))); fs.DataTable.Columns.Add(new DataColumn("Lat", typeof(double))); fs.DataTable.Columns.Add(new DataColumn("Lon", typeof(double))); fs.DataTable.Columns.Add(new DataColumn("Contam", typeof(string))); fs.DataTable.Columns.Add(new DataColumn("Trend", typeof(double))); fs.DataTable.Columns.Add(new DataColumn("Trending", typeof(string))); fs.DataTable.Columns.Add(new DataColumn("Rsquared", typeof(double))); fs.DataTable.Columns.Add(new DataColumn("MCL", typeof(double))); fs.DataTable.Columns.Add(new DataColumn("Units", typeof(string))); fs.DataTable.Columns.Add(new DataColumn("NumSamp", typeof(int))); fs.DataTable.Columns.Add(new DataColumn("LastDate", typeof(string))); fs.DataTable.Columns.Add(new DataColumn("Result", typeof(double))); fs.DataTable.Columns.Add(new DataColumn("Link", typeof(string))); for (int a = 0; a < WellList.Count; a++) { int c = WellList[a].GetTopTrendIndex(3); Coordinate vertices = new Coordinate(); vertices.X = WellList[a].LonDouble[c]; vertices.Y = WellList[a].LatDouble[c]; DotSpatial.Topology.Point Geom = new DotSpatial.Topology.Point(vertices); fs.AddFeature(Geom); fs.DataTable.Rows[a].BeginEdit(); fs.DataTable.Rows[a]["ID"] = WellList[a].ID; fs.DataTable.Rows[a]["Name"] = WellList[a].Names[c]; fs.DataTable.Rows[a]["Lat"] = WellList[a].LatDouble[c]; fs.DataTable.Rows[a]["Lon"] = WellList[a].LonDouble[c]; fs.DataTable.Rows[a]["Contam"] = WellList[a].Contaminate; fs.DataTable.Rows[a]["Trending"] = WellList[a].Trending[c]; fs.DataTable.Rows[a]["Trend"] = WellList[a].Trends[c]; fs.DataTable.Rows[a]["Rsquared"] = WellList[a].R2[c]; fs.DataTable.Rows[a]["MCL"] = WellList[a].MCL; fs.DataTable.Rows[a]["Units"] = WellList[a].Latest[c].UNITS; fs.DataTable.Rows[a]["NumSamp"] = WellList[a].SampsByName[c].Count; fs.DataTable.Rows[a]["LastDate"] = WellList[a].RecentSampleDate[c]; fs.DataTable.Rows[a]["Result"] = WellList[a].Results[c]; fs.DataTable.Rows[a]["Link"] = WellList[a].ChartURL[c]; fs.DataTable.Rows[a].EndEdit(); } fs.Projection = KnownCoordinateSystems.Geographic.NorthAmerica.NorthAmericanDatum1983; fs.SaveAs(savepath, true); //IFeatureSet buff = new FeatureSet(); //buff = fs.Buffer(.003, true); //string filepathB = filepath.Replace(".shp", "buffer.shp"); //buff.Projection = //KnownCoordinateSystems.Geographic.NorthAmerica.NorthAmericanDatum1983; //buff.SaveAs(filepathB, true); }
public static FeatureSet SHPLineDataHandler(FeatureSet fs, IndexedDictionary <string, string[]> data) { try { Debug.Write("\nCoor: " + Convert.ToDouble(data["coordinates"][1]) + "| " + Convert.ToDouble(data["coordinates"][2]) + "| " + Convert.ToDouble(data["coordinates"][3]) + "| " + Convert.ToDouble(data["coordinates"][4])); DotSpatial.Topology.Coordinate ptcoor1 = new DotSpatial.Topology.Coordinate(Convert.ToDouble(data["coordinates"][1]), Convert.ToDouble(data["coordinates"][2])); DotSpatial.Topology.Coordinate ptcoor2 = new DotSpatial.Topology.Coordinate(Convert.ToDouble(data["coordinates"][3]), Convert.ToDouble(data["coordinates"][4])); List <DotSpatial.Topology.Coordinate> lineCoor = new List <DotSpatial.Topology.Coordinate>(); lineCoor.Add(ptcoor1); lineCoor.Add(ptcoor2); LineString line = new LineString(lineCoor); DotSpatial.Data.IFeature feature = fs.AddFeature(line); //remove geometry data.Remove("Geometry"); //now fill in rest of the columns foreach (var item in data) { string dataType = data[item.Key][0]; string value = data[item.Key][1]; Debug.Write("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~SHP null AND dOUBLE DEBUG~~~~~~~~~~~~~~~~ VALUE : " + value + " =" + (string.IsNullOrEmpty(value))); //check if value is null - double dont accept string null values. need to fix it before sending. if (value.Equals("null") && dataType.Equals("Double")) { //for double double d; if (double.TryParse(value, out d)) { // valid number Debug.Write("\n~~~~VALID"); } else { // not a valid number Debug.Write("\n~~~~VALID Assigning 0"); value = "0"; } } if (!item.Key.Equals("Geometry") || !item.Key.Equals("coordinates")) { Debug.Write("\n~~SHP WRITE Property: " + item.Key); Debug.Write("\n~~SHP WRITE dataType: " + dataType); Debug.Write("\n~~SHP WRITE value: " + value); feature.DataRow.BeginEdit(); feature.DataRow[item.Key] = value; feature.DataRow.EndEdit(); } Debug.Write("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~SHP null AND dOUBLE DEBUG~~~~~~~~~~~~~~~~\n"); } } catch (SystemException ex) { Debug.Write("\n" + ex.ToString()); } return(fs); }
private void mapMain_MouseClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { //left click - fill array of coordinates Coordinate coord = mapMain.PixelToProj(e.Location); if (polygonmouseClick == true) { if (firstClick == true) { //Creat a list to contain the polygon coordinates List <Coordinate> polygonArray = new List <Coordinate>(); //Create an instance for LinearRing class. //We pass the polygon List to the constructor of this class LinearRing polygonGeometry = new LinearRing(polygonArray); //add polygonGeomety instance to polygonFeature IFeature polygonFeature = polygonF.AddFeature(polygonGeometry); //add first coordinate polygonFeature.Coordinates.Add(coord); //add to the list of coordinates xCoordinates.Add(coord.X); yCoordinates.Add(coord.Y); //set the polygon feature attribute polygonID = polygonID + 1; polygonFeature.DataRow["PolygonID"] = polygonID; firstClick = false; //Add volume data column polygonFeature.DataRow["Volume"] = 0; } else { //second or more clicks-add points to the existing feature IFeature existingFeature = (IFeature)polygonF.Features[polygonF.Features.Count - 1]; existingFeature.Coordinates.Add(coord); //add to the list of coordinates xCoordinates.Add(coord.X); yCoordinates.Add(coord.Y); //refresh the map if line has 2 or more points if (existingFeature.Coordinates.Count != 0) { //refresh the map polygonF.InitializeVertices(); mapMain.ResetBuffer(); } } } } }
public void SavePointToShapefileWithMandZ(CoordinateType c) { var fileName = FileTools.GetTempFileName(".shp"); try { var fs = new FeatureSet(FeatureType.Point) { Projection = KnownCoordinateSystems.Geographic.World.WGS1984, CoordinateType = c }; fs.AddFeature(new Point(new CoordinateZM(1, 2, 7, 4))); Assert.DoesNotThrow(() => fs.SaveAs(fileName, true)); var loaded = FeatureSet.Open(fileName); if (c == CoordinateType.Regular) { Assert.IsTrue(loaded.Features[0].Geometry.Coordinates[0] is Coordinate); Assert.IsFalse(loaded.Features[0].Geometry.Coordinates[0] is CoordinateZ); Assert.IsFalse(loaded.Features[0].Geometry.Coordinates[0] is CoordinateM); } else if (c == CoordinateType.M) { Assert.IsTrue(loaded.Features[0].Geometry.Coordinates[0] is CoordinateM); Assert.IsFalse(loaded.Features[0].Geometry.Coordinates[0] is CoordinateZ); if (loaded.Features[0].Geometry.Coordinates[0] is CoordinateM cm) { Assert.AreEqual(4, cm.M); Assert.AreEqual(4, loaded.Features[0].Geometry.MinM()); Assert.AreEqual(4, loaded.Features[0].Geometry.MaxM()); } } else if (c == CoordinateType.Z) { Assert.IsTrue(loaded.Features[0].Geometry.Coordinates[0] is CoordinateZM); if (loaded.Features[0].Geometry.Coordinates[0] is CoordinateZM cm) { Assert.AreEqual(7, cm.Z); Assert.AreEqual(7, loaded.Features[0].Geometry.MinZ()); Assert.AreEqual(7, loaded.Features[0].Geometry.MaxZ()); Assert.AreEqual(4, cm.M); Assert.AreEqual(4, loaded.Features[0].Geometry.MinM()); Assert.AreEqual(4, loaded.Features[0].Geometry.MaxM()); } } } finally { FileTools.DeleteShapeFile(fileName); } }
private IFeature ExtractGeographicData(XmlNode c) { string geoData = ""; IBasicGeometry geo = null; string[] pointValue = null; if (typeGeometry == DotSpatial.Topology.FeatureType.Point) { foreach (XmlNode e in c) { if (e.LocalName == Geometry) { geoData = e.InnerText; } } string point = Convert.ToString(geoData); pointValue = point.Split(' '); geo = new Point(Convert.ToDouble(pointValue[0]), Convert.ToDouble(pointValue[1])); } if (typeGeometry == DotSpatial.Topology.FeatureType.Polygon) { foreach (XmlNode e in c) { if (e.LocalName == Geometry) { var t = e.FirstChild.OuterXml; var s = new XmlSerializer(typeof(MultiSurfaceType)); MultiSurfaceType multi = s.Deserialize(new StringReader(t)) as MultiSurfaceType; geo = GetPolygon(multi); // geoData = e.InnerText; } } } if (typeGeometry == DotSpatial.Topology.FeatureType.Line) { foreach (XmlNode e in c) { if (e.LocalName == Geometry) { var t = e.FirstChild.OuterXml; var s = new XmlSerializer(typeof(MultiLineStringType)); MultiLineStringType multi = s.Deserialize(new StringReader(t)) as MultiLineStringType; geo = GetPolyline(multi); // geoData = e.InnerText; } } } IFeature feat = fea.AddFeature(geo); return(feat); }
private FeatureSet getFeatureSetFromRegularGrid(int Cols, int Rows, double MinLatitude, double MinLongitude, int ColsPerLongitude, int RowsPerLatitude) { try { FeatureSet fs = new FeatureSet(); fs.DataTable.Columns.Add("Col", typeof(int)); fs.DataTable.Columns.Add("Row", typeof(int)); for (int i = 0; i < Cols; i++) { for (int j = 0; j < Rows; j++) { Feature f = new Feature(); List <Coordinate> lstCoordinate = new List <Coordinate>(); Coordinate coordinate = new Coordinate(); coordinate.X = MinLongitude + i * (1.0000 / Convert.ToDouble(ColsPerLongitude)); coordinate.Y = MinLatitude + j * (1.0000 / Convert.ToDouble(RowsPerLatitude)); lstCoordinate.Add(coordinate); coordinate = new Coordinate(); coordinate.X = MinLongitude + (i + 1) * (1.0000 / Convert.ToDouble(ColsPerLongitude)); coordinate.Y = MinLatitude + j * (1.0000 / Convert.ToDouble(RowsPerLatitude)); lstCoordinate.Add(coordinate); coordinate = new Coordinate(); coordinate.X = MinLongitude + (i + 1) * (1.0000 / Convert.ToDouble(ColsPerLongitude)); coordinate.Y = MinLatitude + (j + 1) * (1.0000 / Convert.ToDouble(RowsPerLatitude)); lstCoordinate.Add(coordinate); coordinate = new Coordinate(); coordinate.X = MinLongitude + i * (1.0000 / Convert.ToDouble(ColsPerLongitude)); coordinate.Y = MinLatitude + (j + 1) * (1.0000 / Convert.ToDouble(RowsPerLatitude)); lstCoordinate.Add(coordinate); coordinate = new Coordinate(); coordinate.X = MinLongitude + i * (1.0000 / Convert.ToDouble(ColsPerLongitude)); coordinate.Y = MinLatitude + j * (1.0000 / Convert.ToDouble(RowsPerLatitude)); lstCoordinate.Add(coordinate); DotSpatial.Topology.Polygon p = new DotSpatial.Topology.Polygon(lstCoordinate.ToArray()); f.BasicGeometry = p; fs.AddFeature(f); fs.DataTable.Rows[i * Rows + j]["Col"] = i; fs.DataTable.Rows[i * Rows + j]["Row"] = j; } } return(fs); } catch { return(null); } }
public void MergeFeature(FeatureSet m_MergeFeaSet) { if (m_MergeFeaSet.Features.Count < 2 || m_CurrentFeaLyr == null) { return; } //确保目标图层只选中编辑的那一个要素,因为后面会把选中要素移除 //m_CurrentFeaLyr.UnSelectAll(); //m_CurrentFeaLyr.Selection.Clear(); //merge IFeature MergeFea = m_MergeFeaSet.GetFeature(0); for (int i = 0; i < m_MergeFeaSet.Features.Count; i++) { var fea = m_MergeFeaSet.GetFeature(i); MergeFea = MergeFea.Union(fea.Geometry); if (MergeFea == null) { break; } } lFeaM = m_InputFeaSet.AddFeature(MergeFea.Geometry); m_CurrentFeaLyr.RemoveSelectedFeatures(); MainWindow.m_DotMap.ResetBuffer(); MainWindow.m_DotMap.Refresh(); if (MessageBox.Show("Save edit?", "", MessageBoxButton.YesNo) == MessageBoxResult.Yes) { m_CurrentFeaLyr.FeatureSet.Save(); MessageBox.Show("Save successfully!"); } //移除图层重新加载,因为底层bug 移动节点之后选择要素会报错。 MainWindow.m_AddFeaType = Enum.FeaType.None; MainWindow.m_DotMap.FunctionMode = FunctionMode.None; MainWindow.m_DotMap.Cursor = System.Windows.Forms.Cursors.Default; string shpPath = m_CurrentFeaLyr.FeatureSet.FilePath; string name = m_CurrentFeaLyr.LegendText; var symbol = m_CurrentFeaLyr.Symbolizer; var extent = m_CurrentFeaLyr.Extent; IFeatureSet s = Shapefile.Open(shpPath); MainWindow.m_DotMap.Layers.Remove(m_CurrentFeaLyr as IMapLayer); var result = MainWindow.m_DotMap.Layers.Add(s); result.Symbolizer = symbol; result.Projection = MainWindow.m_DotMap.Projection; result.LegendText = name; //result.Select((result as FeatureLayer).FeatureSet.Features[(result as FeatureLayer).FeatureSet.Features.Count - 1]); this.Close(); }
public static IGeometry Project(IGeometry geometry, ProjectionInfo pStart, ProjectionInfo pEnd) { var featureSet = new FeatureSet(); featureSet.AddFeature(geometry.ToDotSpatial()); featureSet.Projection = pStart; featureSet.Reproject(pEnd); return (GeometryConverter.ToGeoAPI( ((featureSet.Features[0].BasicGeometry as DotSpatial.Topology.IGeometry)))); }
public void SavePointToShapefileWithMandZ(CoordinateType c) { var fileName = FileTools.GetTempFileName(".shp"); try { var fs = new FeatureSet(FeatureType.Point) { Projection = KnownCoordinateSystems.Geographic.World.WGS1984, CoordinateType = c }; fs.AddFeature(new Point(new Coordinate(1, 2, 7, 4))); Assert.DoesNotThrow(() => fs.SaveAs(fileName, true)); var loaded = FeatureSet.Open(fileName); if (c == CoordinateType.Regular) { // regular coordinates don't have m values Assert.AreEqual(double.NaN, loaded.Features[0].Geometry.Coordinates[0].M); Assert.AreEqual(double.NaN, loaded.Features[0].Geometry.EnvelopeInternal.Minimum.M); Assert.AreEqual(double.NaN, loaded.Features[0].Geometry.EnvelopeInternal.Maximum.M); } else { // m or z coordinates have m values Assert.AreEqual(4, loaded.Features[0].Geometry.Coordinates[0].M); Assert.AreEqual(4, loaded.Features[0].Geometry.EnvelopeInternal.Minimum.M); Assert.AreEqual(4, loaded.Features[0].Geometry.EnvelopeInternal.Maximum.M); } if (c == CoordinateType.Z) { // z coordinates have z values Assert.AreEqual(7, loaded.Features[0].Geometry.Coordinates[0].Z); Assert.AreEqual(7, loaded.Features[0].Geometry.EnvelopeInternal.Minimum.Z); Assert.AreEqual(7, loaded.Features[0].Geometry.EnvelopeInternal.Maximum.Z); } else { // regular and m coordinates don't have z values Assert.AreEqual(double.NaN, loaded.Features[0].Geometry.Coordinates[0].Z); Assert.AreEqual(double.NaN, loaded.Features[0].Geometry.EnvelopeInternal.Minimum.Z); Assert.AreEqual(double.NaN, loaded.Features[0].Geometry.EnvelopeInternal.Maximum.Z); } } finally { FileTools.DeleteShapeFile(fileName); } }
private void SetupResultsMapGroup(Core.Result.IResultSet set) { if (this.resultsGroup == null) { this.resultsGroup = new DotSpatial.Controls.MapGroup(); this.resultsGroup.LegendText = "Results"; this.resultsGroup.SelectionEnabled = true; this.resultsGroup.IsVisible = false; this.map.Layers.Add(this.resultsGroup); } if (set == null) { if (this.resultsLayer != null) { this.resultsGroup.Layers.Remove(this.resultsLayer); this.resultsLayer = null; } this.curResultsSet = null; this.resultsGroup.IsVisible = false; return; } this.resultsGroup.IsVisible = true; if (this.resultsGroup.Layers.Count > 0) { this.resultsGroup.Layers.Clear(); } this.curResultsSet = set; FeatureSet featureSet = new FeatureSet(FeatureType.Line); featureSet.Projection = this.map.Projection; featureSet.DataTable.Columns.Add(new DataColumn("LayerName", typeof(string))); foreach (var layer in this.curResultsSet.LayerNames) { var points = this.curResultsSet.GetDataset(layer); List <Coordinate> coords = new List <Coordinate>(); for (int i = 0; i <= points.GetUpperBound(0); i++) { coords.Add(new Coordinate(points[i, 0], points[i, 1])); } var feature = featureSet.AddFeature(new LineString(coords)); feature.DataRow["LayerName"] = layer; } this.resultsLayer = new MapLineLayer(featureSet); this.resultsLayer.Symbology.EditorSettings.ExcludeExpression = "[LayerName] <> ''"; this.resultsGroup.Layers.Add(this.resultsLayer); }
/// <summary> /// Erase features from one feature set where they are intersected by another feature set. /// </summary> /// <param name="targetFeatures">Features which will be erased in part or whole.</param> /// <param name="sourceFeatures">Features which represent areas to erase.</param> /// <param name="cancelProgressHandler">Optional parameter to report progress and cancel entire process if needed.</param> /// <returns>A point feature set with the randomly created features.</returns> public static FeatureSet EraseFeatures(IFeatureSet targetFeatures, IFeatureSet sourceFeatures, ICancelProgressHandler cancelProgressHandler = null) { if (targetFeatures == null || sourceFeatures == null) { return(null); } // Erase features from one feature set where they are intersected by another feature set // Note: we use the ShapeIndices here rather than for each feature in featureset.features as a memory management technique. // The current version does not preserve any attribute info. // Dan Ames 2/27/2013 FeatureSet resultFeatures = new FeatureSet(); // the resulting featureset resultFeatures.CopyTableSchema(targetFeatures); // set up the data table in the new feature set for (short i = 0; i <= targetFeatures.ShapeIndices.Count - 1; i++) { var tf = targetFeatures.GetFeature(i); // get the full undifferenced feature for (short j = 0; j <= sourceFeatures.ShapeIndices.Count - 1; j++) { var sf = sourceFeatures.GetFeature(j); if (sf.Geometry.Envelope.Intersects(tf.Geometry.Envelope)) { tf = tf.Difference(sf.Geometry); // clip off any pieces of SF that overlap FR } if (tf == null) { // sometimes difference leaves nothing left of a feature break; } } if (tf != null) { resultFeatures.AddFeature(tf.Geometry).CopyAttributes(targetFeatures.GetFeature(i)); // add the fully clipped feature to the results } if (cancelProgressHandler != null) { if (cancelProgressHandler.Cancel) { return(null); } int progress = Convert.ToInt32(i * 100 / targetFeatures.ShapeIndices.Count); cancelProgressHandler.Progress(string.Empty, progress, string.Empty); } } return(resultFeatures); }
public static MemoryStream GenerateShapeFile(Collection <NatureArea> natureAreas, int epsgCode) { // Return empty memory stream if there are no nature areas or no epsg code: if (natureAreas.Count == 0 || epsgCode < 0) { return(new MemoryStream()); } // Define a new set of features and set projection: FeatureSet featureSets = new FeatureSet { Projection = ProjectionInfo.FromEpsgCode(epsgCode) }; // Add data columns featureSets.DataTable.Columns.Add(new DataColumn("LocalId", typeof(string))); featureSets.DataTable.Columns.Add(new DataColumn("Nivå", typeof(string))); featureSets.DataTable.Columns.Add(new DataColumn("NiN", typeof(string))); // Create geometry objects: foreach (var natureArea in natureAreas) { if (natureArea.Area == null) { continue; } IFeature feature = featureSets.AddFeature(DotSpatialGeometry.GetGeometry(natureArea.Area)); // Adding values for the data columns feature.DataRow.BeginEdit(); feature.DataRow["LocalId"] = natureArea.UniqueId.LocalId.ToString(); feature.DataRow["Nivå"] = Naturnivå.TilNavn(natureArea.Nivå); feature.DataRow["NiN"] = FormatNatureAreaTypes(natureArea.Parameters); feature.DataRow.EndEdit(); } // Create temporary directory: string tempDirectoryPath = GetTempDirectoryPath(); // Save the feature set: featureSets.SaveAs(tempDirectoryPath + "\\TempShapeFiles\\data.shp", true); // Zip all shape files: ZipFile.CreateFromDirectory(tempDirectoryPath + "\\TempShapeFiles", tempDirectoryPath + "\\data.zip"); // Read the zip file: var bytes = File.ReadAllBytes(tempDirectoryPath + "\\data.zip"); // Delete the temporary directory: Directory.Delete(tempDirectoryPath, true); return(new MemoryStream(bytes)); }
// metric coordinates public static IFeatureSet CreateUserInputLayer(double lon, double lat, double radius, string workdir) { FeatureSet infs = new FeatureSet(DotSpatial.Topology.FeatureType.Point); infs.Projection = KnownCoordinateSystems.Projected.WorldSpheroid.Mercatorsphere; DotSpatial.Data.Feature center = new DotSpatial.Data.Feature(new Coordinate(lon, lat)); infs.AddFeature(center); var fs = infs.Buffer(radius, false); fs.SaveAs(WORKSPACE_DIR + workdir + "/usr.shp", true); return(fs); }
public void AddMustNotReplaceFeatureRow() { var parent = new FeatureSet(FeatureType.Point); var target = parent.Features; DataRow expected = null; target.FeatureAdded += (sender, args) => expected = args.Feature.DataRow; var addedFeature = parent.AddFeature(Point.Empty); var actual = addedFeature.DataRow; Assert.AreEqual(expected, actual); }
/// <summary> /// Add the features from SourceFeatures to the TargetFeatures feature set. /// </summary> /// <param name="targetFeatures">Feature set to which features will be added.</param> /// <param name="sourceFeatures">Source of features to add to the target feature set. </param> /// <returns>A point feature set with the randomly created features.</returns> public static FeatureSet AppendFeatures(FeatureSet targetFeatures, FeatureSet sourceFeatures) { // Add the features from SourceFeatures to the TargetFeatures feature set // Note: we use the ShapeIndices here rather than for each feature in featureset.features as a memory management technique. // Dan Ames 2/27/2013 for (short j = 0; j <= sourceFeatures.ShapeIndices.Count - 1; j++) { var sf = sourceFeatures.GetFeature(j); targetFeatures.AddFeature(sf.Geometry).CopyAttributes(sf); // by default this will try to copy attributes over that have the same name. } return(targetFeatures); }
/// <summary> /// Add the features from SourceFeatures to the TargetFeatures feature set. /// </summary> /// <param name="TargetFeatures">Feature set to which features will be added.</param> /// <param name="SourceFeatures">Source of features to add to the target feature set. </param> /// <returns>A point feature set with the randomly created features.</returns> public static FeatureSet AppendFeatures(FeatureSet TargetFeatures, FeatureSet SourceFeatures) { //Add the features from SourceFeatures to the TargetFeatures feature set //Note: we use the ShapeIndices here rather than for each feature in featureset.features as a memory management technique. //Dan Ames 2/27/2013 IFeature SF; for (Int16 j = 0; j <= SourceFeatures.ShapeIndices.Count - 1; j++) { SF = SourceFeatures.GetFeature(j); //TODO jany_ why call get feature twice instead of using sf to copy attributes? TargetFeatures.AddFeature(SF.Geometry).CopyAttributes(SourceFeatures.GetFeature(j)); //by default this will try to copy attributes over that have the same name. } return(TargetFeatures); }
/// <summary> /// Get X,Y axis expressed by longitude and latitude /// </summary> /// <returns>mat[2][], mat[0] is longitude, mat[1] is latitude </returns> public float[][] GetLonLatAxis() { var lonlat = new float[2][]; lonlat[0] = new float[ColumnCount]; lonlat[1] = new float[RowCount]; var wgs84 = ProjectionInfo.FromEpsgCode(4326); IFeatureSet fs_lon = new FeatureSet(FeatureType.Point); fs_lon.Projection = this.Projection; for (int c = 0; c < ColumnCount; c++) { var vertice = LocateCentroid(c + 1, 1); Point pt = new Point(vertice); fs_lon.AddFeature(pt); } if (fs_lon.Projection != null) { fs_lon.Reproject(wgs84); } for (int c = 0; c < ColumnCount; c++) { var fea = fs_lon.GetFeature(c).Geometry.Coordinate; lonlat[0][c] = (float)fea.X; } IFeatureSet fs_lat = new FeatureSet(FeatureType.Point); fs_lat.Projection = this.Projection; for (int r = 0; r < RowCount; r++) { var vertice = LocateCentroid(1, r + 1); Point pt = new Point(vertice); fs_lat.AddFeature(pt); } if (fs_lat.Projection != null) { fs_lat.Reproject(wgs84); } for (int r = 0; r < RowCount; r++) { var fea = fs_lat.GetFeature(r).Geometry.Coordinate; lonlat[1][r] = (float)fea.Y; } return(lonlat); }
public void Add_MustNotReplaceFeatureRow() { var parent = new FeatureSet(FeatureType.Point); var target = parent.Features; DataRow expected = null; target.FeatureAdded += delegate(object sender, FeatureEventArgs args) { expected = args.Feature.DataRow; }; var addedFeature = parent.AddFeature(new Point()); var actual = addedFeature.DataRow; Assert.AreEqual(expected, actual); }
private static IFeatureSet UnionAll(IFeatureSet fs) { FeatureSet fsunion = new FeatureSet(); fsunion.CopyTableSchema(fs); fsunion.Projection = fs.Projection; IFeature f = fs.Features[0]; for (int i = 1; i < fs.Features.Count; i++) { f = f.Union(fs.Features[i], fsunion, FieldJoinType.LocalOnly); } fsunion.AddFeature(f.Geometry); //TODO jany_ why union feature if only geometry is used to create new feature? return(fsunion); }
private static IFeatureSet UnionAll(IFeatureSet fs) { FeatureSet fsunion = new FeatureSet(); fsunion.CopyTableSchema(fs); fsunion.Projection = fs.Projection; IFeature f = fs.Features[0]; for (int i = 1; i < fs.Features.Count; i++) { f = f.Union(fs.Features[i], fsunion, FieldJoinType.LocalOnly); } fsunion.AddFeature(f); return(fsunion); }
public void CoordinateType_WriteOnSaveAs() { var outfile = FileTools.GetTempFileName(".shp"); IFeatureSet fs = new FeatureSet(); var c = new Coordinate(10.1, 20.2, 3.3, 4.4); IFeature f = new Feature(c); fs.CoordinateType = CoordinateType.Z; fs.Projection = KnownCoordinateSystems.Geographic.World.WGS1984; fs.DataTable.Columns.Add(new DataColumn(("ID"), typeof(int))); f = fs.AddFeature(f); f.ShapeType = ShapeType.PointZ; f.DataRow.BeginEdit(); f.DataRow["ID"] = 1; f.DataRow.EndEdit(); fs.SaveAs(outfile, true); var actual = FeatureSet.Open(outfile); try { Assert.AreEqual(fs.CoordinateType, actual.CoordinateType); } finally { FileTools.DeleteShapeFile(outfile); } }
public void UtmProjection_SamePoints_AfterSaveLoadShapeFile() { var fs = new FeatureSet(FeatureType.Point) { Projection = KnownCoordinateSystems.Projected.UtmWgs1984.WGS1984UTMZone33N // set any UTM projection }; const double originalX = 13.408056; const double originalY = 52.518611; var wgs = KnownCoordinateSystems.Geographic.World.WGS1984; var c = new[] { originalX, originalY }; var z = new[] { 0.0 }; Reproject.ReprojectPoints(c, z, wgs, fs.Projection, 0, 1); var pt = new Point(c[0], c[1]); fs.AddFeature(pt); var tmpFile = FileTools.GetTempFileName(".shp"); fs.SaveAs(tmpFile, true); try { // Now try to open saved shapefile // Points must have same location in WGS1984 var openFs = FeatureSet.Open(tmpFile); var fs0 = (Point) openFs.Features[0].BasicGeometry; var c1 = new[] {fs0.X, fs0.Y}; Reproject.ReprojectPoints(c1, z, openFs.Projection, wgs, 0, 1); // reproject back to wgs1984 Assert.IsTrue(Math.Abs(originalX - c1[0]) < 1e-8); Assert.IsTrue(Math.Abs(originalY - c1[1]) < 1e-8); } finally { FileTools.DeleteShapeFile(tmpFile); } }