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))); }
/// <summary> /// Creates a new polygon featureset that is created by buffering each of the individual shapes. /// </summary> /// <param name="self">The IFeatureSet to buffer</param> /// <param name="distance">The double distance to buffer</param> /// <param name="copyAttributes">Boolean, if this is true, then the new featureset will have /// the same attributes as the original.</param> /// <returns>The newly created IFeatureSet</returns> public static IFeatureSet Buffer(this IFeatureSet self, double distance, bool copyAttributes) { // Dimension the new, output featureset. Buffered shapes are polygons, even if the // original geometry is a point or a line. IFeatureSet result = new FeatureSet(FeatureType.Polygon); result.CopyTableSchema(self); result.Projection = self.Projection; // Cycle through the features, and buffer each one separately. foreach (IFeature original in self.Features) { // Actually calculate the buffer geometry. IFeature buffer = original.Buffer(distance); // Add the resulting polygon to the featureset result.Features.Add(buffer); // If copyAttributes is true, then this will copy those attributes from the original. if (copyAttributes) { // Accessing the attributes should automatically load them from the datasource if // they haven't been loaded already. buffer.CopyAttributes(original); } } return result; }
/// <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 void CreateFromFeatureSet(FeatureSet fs, string imgField, string OnCLickFiled,string aRefField, string OnMouseOverField, string OnMouseOutField, string dxField, string dyField) { SetMarkNumber(fs.Features.Count); int i = 0; foreach (Feature f in fs.Features) { if (f.Coordinates.Count>0) { _crds[i] = f.Coordinates[0]; _imgs[i] = Convert.ToString(f.DataRow[imgField]); if (OnCLickFiled != "" & OnCLickFiled != null) _OnClick[i] = Convert.ToString(f.DataRow[OnCLickFiled]); if (aRefField != "" & aRefField != null) _aRef[i] = Convert.ToString(f.DataRow[aRefField]); if (OnMouseOverField != "" & OnMouseOverField != null) _OnMouseOver[i] = Convert.ToString(f.DataRow[OnMouseOverField]); if (OnMouseOutField != "" & OnMouseOutField != null) _OnMouseOut[i] = Convert.ToString(f.DataRow[OnMouseOutField]); _dxy[i].X = Convert.ToInt32(f.DataRow[dxField]); _dxy[i].Y = Convert.ToInt32(f.DataRow[dyField]); } i++; } }
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); }
/// <summary> /// Generates an empty featureset that has the combined fields from this featureset /// and the specified featureset. /// </summary> /// <param name="self">This featureset</param> /// <param name="other">The other featureset to combine fields with.</param> /// <returns></returns> public static IFeatureSet CombinedFields(this IFeatureSet self, IFeatureSet other) { IFeatureSet result = new FeatureSet(self.FeatureType); Dictionary<string, DataColumn> resultColumns = new Dictionary<string, DataColumn>(); foreach (DataColumn dc in self.DataTable.Columns) { string name = dc.ColumnName; int i = 1; while (resultColumns.ContainsKey(name)) { name = dc.ColumnName + i; i++; } resultColumns.Add(name, dc); } foreach (DataColumn dc in other.DataTable.Columns) { string name = dc.ColumnName; int i = 1; while (resultColumns.ContainsKey(name)) { name = dc.ColumnName + i; i++; } resultColumns.Add(name, dc); } foreach (KeyValuePair<string, DataColumn> pair in resultColumns) { result.DataTable.Columns.Add(new DataColumn(pair.Key, pair.Value.DataType)); } return result; }
/// <summary> /// Creates a new Line Feature Set parameter /// </summary> /// <param name="name">The name of the parameter</param> public LineFeatureSetParam(string name) { Name = name; Value = new FeatureSet(); ParamVisible = ShowParamInModel.Always; ParamType = "DotSpatial LineFeatureSet Param"; DefaultSpecified = false; }
/// <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); TargetFeatures.AddFeature(SF).CopyAttributes(SourceFeatures.GetFeature(j)); //by default this will try to copy attributes over that have the same name. } return TargetFeatures; }
public void GetAttributes_WithFieldNames() { var fs = new FeatureSet(FeatureType.Point); fs.DataTable.Columns.Add("Column1"); fs.DataTable.Columns.Add("Column2"); fs.AddFeature(new Point(0, 0)); var fl = new PointLayer(fs); var target = new IndexSelection(fl); var attributesTable = target.GetAttributes(0, 1, new[] {"Column1"}); Assert.AreEqual(1, attributesTable.Columns.Count); Assert.AreEqual("Column1", attributesTable.Columns[0].ColumnName); }
/// <summary> /// The Voronoi Graph calculation creates a delaunay tesselation where /// each point is effectively converted into triangles. /// </summary> /// <param name="points">The points to use for creating the tesselation.</param> /// <returns>The generated line featureset.</returns> public static IFeatureSet DelaunayLines(IFeatureSet points) { double[] vertices = points.Vertex; VoronoiGraph gp = Fortune.ComputeVoronoiGraph(vertices); FeatureSet result = new FeatureSet(); foreach (VoronoiEdge edge in gp.Edges) { Coordinate c1 = edge.RightData.ToCoordinate(); Coordinate c2 = edge.LeftData.ToCoordinate(); LineString ls = new LineString(new List<Coordinate> { c1, c2 }); Feature f = new Feature(ls); result.AddFeature(f); } return result; }
public static System.Data.Entity.Spatial.DbGeometry Project(System.Data.Entity.Spatial.DbGeometry source, ProjectionInfo pStart, ProjectionInfo pEnd) { var wkt = source.WellKnownValue.WellKnownText; var wktReader = new WKTReader(); var geometry = wktReader.Read(wkt); var featureSet = new FeatureSet(); featureSet.Features.Add(geometry.ToDotSpatial()); featureSet.Projection = pStart; featureSet.Reproject(pEnd); var projected = (featureSet.Features.First().BasicGeometry as IGeometry).ToGeoAPI(); var wktWriter = new WKTWriter(); var projectedWkt = wktWriter.Write(projected); return System.Data.Entity.Spatial.DbGeometry.FromText(projectedWkt); }
/// <summary> /// The Voronoi Graph calculation creates the lines that form a voronoi diagram. /// </summary> /// <param name="points">The points to use for creating the tesselation.</param> /// <returns>An IFeatureSet that is the resulting set of lines in the diagram.</returns> public static IFeatureSet VoronoiLines(IFeatureSet points) { double[] vertices = points.Vertex; VoronoiGraph gp = Fortune.ComputeVoronoiGraph(vertices); HandleBoundaries(gp, points.Extent.ToEnvelope()); FeatureSet result = new FeatureSet(); foreach (VoronoiEdge edge in gp.Edges) { Coordinate c1 = edge.VVertexA.ToCoordinate(); Coordinate c2 = edge.VVertexB.ToCoordinate(); LineString ls = new LineString(new List<Coordinate> { c1, c2 }); Feature f = new Feature(ls); result.AddFeature(f); } return result; }
public static List<IGeometry> Project(List<IGeometry> toList, ProjectionInfo pStart, ProjectionInfo pEnd) { var geometryCollection = new GeometryCollection(toList.ToArray()); var collection = geometryCollection.ToDotSpatial(); var featureSet = new FeatureSet(); foreach (var geo in collection.Geometries) { featureSet.Features.Add(geo); } featureSet.Projection = pStart; featureSet.Reproject(pEnd); var dotSpatialProjectedGeos = featureSet.Features.Select(x => x.BasicGeometry as DotSpatial.Topology.IGeometry).ToList(); var result = dotSpatialProjectedGeos.Select( dotSpatialProjectedGeo => GeometryConverter.ToGeoAPI((dotSpatialProjectedGeo))) .ToList(); return result; }
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { changeButtonStatus(false); if (!string.IsNullOrEmpty(textBox1.Text)) { Feature f = new Feature(); fs = new FeatureSet(f.FeatureType); var dataTable = new DataTable(); dataTable.Columns.Add(new DataColumn("X", typeof(double))); dataTable.Columns.Add(new DataColumn("Y", typeof(double))); dataTable.Columns.Add(new DataColumn("Z", typeof(double))); for (int i = 0; i < textBox1.Lines.Length; i++) { var data = textBox1.Lines[i].Split(',').Where(c => !string.IsNullOrEmpty(c)) .Select(c => Convert.ToDouble(c)).ToArray(); if (data.Length == 3) { var c = new Coordinate(data); //var c = new Coordinate(Convert.ToDouble(data[0]), Convert.ToDouble(data[1]), Convert.ToDouble(data[2])); fs.Features.Add(c); dataTable.Rows.Add(data[0],data[1],data[2]); } backgroundWorker1.ReportProgress((i + 1)); } dataTable.TableName = "ImportData"; fs.DataTable = dataTable; fs.Name = "Imported Data"; } changeButtonStatus(true); }
/// <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 IFeature TF, SF; //a single output feature ResultFeatures.CopyTableSchema(TargetFeatures); //set up the data table in the new feature set for (Int16 i = 0; i <= TargetFeatures.ShapeIndices.Count - 1; i++) { TF = TargetFeatures.GetFeature(i); //get the full undifferenced feature for (Int16 j = 0; j <= SourceFeatures.ShapeIndices.Count - 1; j++) { SF = SourceFeatures.GetFeature(j); if (SF.Envelope.Intersects(TF.Envelope)) { TF = TF.Difference(SF); //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).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; }
private IFeatureSet CreatefilterFeatureSet() { IFeatureSet data1 = new FeatureSet(FeatureType.Point); data1.Projection = _originalData.Projection; data1.DataTable.Columns.Add(new System.Data.DataColumn(this.Field, typeof(double))); data1.DataTable.Columns.Add(new System.Data.DataColumn("Repeat", typeof(string))); List<int> listt = _originalData.SelectIndexByAttribute(Filterfields); foreach (int index in listt) { IFeature fea1 = _originalData.GetFeature(index); IFeature d=data1.AddFeature((IBasicGeometry)fea1); d.DataRow[this.Field] = fea1.DataRow[this.Field]; } return data1; }
/// <summary> /// Generates an empty featureset that has the combined fields from this featureset /// and the specified featureset. /// </summary> /// <param name="self">This featureset</param> /// <param name="other">The other featureset to combine fields with.</param> /// <returns></returns> public static IFeatureSet CombinedFields(this IFeatureSet self, IFeatureSet other) { IFeatureSet result = new FeatureSet(self.FeatureType); var uniqueNames = new HashSet<string>(); foreach (var fs in new []{self, other}) { foreach (DataColumn dc in fs.DataTable.Columns) { var name = dc.ColumnName; var i = 1; while (uniqueNames.Contains(name)) { name = dc.ColumnName + i; i++; } uniqueNames.Add(name); result.DataTable.Columns.Add(new DataColumn(name, dc.DataType)); } } return result; }
/// <summary> /// Creates a specified number of random point features inside multiple polygon features in a feature set. /// </summary> /// <param name="ConstrainingFeatures">Random points will be generated inside all features in this feature set.</param> /// <param name="NumberOfPoints">The number of points to be randomly generated.</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 IFeatureSet RandomPoints(IFeatureSet ConstrainingFeatures, int NumberOfPoints, IFeatureSet fsOut = null, ICancelProgressHandler cancelProgressHandler = null) { //This function generates random points within the boundaries of all polygon features in a feature set if (fsOut == null) { 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 set double rndx = r.Next(0, 100000) / 100000.0; double rndy = r.Next(0, 100000) / 100000.0; c.X = rndx * (ConstrainingFeatures.Extent.MaxX - ConstrainingFeatures.Extent.MinX) + ConstrainingFeatures.Extent.MinX; c.Y = rndy * (ConstrainingFeatures.Extent.MaxY - ConstrainingFeatures.Extent.MinY) + ConstrainingFeatures.Extent.MinY; //check if the point falls within the polygon featureset foreach (Feature f in ConstrainingFeatures.Features) { if (f.Intersects(c)) { fsOut.AddFeature(new Feature(c)); i++; } } if (cancelProgressHandler != null) { if (cancelProgressHandler.Cancel) { return null; } int progress = Convert.ToInt32(i * 100 / NumberOfPoints); cancelProgressHandler.Progress(String.Empty, progress, String.Empty); } } return fsOut; }
internal FeatureSet CreateFeatureSet() { FeatureSet featureSet = new FeatureSet(FeatureType.Line); featureSet.Projection = KnownCoordinateSystems.Geographic.World.WGS1984; foreach (ReferentielMultiLineString mls in this.MultiLineStrings) { List<LineString> lineStrings = new List<LineString>(); foreach (ReferentielLineString ls in mls.LineStrings) { List<Coordinate> coordinates = new List<Coordinate>(); for (int i = 0; i < (ls.Segements.Count - 1); i++) { coordinates.Add(ls.Segements[i].CoordDeb); } coordinates.Add(ls.Segements.Last().CoordDeb); coordinates.Add(ls.Segements.Last().CoordFin); LineString fsLs = new LineString(coordinates); lineStrings.Add(fsLs); } MultiLineString fsMls = new MultiLineString(lineStrings); featureSet.AddFeature(fsMls); } return featureSet; }
/// <summary> /// As an example, choosing myFeatureLayer.SelectedFeatures.ToFeatureSet creates a new set. /// </summary> /// <returns>An in memory featureset that has not yet been saved to a file in any way.</returns> public FeatureSet ToFeatureSet() { FeatureSet fs = new FeatureSet(ToFeatureList()); // the output features will be copied. if (fs.Features.Count == 0) { if (_filter.FeatureList.Count > 0) { fs.CopyTableSchema(_filter.FeatureList[0].ParentFeatureSet); } } return fs; }
public static void exportSDFtoShapeFile(string inputsdfFile, string outputShapefile) { using (TextReader reader = new StreamReader(inputsdfFile)) { string line; while ((line = reader.ReadLine()) != null) { if (line.Trim() == "BEGIN BOUNDS:") { FeatureSet fs = new FeatureSet(FeatureType.Polygon); fs.DataTable.Columns.AddRange(new DataColumn[] { new DataColumn("ProfileName" , typeof(string)), new DataColumn("ProfileDate" , typeof(string)), }); fs.AddFid(); while ((line = reader.ReadLine()) != null) { if (line.Trim() == "END BOUNDS:") { fs.SaveAs(outputShapefile, true); break; } else if (line.Trim() == "PROFILE LIMITS:") { string profileName = ""; bool isDate = false; DateTime dateTime = DateTime.Now; IList<Coordinate> coordinates = new List<Coordinate>(); while ((line = reader.ReadLine()) != null) { string[] cols; double x, y, z; if (line.Trim() == "END:") { Polygon p = new Polygon(coordinates); IFeature f = fs.AddFeature(p); f.DataRow.BeginEdit(); f.DataRow["ProfileName"] = profileName; if (isDate) { f.DataRow["ProfileDate"] = dateTime.ToString("yyyy/MM/dd HH:mm:ss"); } f.DataRow.EndEdit(); break; } else if (line.Trim() == "POLYGON:") { } else if ((cols = line.Trim().Split(new string[] { ":", "," }, StringSplitOptions.RemoveEmptyEntries)).Length > 1) { if (cols[0].Trim() == "PROFILE ID") { profileName = cols[1].Trim(); cols = profileName.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); int day, year; if (cols.Length == 2 && int.TryParse(cols[0].Substring(0, 2), out day) && int.TryParse(cols[0].Substring(5, 4), out year) && months.ContainsKey(cols[0].Substring(2, 3))) { isDate = true; dateTime = new DateTime(year, months[cols[0].Substring(2, 3)], day); dateTime = dateTime.AddHours(double.Parse(cols[1].Substring(0, 2))); dateTime = dateTime.AddMinutes(double.Parse(cols[1].Substring(2, 2))); } } else if ( double.TryParse(cols[0], out x) && double.TryParse(cols[1], out y) && double.TryParse(cols[2], out z) ) { coordinates.Add(new Coordinate(x, y, z) { Z = z }); } } } } } } } } }
private bool AddKrigingLayer(List<Polygon> polygonsList) { var field = this._krigingFields[krigingProcess]; string datasetName = field.ID; // field.ProductResult = Math.Round(CalculateProductSum(datasetName), 2); var zList = new List<double>(); FeatureSet fs = new FeatureSet(FeatureType.Polygon); fs.Projection = _config.TargetPolygonLayer.Projection; fs.DataTable.Columns.Add(new DataColumn("ID", typeof(int))); fs.DataTable.Columns.Add(new DataColumn("Z", typeof(double))); fs.DataTable.Columns.Add(new DataColumn("Product", typeof(double))); for (int i = 0; i < polygonsList.Count; i++) { var feature = fs.AddFeature(polygonsList[i]); feature.DataRow["ID"] = i; feature.DataRow["Z"] = polygonsList[i].Coordinate.Z; feature.DataRow["Product"] = field.ProductResult; zList.Add(polygonsList[i].Coordinate.Z); } fs.Name = field.Field; var shapeFile = Path.Combine(field.Folder, "kriging.shp"); fs.SaveAs(shapeFile, true); var input = fs as IFeatureSet; var input2 = _config.TargetPolygonLayer.DataSet as IFeatureSet; input.FillAttributes(); input2.FillAttributes(); FeatureSet output = new FeatureSet(input.FeatureType); output.Projection = input2.Projection; IFeatureSet tempOutput = input.Intersection(input2, FieldJoinType.LocalOnly, null); foreach (DataColumn inputColumn in tempOutput.DataTable.Columns) { output.DataTable.Columns.Add(new DataColumn(inputColumn.ColumnName, inputColumn.DataType)); } foreach (var fe in tempOutput.Features) { output.Features.Add(fe); } output.Name = datasetName; output.Filename = datasetName + ".shp"; field.OutputShapeFile = datasetName + ".shp"; field.OutputZ = string.Join(",", zList); var layer = PluginExtension.MyAppManager.Map.Layers.Add(output); layer.LegendText = field.Field; layer.Symbology.ClearCategories(); var pieChartData = new List<TempPIEChartData>(); _colorsList = _legendRepository.GetFieldLegend(field.Field); if (_colorsList.Where(c => c.Value == null).Count() > 0) { CreateRandomColorCategories(zList, ref pieChartData).ForEach(c => layer.Symbology.AddCategory(c)); } else { _colorsList.Reverse(); CreatePredefinedColorCategories(zList, ref pieChartData).ForEach(c => layer.Symbology.AddCategory(c)); } field.PieChartData = pieChartData; layer.ContextMenuItems.Add(new DotSpatial.Symbology.SymbologyMenuItem("View Input Data", new EventHandler((s, e) => ViewInputDataClick(s, e, field.ID)))); layer.ContextMenuItems.Add( new DotSpatial.Symbology.SymbologyMenuItem("Load Grid File", new EventHandler((s, ev) => LoadGridFileClick(s, ev, field)))); layer.ContextMenuItems.Add(new DotSpatial.Symbology.SymbologyMenuItem("Calculate Product", new EventHandler((s, e) => CalculateProductClick(s, e, field)))); layer.ContextMenuItems.Add( new DotSpatial.Symbology.SymbologyMenuItem("Load Product File", new EventHandler((s, ev) => LoadProductFileClick(s, ev, field)))); new DotSpatial.Symbology.Forms.FeatureCategoryControl(layer).ApplyChanges(); ColorsList = new List<LegendPattern>(); foreach (var item in layer.Symbology.GetCategories()) { var pattern = new Repository.Utils.LegendPattern(); pattern.Color = item.GetColor(); pattern.Value = item.LegendText != null ? item.LegendText : zList.Max().ToString(); ColorsList.Add(pattern); } field.Image = getMapImage(field); return true; }
/// <summary> /// Given a line that contains portion both inside and outside of the polygon, this /// function will split the polygon based only on the segments that completely bisect /// the polygon. It assumes: out->out, and in->in 2pt segments do not intersect the /// polygon, and out->in, in->out 2pt segments have only one point of intersection. /// </summary> /// <param name="insidePts">A boolean array indicating if a point is inside the polygon or not.</param> /// <param name="line">The line that intersects the polygon.</param> /// <param name="polygon">The polygon that will be split by the intersecting line.</param> /// <param name="resultFeatureSet">The shapefile that the polygon sections will be saved to.</param> /// <returns>False if errors were encountered or an assumption violated, true otherwise.</returns> private static bool Fast_ProcessPartInAndOut( bool[] insidePts, IFeature line, IFeature polygon, IFeatureSet resultFeatureSet) { int numLinePts = line.NumPoints; int numLineSegs = numLinePts - 1; int numPolyPts = polygon.NumPoints; int[] intersectsPerSeg; Point[][] intersectPts = new Point[numLineSegs][]; int[][] polyIntLocs = new int[numLineSegs][]; // intersection occurs between polygon point indexed by polyIntLoc[][] and the previous point. // cut line into 2pt segments and put in new shapefile. IFeatureSet lineSegments = new FeatureSet(); IFeature lineSegment; IList<Coordinate> coordi = line.Coordinates; for (int i = 0; i <= numLineSegs - 1; i++) { Coordinate[] secCoordinate = new Coordinate[2]; secCoordinate[0] = coordi[i]; secCoordinate[1] = coordi[i + 1]; lineSegment = new Feature(FeatureType.Line, secCoordinate); lineSegments.Features.Add(lineSegment); intersectPts[i] = new Point[numPolyPts]; polyIntLocs[i] = new int[numPolyPts]; } // find number of intersections, intersection pts, and locations for each 2pt segment int numIntersects = FindIntersections( lineSegments, polygon, out intersectsPerSeg, out intersectPts, out polyIntLocs); if (numIntersects == 0) { return false; } IFeature insideLine = new Feature(); List<Coordinate> insideLineList = new List<Coordinate>(); List<Coordinate> intersectSegList; Point startIntersect = new Point(); bool startIntExists = false; bool validInsideLine = false; int insideStart = 0; int startIntPolyLoc = 0; // loop through each 2pt segment for (int i = 0; i <= numLinePts - 2; i++) { lineSegment = lineSegments.Features[i]; int numSegIntersects = intersectsPerSeg[i]; // ****************** case: inside->inside **************************************// int ptIndex; if (insidePts[i] && insidePts[i + 1]) { if (numSegIntersects == 0 && i != numLinePts - 2 && i != 0) { // add points to an inside line segment if (startIntExists) { ptIndex = 0; insideLineList.Insert(ptIndex, startIntersect.Coordinate); startIntExists = false; validInsideLine = true; insideStart = startIntPolyLoc; } if (validInsideLine) { ptIndex = insideLine.NumPoints; insideLineList.Insert(ptIndex, lineSegment.Coordinates[0]); } } else { // we do not handle multiple intersections in the fast version return false; } // end of inside->inside } else if (insidePts[i] && insidePts[i + 1] == false) { // ********************** case: inside->outside **************************************** if (numSegIntersects == 0) { return false; } if (numSegIntersects == 1) { if (startIntExists) { intersectSegList = new List<Coordinate>(); ptIndex = 0; intersectSegList.Insert(ptIndex, startIntersect.Coordinate); ptIndex = 1; intersectSegList.Insert(ptIndex, lineSegment.Coordinates[0]); ptIndex = 2; intersectSegList.Insert(ptIndex, intersectPts[i][0].Coordinate); IFeature intersectSeg = new Feature(FeatureType.Line, intersectSegList); int firstPolyLoc = startIntPolyLoc; int lastPolyLoc = polyIntLocs[i][0] - 1; if (SectionPolygonWithLine( ref intersectSeg, ref polygon, firstPolyLoc, lastPolyLoc, ref resultFeatureSet) == false) { return false; } startIntExists = false; // we just used it up! } else if (insideLine.NumPoints != 0 && validInsideLine) { ptIndex = insideLineList.Count; insideLineList.Insert(ptIndex, lineSegment.Coordinates[0]); ptIndex++; insideLineList.Insert(ptIndex, intersectPts[i][0].Coordinate); insideLine = new Feature(FeatureType.Line, insideLineList); int firstPolyLoc = insideStart; int lastPolyLoc = polyIntLocs[i][0] - 1; if (SectionPolygonWithLine( ref insideLine, ref polygon, firstPolyLoc, lastPolyLoc, ref resultFeatureSet) == false) { return false; } validInsideLine = false; insideLine.Coordinates.Clear(); } } else { // we do not handle multiple intersections in the fast version return false; } // end of inside->outside } else if (insidePts[i] == false && insidePts[i + 1]) { // ********************** case: outside->inside *************************************** validInsideLine = false; if (numSegIntersects == 0) { return false; } if (numSegIntersects == 1) { startIntExists = true; startIntersect = intersectPts[i][0]; startIntPolyLoc = polyIntLocs[i][0] - 1; } else { // we do not handle multiple intersections in the fast version return false; } } else if (insidePts[i] == false && insidePts[i + 1] == false) { // ************************ case: outside->outside *********************************** startIntExists = false; validInsideLine = false; if (numSegIntersects == 0) { // do nothing } else { // we do not handle multiple intersections in the fast version return false; } } // end of outside->outside } // end of looping through 2pt segments return true; }
/// <summary> /// Executes the ClipPolygonWithLine Operation tool programaticaly. /// Ping deleted static for external testing 01/2010 /// </summary> /// <param name="input1">The input Polygon FeatureSet.</param> /// <param name="input2">The input Polyline FeatureSet.</param> /// <param name="output">The output Polygon FeatureSet.</param> /// <param name="cancelProgressHandler">The progress handler.</param> /// <returns></returns> public bool Execute( IFeatureSet input1, IFeatureSet input2, IFeatureSet output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (input1 == null || input2 == null || output == null) { return false; } if (cancelProgressHandler.Cancel) { return false; } IFeature polygon = input1.Features[0]; IFeature line = input2.Features[0]; IFeatureSet resultFs = new FeatureSet(FeatureType.Polygon); int previous = 0; if (DoClipPolygonWithLine(ref polygon, ref line, ref output) == false) { throw new SystemException(TextStrings.Exceptioninclipin); } int intFeature = output.Features.Count; for (int i = 0; i < intFeature; i++) { Polygon poly = new Polygon(output.Features[i].Coordinates); resultFs.AddFeature(poly); int current = Convert.ToInt32(Math.Round(i * 100D / intFeature)); // only update when increment in percentage if (current > previous) { cancelProgressHandler.Progress(string.Empty, current, current + TextStrings.progresscompleted); } previous = current; } cancelProgressHandler.Progress(string.Empty, 100, 100 + TextStrings.progresscompleted); resultFs.SaveAs(output.Filename, true); return true; }
/// <summary> /// For faster clipping of polygons with lines. Limits the finding of intersections to /// outside->inside or inside->outside 2pt segments. Assumes only one intersections exists /// per segment, that a segment of two inside points or two outside points will not intersect /// the polygon. /// </summary> /// <param name="polygon">The polygon that will be sectioned by the line.</param> /// <param name="line">The line that will clip the polygon into multiple parts.</param> /// <param name="resultFeatureSet">The in-memory shapefile where the polygon sections will be saved.</param> /// <returns>False if errors are encountered, true otherwise.</returns> public static bool Fast_ClipPolygonWithLine( ref IFeature polygon, ref IFeature line, ref IFeatureSet resultFeatureSet) { IFeatureSet resultFile = new FeatureSet(FeatureType.Polygon); if (polygon != null && line != null) { // make sure we are dealing with a valid shapefile type if (polygon.FeatureType == FeatureType.Polygon) { // create the result shapefile if it does not already exist if (!polygon.Overlaps(line)) { resultFeatureSet = resultFile; return false; } // find if all of the line is inside, outside, or part in and out of polygon // line might intersect polygon mutliple times int numPoints = line.NumPoints; bool[] ptsInside = new bool[numPoints]; int numInside = 0; int numOutside = 0; int numParts = polygon.NumGeometries; if (numParts == 0) { numParts = 1; } Coordinate[][] polyVertArray = new Coordinate[numParts][]; ConvertPolyToVertexArray(ref polygon, ref polyVertArray); // check each point in the line to see if the entire line is either // inside of the polygon or outside of it (we know it's inside polygon bounding box). for (int i = 0; i <= numPoints - 1; i++) { Point currPt = new Point(line.Coordinates[i]); if (polygon.Covers(currPt)) { ptsInside[i] = true; numInside += 1; } else { ptsInside[i] = false; numOutside += 1; } } // case: all points are inside polygon - check for possible intersections if (numInside == numPoints) { // assume no intersections exist in fast version } else if (numOutside == numPoints) { // case: all points are outside of the polygon - check for possible intersections // assume no intersections exist in fast version } else { // case: part of line is inside and part is outside - find inside segments. if (Fast_ProcessPartInAndOut(ptsInside, line, polygon, resultFile) == false) { resultFeatureSet = resultFile; return false; } } // resultSF result file, do not save to disk. resultFeatureSet = resultFile; } else { resultFeatureSet = resultFile; return false; } } else { // polygon or line is invalid resultFeatureSet = resultFile; return false; } return true; }
/// <summary> /// This will clip MultiPart Polygon with line. /// </summary> /// <param name="polygon">Input Polygon.</param> /// <param name="line">Input Line.</param> /// <param name="resultFile">Output Featureset.</param> /// <param name="speedOptimized">The speed optimizer.</param> /// <returns></returns> public static bool ClipMultiPartPolyWithLine( ref IFeature polygon, ref IFeature line, ref IFeatureSet resultFile, bool speedOptimized) { int numParts = polygon.NumGeometries; if (numParts == 0) { numParts = 1; } if (numParts > 1) { // multiple parts FixMultiPartPoly(ref polygon); IFeature[] polyParts = new IFeature[numParts]; SeparateParts(ref polygon, ref polyParts); IFeatureSet holeSf = new FeatureSet(FeatureType.Polygon); IFeatureSet tempResult = new FeatureSet(FeatureType.Polygon); IFeatureSet modPolySf = new FeatureSet(FeatureType.Polygon); IFeatureSet resultSf = new FeatureSet(FeatureType.Polygon); for (int i = 0; i <= numParts - 1; i++) { IFeature currPart = polyParts[i]; if (CgAlgorithms.IsCounterClockwise(currPart.Coordinates) == false) { if (speedOptimized) { Fast_ClipPolygonWithLine(ref currPart, ref line, ref tempResult); } else { Accurate_ClipPolygonWithLine(ref currPart, ref line, ref tempResult); } int numResults = tempResult.Features.Count; if (numResults > 0) { for (int j = 0; j <= numResults - 1; j++) { modPolySf.Features.Add(tempResult.Features[j]); } } } else { holeSf.Features.Add(currPart); } } if (holeSf.Features.Count > 0) { ErasePolygonShapefileWithPolygonShapefile(modPolySf, holeSf, resultSf); } if (resultSf.Features.Count > 0) { resultFile = resultSf; return true; } resultFile = resultSf; return false; } if (speedOptimized) { return Fast_ClipPolygonWithLine(ref polygon, ref line, ref resultFile); } return Accurate_ClipPolygonWithLine(ref polygon, ref line, ref resultFile); }
/// <summary> /// /// </summary> /// <param name="resultFeatureSet"></param> private static void RemoveDuplicateFeaturesFromFeatureSet(ref IFeatureSet resultFeatureSet) { IFeatureSet ifsNewResultFS = new FeatureSet(); int nIndexOfCurrent = 0; List<int> listIndexesToNotAdd = new List<int>(); List<int> listIndexesAddedToNewFS = new List<int>(); if (resultFeatureSet.Features.Count < 2) return; // no need to check while (nIndexOfCurrent < resultFeatureSet.Features.Count) { IFeature currentFeature = resultFeatureSet.Features[nIndexOfCurrent]; if (listIndexesToNotAdd.Contains(nIndexOfCurrent) == false) { for (int j = 0; j < resultFeatureSet.Features.Count; j++) { if (nIndexOfCurrent != j && listIndexesAddedToNewFS.Contains(j) == false) { IFeature feature = resultFeatureSet.Features[j]; IFeature diffFeature = currentFeature.SymmetricDifference(feature); if (diffFeature == null && listIndexesToNotAdd.Contains(j) == false) { // Exact duplicate listIndexesToNotAdd.Add(j); } else if (diffFeature.Area() <= FindIntersectionTolerance && listIndexesToNotAdd.Contains(j) == false) { // Only a "sliver" remained; treat as a duplicate listIndexesToNotAdd.Add(j); } } } } if (listIndexesToNotAdd.Contains(nIndexOfCurrent) == false) { ifsNewResultFS.Features.Add(currentFeature); listIndexesAddedToNewFS.Add(nIndexOfCurrent); } nIndexOfCurrent++; } // Done resultFeatureSet = ifsNewResultFS; }
private bool TryCreateFeatureSet(string pathToFile, DotSpatial.Topology.FeatureType type, out DotSpatial.Data.FeatureSet set) { char[] splitChars = new char[] { ' ', '\t' }; set = new FeatureSet(type); if (!File.Exists(pathToFile)) { return(false); } StreamReader sr = null; try { sr = new StreamReader(pathToFile); List <Coordinate> coords = new List <Coordinate>(); string line = ""; while ((line = sr.ReadLine()) != null) { if (line.StartsWith("RMTEXT")) { continue; } string[] parts = line.Split(splitChars, StringSplitOptions.RemoveEmptyEntries); if (parts.Length < 2) { continue; } double x; if (!double.TryParse(parts[0], out x)) { continue; } double y; if (!double.TryParse(parts[1], out y)) { continue; } coords.Add(new Coordinate(x, y)); } set.AddFeature(new LineString(coords)); return(true); } catch { return(false); } finally { if (sr != null) { sr.Close(); } } }
private XPathNodeIterator CreateFields(XPathNavigator nav, DotSpatial.Topology.FeatureType type) { string exp = @"/wfs:FeatureCollection/child::*[name() = 'gml:featureMember' or name() = 'gml:featureMembers']/child::*"; XPathNodeIterator iterator = nav.Select(exp, _nsmgr); fea = new FeatureSet(type); if (iterator.Count > 0) { foreach (string fieldName in fields.Keys) { if (fieldName != Geometry) { fea.DataTable.Columns.Add(new DataColumn(fieldName, GetType(fieldName))); } } } return iterator; }
/// <summary> /// Allows for new behavior during deactivation. /// </summary> protected override void OnDeactivate() { if (_standBy) { return; } // Don't completely deactivate, but rather go into standby mode // where we draw only the content that we have actually locked in. _standBy = true; if (_coordinateDialog != null) { _coordinateDialog.Hide(); } if (_coordinates != null && _coordinates.Count > 1) { LineString ls = new LineString(_coordinates); FeatureSet fs = new FeatureSet(FeatureType.Line); fs.Features.Add(new Feature(ls)); MapLineLayer gll = new MapLineLayer(fs) { Symbolizer = { ScaleMode = ScaleMode.Symbolic, Smoothing = true }, MapFrame = Map.MapFrame }; _tempLayer = gll; Map.MapFrame.DrawingLayers.Add(gll); Map.MapFrame.Invalidate(); Map.Invalidate(); } base.Deactivate(); }
/// <summary> /// /// </summary> /// <param name="insidePts"></param> /// <param name="line"></param> /// <param name="polygon"></param> /// <param name="resultFeatureSet"></param> /// <param name="numIntersects"></param> /// <param name="numLineSegs"></param> /// <param name="intersectPts"></param> /// <param name="polyIntLocs"></param> /// <param name="numPolyPts"></param> /// <param name="colLineParts"></param> /// <param name="colPolyIntLocPoints"></param> /// <returns></returns> private static bool ProcessPartInAndOutWithWholeLine(ref bool[] insidePts, ref IFeature line, ref IFeature polygon, ref IFeatureSet resultFeatureSet, int numIntersects, int numLineSegs, Point[][] intersectPts, int[][] polyIntLocs, int numPolyPts, List<IFeature> colLineParts, List<Coordinate> colPolyIntLocPoints) { Point[] intPts = new Point[numIntersects]; Point startPt = new Point(line.Coordinates[0]); Point firstIntPt = null; Point lastIntPt = null; List<int> listIntLocs = new List<int>(); List<int> listLinePartIndexValuesForOrigLine = new List<int>(); List<List<int>> colListForEachLinePart = new List<List<int>>(); List<int> listLinePartStartEndIndexValues = new List<int>(); int nNewLineStartIndex = 0; int nNewLineEndIndex = 0; int nLastIndexUsed = -1; List<Coordinate> listNewLine = new List<Coordinate>(); int nLineParts = 0; // First time only: collect the information needed for all intersections if (colLineParts.Count == 0) { for (int i = 0; i <= numLineSegs - 1; i++) { FindAndSortValidIntersects(numIntersects, ref intersectPts[i], ref intPts, ref startPt, ref polyIntLocs[i]); // Find the intersect points & start/end line points for (int j = 0; j < numPolyPts; j++) { if (polyIntLocs[i][j] != 0) { // Save this index in the polygon points listIntLocs.Add(polyIntLocs[i][j] - 1); } if (intersectPts[i][j].X.Equals(double.NaN) == false) { if (firstIntPt == null) { firstIntPt = intersectPts[i][j]; // first intersection for this cut nNewLineStartIndex = i; listNewLine.Add(new Coordinate(intersectPts[i][j].X, intersectPts[i][j].Y, 0.0)); listLinePartStartEndIndexValues.Add(listNewLine.Count - 1); } else { lastIntPt = intersectPts[i][j]; // last intersection for this cut nNewLineEndIndex = i; } } } if (firstIntPt != null && lastIntPt == null) { // Collect the point from the line that are between the two poly intersetion points listNewLine.Add(line.Coordinates[i]); if (i > nLastIndexUsed) { listLinePartIndexValuesForOrigLine.Add(i); nLastIndexUsed = i; // we want one of each index } } else if (firstIntPt != null && lastIntPt != null) { listNewLine.Add(new Coordinate(lastIntPt.X, lastIntPt.Y, 0.0)); listLinePartStartEndIndexValues.Add(listNewLine.Count - 1); colListForEachLinePart.Add(new List<int>(listLinePartIndexValuesForOrigLine)); listLinePartIndexValuesForOrigLine.Clear(); firstIntPt = null; lastIntPt = null; } } for (int i = 0; i < (listIntLocs.Count / 2); i++) { // Save these points so we can find the "new" index values later colPolyIntLocPoints.Add(polygon.Coordinates[listIntLocs[2 * i]]); colPolyIntLocPoints.Add(polygon.Coordinates[listIntLocs[2 * i + 1]]); // Build the line parts that we need for each cut int nStart = listLinePartStartEndIndexValues[2 * nLineParts]; int nEnd = listLinePartStartEndIndexValues[2 * nLineParts + 1]; List<int> currentListOfIndexValues = colListForEachLinePart[nLineParts]; List<Coordinate> listLinePart = new List<Coordinate>(); listLinePart.Add(listNewLine[nStart]); // Add first intersection foreach (int j in currentListOfIndexValues) { listLinePart.Add(line.Coordinates[j + 1]); // get values from original line } listLinePart.Add(listNewLine[nEnd]); // Add second intersection // Now, we have the part of the line we need make this cut IFeature newLinePart = new Feature(FeatureType.Line, listLinePart); colLineParts.Add(newLinePart); nLineParts++; // get ready for next part } } bool bSwapIntLocs = false; nLineParts = 0; // For each intersecting line part, see if a cut needs to be made. for (int i = 0; i < colLineParts.Count; i++) { IFeature newLinePart = colLineParts[i]; IFeatureSet tempFeatureSet = new FeatureSet(FeatureType.Polygon); foreach (IFeature feature in resultFeatureSet.Features) { IFeature currentFeature = feature; // Does this part of the line really intersect? if (newLinePart.Intersects(currentFeature)) { int firstIntLoc = -1; int lastIntLoc = -1; Coordinate firstCoord = colPolyIntLocPoints[2 * nLineParts]; Coordinate lastCoord = colPolyIntLocPoints[2 * nLineParts + 1]; // Find the index of both points for (int j = 0; j < currentFeature.Coordinates.Count; j++) { Coordinate coord = currentFeature.Coordinates[j]; if (coord.Equals(firstCoord) && firstIntLoc == -1) firstIntLoc = j; if (coord.Equals(lastCoord) && lastIntLoc == -1) lastIntLoc = j; } if (bSwapIntLocs) { int nTemp = firstIntLoc; firstIntLoc = lastIntLoc; lastIntLoc = nTemp; } IFeatureSet tempSplitFeatureSet = new FeatureSet(FeatureType.Polygon); if (SectionPolygonWithLine(ref newLinePart, ref currentFeature, firstIntLoc, lastIntLoc, ref tempSplitFeatureSet) == false) { return false; } if (tempSplitFeatureSet.Features.Count == 0) { tempFeatureSet.Features.Add(currentFeature); // no cut was made } else { foreach (IFeature feature2 in tempSplitFeatureSet.Features) { tempFeatureSet.Features.Add(feature2); } } } else { tempFeatureSet.Features.Add(currentFeature); // no cut needed for this polygon } } // Next time we will need to do the opposite nLineParts++; // get ready for next part // Replace original features with new ones resultFeatureSet = new FeatureSet(tempFeatureSet.Features); } return true; }