private void ShrinkOrGrowPoly(ref MapWinGIS.Shape shp, double distance) { MapWinGIS.Point centroid = MapWinGeoProc.Statistics.Centroid(ref shp); // Avoid OLE calls; cache centroid point in local variable double cx = centroid.x; double cy = centroid.y; for (int i = 0; i < shp.numPoints; i++) { double ox = shp.get_Point(i).x; double oy = shp.get_Point(i).y; // Find the adjusted "real" distance (rdistance) double rdistance = Math.Sqrt(Math.Pow(cy - oy, 2) + Math.Pow(cx - ox, 2)) + distance; // Find the full distance of point to centroid (fdistance) double fdistance = Math.Sqrt(Math.Pow(cy - oy, 2) + Math.Pow(cx - ox, 2)); if (rdistance < 0.00001) { MapWinUtility.Logger.Message("Shrinking the shape by this amount will result in losing some shape geometry; aborting.", "Aborting - Loss of Geometry", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, DialogResult.OK); return; } // Find the new point (project the old point along the line from point to midpoint) shp.get_Point(i).x = cx + (rdistance / fdistance) * (ox - cx); shp.get_Point(i).y = cy + (rdistance / fdistance) * (oy - cy); } }
private static double LatitudeCorrectedArea(ref MapWinGIS.Shape shp) { // area per square degree changes as a function of latitude // these are function parameters for a 'best-fit' equation derived from a series of known-size squares // that were established at different latitudes from 0 to 90 try { double x0 = 2.5973 * Math.Pow(10, -6); double x1 = -1.6551 * Math.Pow(10, -7); double x2 = 5.8911 * Math.Pow(10, -9); double x3 = -9.0237 * Math.Pow(10, -11); double x4 = 5.5763 * Math.Pow(10, -13); //use the average latitude of the shape to determine the correction factor //1/24/2009 JK - latitude must be multiplied by (-1) for southern hemisphere. double latitude = (shp.Extents.yMax + shp.Extents.yMin) / 2; if (latitude < 0) { latitude = latitude * -1; } double CorrectedFactor = (x0 + latitude * x1 + Math.Pow(latitude, 2) * x2 + Math.Pow(latitude, 3) * x3 + Math.Pow(latitude, 4) * x4); return(CorrectedFactor); } catch (Exception ex) { throw new Exception("Error in LatitudeCorrectedArea: \n" + ex.ToString()); } }
/// <summary> /// Draws selected bounds on map /// </summary> /// <param name="ext">Bounding box to search CS</param> public void DrawSelectedBounds(MapWinGIS.Extents ext) { this.RemoveLayer(m_handleBounds); MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile(); if (sf.CreateNew("", MapWinGIS.ShpfileType.SHP_POLYGON)) { MapWinGIS.Shape shp = new MapWinGIS.Shape(); shp.Create(MapWinGIS.ShpfileType.SHP_POLYGON); this.InsertPart(shp, ext.xMin, ext.xMax, ext.yMin, ext.yMax); int index = 0; sf.EditInsertShape(shp, ref index); m_handleBounds = this.AddLayer(sf, true); MapWinGIS.ShapeDrawingOptions options = sf.DefaultDrawingOptions; MapWinGIS.Utils ut = new MapWinGIS.Utils(); options.FillColor = ut.ColorByName(MapWinGIS.tkMapColor.Orange); options.LineColor = ut.ColorByName(MapWinGIS.tkMapColor.Orange); options.LineWidth = 3; options.LineStipple = MapWinGIS.tkDashStyle.dsDash; options.FillTransparency = 100; } else { System.Diagnostics.Debug.Print("Failed to create in-memory shapefile"); } }
/// <summary> /// Converts a list of polylines into a single multi-part shape /// </summary> /// <param name="Polylines"></param> /// <returns></returns> public static MapWinGIS.Shape LineStrings_To_mwShape(List <LineString> Polylines) { MapWinGIS.Shape mwShape = new MapWinGIS.Shape(); bool res; res = mwShape.Create(MapWinGIS.ShpfileType.SHP_POLYLINEZ); if (res != true) { throw new ApplicationException(mwShape.get_ErrorMsg(mwShape.LastErrorCode)); } int idx = 0; for (int iPart = 0; iPart < Polylines.Count; iPart++) { LineString Part = Polylines[iPart]; // we only cal set_part if we have multiple polylines if (Polylines.Count > 0) { mwShape.set_Part(iPart, idx); } for (int iPoint = 0; iPoint < Part.Points.Count; iPoint++) { mwShape.InsertPoint(Part.Points[iPoint].To_mwPoint(), ref idx); idx++; } } return(mwShape); } // End LineStrings_To_mwShape
// Returns only the point index values of the shapes in the interesection of the shape extents private static void PointsOfInterest(MapWinGIS.Shape Shape1, MapWinGIS.Shape Shape2, ref List <int> Points1, ref List <int> Points2) { Envelope Rect1, Rect2, rectIntersect; Rect1 = new Envelope(Shape1.Extents); Rect2 = new Envelope(Shape2.Extents); rectIntersect = (Envelope)Rect1.Intersection(Rect2); MapWinGIS.Point pt = new MapWinGIS.Point(); // reduce our points to points of interrest int numPoints1 = Shape1.numPoints; for (int I = 0; I < numPoints1; I++) { pt = Shape1.get_Point(I); if (rectIntersect.Intersects(pt)) { Points1.Add(I); } } int numPoints2 = Shape2.numPoints; for (int I = 0; I < numPoints2; I++) { pt = Shape2.get_Point(I); if (rectIntersect.Intersects(pt)) { Points2.Add(I); } } }
/// <summary> /// Not Implemented /// This function will calculate the length of every line shape in the shapefile and save the results to the corresponding .dbf table. /// </summary> /// <param name="sf">The shapefile of lines whose lengths are to be computed.</param> /// <param name="fieldIndex">The field index of the field to update with values.</param> /// <param name="Units">The units of the dataset (e.g., Meters, Lat/Long).</param> /// <returns>False if an error was encountered, true otherwise.</returns> public static bool ComputeLengths(MapWinGIS.Shapefile sf, int fieldIndex, string Units) { try { //Loop trough all shapes for (int i = 0; i <= sf.NumShapes - 1; i++) { double length = 0f; MapWinGIS.Shape line = new MapWinGIS.Shape(); //Measure length of each line part line = sf.get_Shape(i); //-2 else out of bounds!! for (int j = 0; j <= line.numPoints - 2; j++) { length += DistancePointToPoint(line.get_Point(j).x, line.get_Point(j).y, line.get_Point(j + 1).x, line.get_Point(j + 1).y, Units); } //Add length as attribute: if (!sf.EditCellValue(fieldIndex, i, length)) { Error.SetErrorMsg(sf.get_ErrorMsg(sf.LastErrorCode)); } } return(false); } catch (Exception lEx) { Error.SetErrorMsg(lEx.ToString()); return(false); } }
/// <summary> /// reads a MapWinGIS.Shape to find the ShapeCategory /// </summary> /// <param name="Shape">A MapWinGIS.Shape object to learn the category of</param> /// <returns>A ShapeCategories enumeration</returns> public static ShapeCategories GetCategory(MapWinGIS.Shape Shape) { if (Shape.ShapeType == MapWinGIS.ShpfileType.SHP_POLYGON || Shape.ShapeType == MapWinGIS.ShpfileType.SHP_POLYGONM || Shape.ShapeType == MapWinGIS.ShpfileType.SHP_POLYGONZ) { return(ShapeCategories.Polygon); } if (Shape.ShapeType == MapWinGIS.ShpfileType.SHP_POLYLINE || Shape.ShapeType == MapWinGIS.ShpfileType.SHP_POLYLINEM || Shape.ShapeType == MapWinGIS.ShpfileType.SHP_POLYLINEZ) { return(ShapeCategories.Line); } if (Shape.ShapeType == MapWinGIS.ShpfileType.SHP_MULTIPATCH || Shape.ShapeType == MapWinGIS.ShpfileType.SHP_NULLSHAPE) { return(ShapeCategories.Invalid); } if (Shape.ShapeType == MapWinGIS.ShpfileType.SHP_MULTIPOINT || Shape.ShapeType == MapWinGIS.ShpfileType.SHP_MULTIPOINTM || Shape.ShapeType == MapWinGIS.ShpfileType.SHP_MULTIPOINTZ) { return(ShapeCategories.MultiPoint); } return(ShapeCategories.Point); }
}// End FastPolygonsIntersect #region --------------------------- POINTS WITHIN EXTENTS ---------------------------------- /// <summary> /// Finds a list of point indecies from a MapWinGIS.Shape that are within the extents specified /// </summary> /// <param name="Shape">Any shapefile with points.</param> /// <param name="Envelope">A MapWinGIS.Extents object representing the area of interrest</param> /// <returns>Returns a list of integer point indecies in Shape that are within Envelope</returns> public static List <int> PointsWithinEnvelope(MapWinGIS.Shape Shape, MapWinGIS.Extents Envelope) { Envelope Rect; Rect = new Envelope(Envelope); return(PointsWithinRect(Shape, Rect)); }
/// <summary> /// This one way function will convert most geometries into a valid MapWinGIS Shape object. /// </summary> /// <param name="geom">Point, MultiPoint, LineString, MultiLineString, LinearRing, Polygon, MultiPolygon</param> /// <returns>A MapWinGIS.Shape that will hold the specified geometries.</returns> /// <remarks>Shapes are not TypeZ or TypeM! Adding them to the wrong shapefile can cause problems.</remarks> public static MapWinGIS.Shape GeometryToShape(IGeometry geom) { // We can just call AppendGeometryToShape from here after using a null parameter. MapWinGIS.Shape mwShape = null; AppendGeometryToShape(geom, ref mwShape); return(mwShape); }
// Add the shapes one by one private bool AddShapes(MapWinGIS.Shapefile inSF, out string errorMessage) { errorMessage = "No Error."; int outShp = _outSF.NumShapes; // Add all the shapes and attributes from the first shapefile for (int shp = 0; shp < inSF.NumShapes; shp++) { MapWinGIS.Shape shape = inSF.get_Shape(shp); _outSF.EditInsertShape(shape, ref outShp); for (int fld = 0; fld < inSF.NumFields; fld++) { string name = inSF.get_Field(fld).Name; int index = IndexOf(name); if (index == -1) { errorMessage = "Could not find a field in the output shapefile: [" + name + "]"; return(false); } if (_outSF.EditCellValue(index, outShp, inSF.get_CellValue(fld, shp)) == false) { errorMessage = _outSF.get_ErrorMsg(_outSF.LastErrorCode); return(false); } } outShp++; } return(true); }
/// <summary> /// Calculate area of shapes in lat/long coordinates. /// The shape coordinates must be in decimal degrees. It is assumed that the WGS-84 /// ellipsoid is used - this can result in small errors if the coordinate system of the /// shape is based on a different ellipsoid. /// Added by Jiri Kadlec based on the UpdateMeasurements plugin code by Paul Meems. /// </summary> /// <param name="shp">The polygon shape (must have coordinates in decimal degrees)</param> /// <returns>Area of shape in square kilometres</returns> public static double LLArea(ref MapWinGIS.Shape shp) { //for smaller shapes, an approximation is used (area correction factor for latitude). //for very large shapes (extent in latitude > 1 decimal degree, use the spherical polygon //area calculation algorithm. double maxLatitudeExtent = 1.0; //one decimal degree (~110 km) double area; //area - in square kilometres if (Math.Abs(shp.Extents.yMax - shp.Extents.yMin) < maxLatitudeExtent) { // use latitude corrected area approximation area = MapWinGeoProc.Utils.Area(ref shp); if (area < 0) { area = -1 * area; } area = (area / LatitudeCorrectedArea(ref shp)) * 0.01; } else { //for big shapes, use the spheric polygon area calculation (added by JK) area = SphericPolygonArea(ref shp); } return(area); }
/// <summary> /// Event that occurs when the AddShapeForm is closing. I generate the return value here. /// </summary> /// <param name="sender">The object causing the close event.</param> /// <param name="e">Event data.</param> private void AddShapeForm_Closing(object sender, System.ComponentModel.CancelEventArgs e) { m_globals.Events.RemoveHandler(m_MapMouseMoveDelegate); m_globals.Events.RemoveHandler(m_MapMouseUpDelegate); m_globals.MapWin.View.CursorMode = m_oldCursorMode; m_globals.MapWin.View.MapCursor = m_oldCursor; m_globals.MapWin.View.UserCursorHandle = m_oldCursorHandle; if (m_sf.EditingShapes == true) { m_globals.CreateUndoPoint(); m_sf.StopEditingShapes(true, true, null); } if (m_Shape.NumPoints > 0) { m_retval = m_Shape.ToMWShape(m_sf.ShapefileType); } else { m_retval = null; } //Added by Lailin Chen to clear the SnapData list after use 12/12/2005 m_snapper.ClearSnapData(); }
/// <summary> /// Merges two polygons together. If they touch, they will be UNIONed together, /// If they do not touch, they will be combined into one multi-part shape. /// </summary> /// <param name="poly1">The first polygon to be considered.</param> /// <param name="poly2">The second polygon to be considered.</param> /// <param name="sfType">The type of shapefile the polygons are a part of.</param> /// <param name="resultShp">The polygon shape that results after merging.</param> /// <returns>True if merging was successful, false otherwise.</returns> private static bool MergePolygons(ref MapWinGIS.Shape poly1, ref MapWinGIS.Shape poly2, MapWinGIS.ShpfileType sfType, out MapWinGIS.Shape resultShp) { MapWinGIS.Shape mShp = new MapWinGIS.ShapeClass(); mShp.Create(sfType); if (Globals.CheckBounds(ref poly1, ref poly2)) { //bounds overlap, try union Debug.WriteLine("Union operation is being performed."); mShp = SpatialOperations.Union(poly1, poly2); if (mShp.numPoints > 0) { resultShp = mShp; return(true); } else { //even though bounds overlap, the polygons may not touch //combine them into a multi-part polygon. bool status = CombinePolygons(ref poly1, ref poly2, out mShp); resultShp = mShp; return(status); } } else { //Polygons don't overlap, try combining them into a multi-part polygon gErrorMsg = "Combining polygons into one multi-part shape."; Debug.WriteLine(gErrorMsg); bool status = CombinePolygons(ref poly1, ref poly2, out mShp); resultShp = mShp; MapWinUtility.Logger.Dbg(gErrorMsg); return(status); } }
/// <summary> /// Creates a new instance of the polyline class /// </summary> /// <param name="mwShape">A MapWinGIS.Shape to derive the polyline from</param> /// <remarks>Assumes shape is one part. To Split Multipart shapes, use Split.</remarks> public LineString(MapWinGIS.Shape mwShape) { if (Adapter.GetCategory(mwShape) != ShapeCategories.Line) { throw new ArgumentException("The Split method only takes Polyline shape types."); } m_Envelope = new Envelope(mwShape.Extents); extentsValid = true; // When adding all the points at once, we have no problem. m_Length = 0; lengthValid = false; // Calculate this only if it is needed m_Center = new Point((m_Envelope.xMin + m_Envelope.xMax) / 2, (m_Envelope.yMin + m_Envelope.yMax) / 2, (m_Envelope.zMin + m_Envelope.zMax) / 2); centerValid = true; // since extents were ok already, we can quickly find the center m_MaxRadius = 0; maxradiusValid = false; // Calculate this only if it is needed m_Points = new List <Point>(); for (int I = 0; I < mwShape.NumParts; I++) { Add_Point(mwShape.get_Point(I)); } }
/// <summary> /// Creates a new instance of the Polygon class /// The shape is closed, but the first and last point will be the same. /// This way, algorithms don't have to loop back to the 0 point in order to evaluate /// the final segment. /// </summary> /// <param name="mwShape">A MapWinGIS.Shape to derive the Polygon from</param> /// <remarks>Assumes shape is one part. To Split Multipart shapes, use Split.</remarks> public Polygon(MapWinGIS.Shape mwShape) { if (Adapter.GetCategory(mwShape) != ShapeCategories.Polygon) { throw new ArgumentException("The Split method only takes Polygon shape types."); } m_Area = 0; areaValid = false; // Calculate this when needed and then cache it. m_Envelope = new Envelope(mwShape.Extents); extentsValid = true; // When adding all the points at once, we have no problem. m_Center = new Point((m_Envelope.xMin + m_Envelope.xMax) / 2, (m_Envelope.yMin + m_Envelope.yMax) / 2, (m_Envelope.zMin + m_Envelope.zMax) / 2); centerValid = true; // since extents were ok already, we can quickly find the center m_Perimeter = 0.0; perimeterValid = false; // Calculate this only if it is needed m_MaxRadius = 0.0; maxradiusValid = false; // Calculate this only if it is needed m_Points = new List <Point>(); // skip the last duplicate point for (int I = 0; I < mwShape.NumParts - 1; I++) { Add_Point(mwShape.get_Point(I)); } }
/// <summary> /// If a Shape has multiple parts, this will create a separate polyline for each part. /// </summary> /// <param name="mwShape">A MapWinGIS.Shape that should be a LineString shape type</param> /// <returns>A List of Polylines derived from the various shapes</returns> public static List <LineString> mwShape_To_LineStrings(MapWinGIS.Shape mwShape) { if (Adapter.GetCategory(mwShape) != ShapeCategories.Line) { throw new ArgumentException("The Split method only takes Polyline shape types."); } List <LineString> newLines = new List <LineString>(); if (mwShape.NumParts <= 1) { LineString Part = new LineString(); for (int I = 0; I < mwShape.numPoints; I++) { Part.Add_Point(mwShape.get_Point(I)); } newLines.Add(Part); return(newLines); } int PartIndex = 0; for (int P = 0; P < mwShape.NumParts; P++) { LineString Part = new LineString(); int Pnext = mwShape.get_Part(P); for (int I = PartIndex; I < Pnext; I++) { Part.Add_Point(mwShape.get_Point(I)); } newLines.Add(Part); } return(newLines); }
private void MarkAllVertices() { try { MapWinGIS.Shape shp = null; MapWinGIS.Shapefile sf = m_globals.CurrentLayer; MapWindow.Interfaces.View v = m_globals.MapWin.View; //clear the drawings v.Draw.ClearDrawing(m_HDraw); m_HDraw = v.Draw.NewDrawing(MapWinGIS.tkDrawReferenceList.dlSpatiallyReferencedList); //display all the vertices for each shape for (int i = 0; i < v.SelectedShapes.NumSelected; i++) { shp = sf.get_Shape(v.SelectedShapes[i].ShapeIndex); for (int j = 0; j < shp.numPoints; j++) { MapWinGIS.Point shpPoint = shp.get_Point(j); m_globals.MapWin.View.Draw.DrawPoint(shpPoint.x, shpPoint.y, m_globals.VertexSize, System.Drawing.Color.Red); } } } catch (System.Exception ex) { m_globals.MapWin.ShowErrorDialog(ex); } }
/// <summary> /// Returns a MapWinGIS Multi-part PolyLine representing this multiLineString /// </summary> /// <returns>MapWinGIS Shape</returns> public static MapWinGIS.Shape mwShapeFromMultiLineString(MultiLineString MLS, MapWinGIS.ShpfileType sfType) { MapWinGIS.Shape mwShape = new MapWinGIS.Shape(); mwShape.Create(sfType); int prt = 0; // Part Index int pt = 0; // Point Index int numParts = MLS.NumGeometries; int maxpt; while (prt < numParts) { LineString LS = MLS.GeometryN[prt] as LineString; maxpt = LS.Coordinates.Count; mwShape.InsertPart(pt, ref prt); for (int I = 0; I < maxpt; I++) { MapWinGIS.Point mwPoint = new MapWinGIS.Point(); mwPoint.x = LS.Coordinates[I].X; mwPoint.y = LS.Coordinates[I].Y; bool result = mwShape.InsertPoint(mwPoint, ref pt); if (result == false) { throw new ApplicationException(mwShape.get_ErrorMsg(mwShape.LastErrorCode)); } pt++; } prt++; } return(mwShape); }
/// <summary> /// Creates a buffer polygon that is Distance around mwShape /// </summary> /// <param name="mwShape">The polygon to buffer</param> /// <param name="Distance">The distance</param> /// <param name="QuadrantSegmants">how rounded the buffer is</param> /// <param name="EndCap">The type of endcap</param> /// <returns></returns> public static MapWinGIS.Shape Buffer(MapWinGIS.Shape mwShape, double Distance, int QuadrantSegmants, MapWindow.Interfaces.Geometries.BufferStyles EndCap) { IGeometry Buffer; Geometry geom = NTS_Adapter.ShapeToGeometry(mwShape); Buffer = geom.Buffer(Distance, QuadrantSegmants, EndCap); return(NTS_Adapter.GeometryToShape(Buffer)); }
private void AddRectangle(double LeftmostX, double LowestY, double RightmostX, double HighestY) { MapWinGIS.Shape newPolygon = new MapWinGIS.Shape(); int partIndex = 0; newPolygon.Create(MapWinGIS.ShpfileType.SHP_POLYGON); newPolygon.InsertPart(0, ref partIndex); int shpIndex = 0; MapWinGIS.Point newPt = new MapWinGIS.Point(); newPt.x = LeftmostX; newPt.y = HighestY; newPt.Z = 0; newPolygon.InsertPoint(newPt, ref shpIndex); newPt = new MapWinGIS.Point(); newPt.x = RightmostX; newPt.y = HighestY; newPt.Z = 0; newPolygon.InsertPoint(newPt, ref shpIndex); newPt = new MapWinGIS.Point(); newPt.x = RightmostX; newPt.y = LowestY; newPt.Z = 0; newPolygon.InsertPoint(newPt, ref shpIndex); newPt = new MapWinGIS.Point(); newPt.x = LeftmostX; newPt.y = LowestY; newPt.Z = 0; newPolygon.InsertPoint(newPt, ref shpIndex); // Finalize -- add it. MapWinGIS.Shapefile sf = (MapWinGIS.Shapefile)g.MapWin.Layers[g.MapWin.Layers.CurrentLayer].GetObject(); if (!sf.EditingShapes || !sf.EditingTable) { sf.StartEditingShapes(true, null); } int addedShapes = sf.NumShapes; sf.EditInsertShape(newPolygon, ref addedShapes); g.CreateUndoPoint(); sf.StopEditingShapes(true, true, null); // Release memory used by point reallocations above GC.Collect(); // And show it: g.UpdateView(); g.MapWin.Plugins.BroadcastMessage("ShapefileEditor: Layer " + g.MapWin.Layers.CurrentLayer.ToString() + ": New Shape Added"); }
private void DrawMoveLine(double x, double y, System.Collections.ArrayList snapPoints) { try { if (snapPoints.Count == 0) { return; } double projX = 0, projY = 0; m_MapWin.View.PixelToProj(x, y, ref projX, ref projY); //get the working shapefile if (m_globals.CurrentLayer == null) { return; } MapWinGIS.Shapefile shpFile = m_globals.CurrentLayer; //get the current vertex index ShapefileEditor.SnapData snapData = (ShapefileEditor.SnapData)snapPoints[0]; int vertexIndex = snapData.pointIndex; //get the current shape MapWinGIS.Shape shp = shpFile.get_Shape(snapData.shpIndex); if (shpFile.ShapefileType == MapWinGIS.ShpfileType.SHP_POINT) { m_MapWin.View.Draw.DrawPoint(projX, projY, m_globals.VertexSize, System.Drawing.Color.Red); } else { if (vertexIndex > 0 && vertexIndex < shp.numPoints - 1) { //draw a line from the prev to current to next vertex MapWinGIS.Point prevPoint = shp.get_Point(vertexIndex - 1); MapWinGIS.Point nextPoint = shp.get_Point(vertexIndex + 1); m_MapWin.View.Draw.DrawLine(prevPoint.x, prevPoint.y, projX, projY, 2, System.Drawing.Color.Red); m_MapWin.View.Draw.DrawLine(projX, projY, nextPoint.x, nextPoint.y, 2, System.Drawing.Color.Red); } else if (vertexIndex == 0) { MapWinGIS.Point nextPoint = shp.get_Point(vertexIndex + 1); m_MapWin.View.Draw.DrawLine(projX, projY, nextPoint.x, nextPoint.y, 2, System.Drawing.Color.Red); } else if (vertexIndex == shp.numPoints - 1) { MapWinGIS.Point prevPoint = shp.get_Point(vertexIndex - 1); m_MapWin.View.Draw.DrawLine(prevPoint.x, prevPoint.y, projX, projY, 2, System.Drawing.Color.Red); } } } catch (System.Exception ex) { m_MapWin.ShowErrorDialog(ex); } }
private void button2_Click(object sender, EventArgs e) { if (!rdGrow.Checked && !rdShrink.Checked) { MapWinUtility.Logger.Message("Please select whether to shrink or expand the shape.", "Choose Operation", MessageBoxButtons.OK, MessageBoxIcon.Information, DialogResult.OK); return; } double trueDist = 0; MapWinGIS.Shape inShp = sf.get_Shape(Shape); if (rdDistance.Checked) { if (!double.TryParse(txtDist.Text, out trueDist)) { MapWinUtility.Logger.Message("The distance was not understood.", "Bad Resize Distance", MessageBoxButtons.OK, MessageBoxIcon.Information, DialogResult.OK); return; } } else { double by = 0; if (!double.TryParse(txtPercent.Text, out by)) { MapWinUtility.Logger.Message("The percentage was not understood.", "Bad Resize Percentage", MessageBoxButtons.OK, MessageBoxIcon.Information, DialogResult.OK); return; } if (by < 1) { MapWinUtility.Logger.Message("Please enter a percentage greater than 1%.", "Bad Resize Percentage", MessageBoxButtons.OK, MessageBoxIcon.Information, DialogResult.OK); return; } if (by > 99 && rdShrink.Checked) { MapWinUtility.Logger.Message("When shrinking a shape, please enter a percentage less than 99%.", "Bad Resize Percentage", MessageBoxButtons.OK, MessageBoxIcon.Information, DialogResult.OK); return; } trueDist = Math.Abs(inShp.Extents.xMax - inShp.Extents.xMin) * (by / 100); } if (rdShrink.Checked) { if (rdPercent.Checked) { trueDist /= 2; } ShrinkOrGrowPoly(ref inShp, -1 * trueDist); } else { ShrinkOrGrowPoly(ref inShp, trueDist); } g.MapWin.View.Redraw(); }
/// <summary> /// Creates a new instance of a MultLineSTring from a Late-Bound object /// </summary> /// <param name="MapWinGIS_Shape">Uses object so we can localized MapWinGIS Dependency</param> /// <returns>A MultLineString</returns> public static MultiLineString CreateMultiLineString(object MapWinGIS_Shape) { if (MapWinGIS_Shape.GetType() != typeof(MapWinGIS.ShapeClass)) { return(null); } MapWinGIS.Shape mwShape = MapWinGIS_Shape as MapWinGIS.Shape; return(CreateMultiLineString(mwShape)); }
/// <summary> /// Exports the shapes from the inputSF which fall within the given polygon, saving to the resultSF provided. /// </summary> /// <returns>False if an error occurs, true otherwise.</returns> public static bool SelectPointsWithPolygon(ref MapWinGIS.Shapefile inputSF, ref MapWinGIS.Shape polygon, ref MapWinGIS.Shapefile resultSF, bool SkipMWShapeID) { MapWinGIS.Utils utils = new MapWinGIS.UtilsClass(); int numPoints = inputSF.NumShapes; int shpIndex = 0; if (Globals.CopyFields(ref inputSF, ref resultSF) == false) { return(false); } for (int i = 0; i <= numPoints - 1; i++) { MapWinGIS.Point currPt = new MapWinGIS.PointClass(); currPt = inputSF.QuickPoint(i, 0); if (utils.PointInPolygon(polygon, currPt)) { shpIndex = resultSF.NumShapes; if (resultSF.EditInsertShape(inputSF.get_Shape(i), ref shpIndex) == false) { gErrorMsg = "Problem inserting shape into result file: " + resultSF.get_ErrorMsg(resultSF.LastErrorCode); Debug.WriteLine(gErrorMsg); Error.SetErrorMsg(gErrorMsg); return(false); } //add the table values int numFields = resultSF.NumFields; for (int j = 0; j <= numFields - 1; j++) { if (resultSF.EditCellValue(j, shpIndex, inputSF.get_CellValue(j, i)) == false) { gErrorMsg = "Problem inserting value into DBF table: " + resultSF.get_ErrorMsg(resultSF.LastErrorCode); Debug.WriteLine(gErrorMsg); Error.SetErrorMsg(gErrorMsg); return(false); } } //end of looping through table } //end of checking if point is inside polygon } //end of looping through points if (resultSF.NumShapes > 0) { if (resultSF.NumFields == 0 || !SkipMWShapeID) { //add the ID field and values if (Globals.DoInsertIDs(ref resultSF) == false) { return(false); } } return(true); } else { return(false); } }
/// <summary> /// Returns the indexes of shapes that fall within the specified polygon. /// </summary> /// <returns>False if an error occurs, true otherwise.</returns> public static bool SelectLinesWithPolygon(ref MapWinGIS.Shapefile inputSF, ref MapWinGIS.Shape polygon, ref System.Collections.ArrayList results) { int numLines = inputSF.NumShapes; results = new System.Collections.ArrayList(); // Boundary intersection test variables double xMin1, xMax1, yMin1, yMax1, zMin1, zMax1, xMin2, xMax2, yMin2, yMax2, zMin2, zMax2; // Get the masking polygon's boundaries only once: polygon.Extents.GetBounds(out xMin2, out yMin2, out zMin2, out xMax2, out yMax2, out zMax2); MapWinGIS.Shape currLine; MapWinGIS.Point currPt; for (int i = 0; i <= numLines - 1; i++) { currLine = inputSF.get_Shape(i); currLine.Extents.GetBounds(out xMin1, out yMin1, out zMin1, out xMax1, out yMax1, out zMax1); // Are the boundaries intersecting? if (!(xMin1 > xMax2 || xMax1 < xMin2 || yMin1 > yMax2 || yMax1 < yMin2)) { //lines are nasty, just because the boundaries intersect it //doesn't mean the line enters the polygon //do a quick point check before doing a more thorough investigation int numPoints = currLine.numPoints; bool ptInside = false; for (int j = 0; j <= numPoints - 1; j++) { currPt = currLine.get_Point(j); if (polygon.PointInThisPoly(currPt)) { ptInside = true; break; } } if (ptInside) { results.Add(i); }//end of ptInside check else { // Avoid using a temp file to test each individual file; // instead, just see if the line crosses the polygon if (LineCrossesPoly(ref currLine, ref polygon)) { //part of the line lies within the polygon, add to result file results.Add(i); } //end of successful cross } //end of else no points were found inside polygon } //end of checking bounds } //end of looping through lines return(results.Count > 0); }
/// <summary> /// Not implemented /// Computes the distance between a point and a polygon. /// </summary> /// <param name="pt">The point to be considered.</param> /// <param name="polygon">The line to be considered.</param> /// <param name="distType">Indicates whether the distance should be from the nearest, farthest, or centroid of the polygon.</param> /// <returns></returns> public static double DistancePointToPolygon(MapWinGIS.Point pt, MapWinGIS.Shape polygon, int distType) { //TODO: Implement this function Error.ClearErrorLog(); gErrorMsg = "This function is not yet implemented."; Error.SetErrorMsg(gErrorMsg); Debug.WriteLine(gErrorMsg); return(0); }
/// <summary> /// Returns a MultiLineString geometry collection derived from the mwShape /// </summary> /// <param name="mwShape">The shape to convert into a multi-line string</param> public static MultiLineString CreateMultiLineString(MapWinGIS.Shape mwShape) { MultiLineString MLS = new MultiLineString(); // Variables int numParts; // The number of parts in the shape int numPoints; // The number of points in the shape LineString LS; // Parameter checking if (mwShape == null) { throw new ArgumentException("mwShape should either not be null, or not be specified."); } if (mwShape.ShapeType == MapWinGIS.ShpfileType.SHP_MULTIPATCH || mwShape.ShapeType == MapWinGIS.ShpfileType.SHP_MULTIPOINT || mwShape.ShapeType == MapWinGIS.ShpfileType.SHP_MULTIPOINTM || mwShape.ShapeType == MapWinGIS.ShpfileType.SHP_MULTIPOINTZ || mwShape.ShapeType == MapWinGIS.ShpfileType.SHP_NULLSHAPE || mwShape.ShapeType == MapWinGIS.ShpfileType.SHP_POINT || mwShape.ShapeType == MapWinGIS.ShpfileType.SHP_POINTM || mwShape.ShapeType == MapWinGIS.ShpfileType.SHP_POINTZ) { throw new ArgumentException("Argument mwShape shapetype must be a polyline or polygon."); } MLS.GeometryN = new List <Geometry>(); numParts = mwShape.NumParts; numPoints = mwShape.numPoints; // if NumParts = 0, treat as though the whole shape was a single part int prt = 0; // prt is the part index int pt = 0; // pt is the point index while (prt < numParts - 1) { int maxpt = mwShape.get_Part(prt + 1); LS = new LineString(); while (pt < maxpt) { Coordinate Coord = GeometryFactory.CreateCoordinate(mwShape.get_Point(pt)); LS.Coordinates.Add(Coord); pt++; } MLS.GeometryN.Add(LS); prt++; } LS = new LineString(); while (pt < numPoints) { Coordinate Coord = GeometryFactory.CreateCoordinate(mwShape.get_Point(pt)); LS.Coordinates.Add(Coord); pt++; } MLS.GeometryN.Add(LS); return(MLS); }
private void RotateShape(MapWinGIS.Shape shape, double Angle, double aboutX, double aboutY) { for (int i = 0; i < shape.numPoints; i++) { MapWinGIS.Point pt = shape.get_Point(i); double Nx = 0, Ny = 0; Rotate(Angle, pt.x, pt.y, aboutX, aboutY, ref Nx, ref Ny); pt.x = Nx; pt.y = Ny; } }
private void AddEllipse(double LeftmostX, double LowestY, double RightmostX, double HighestY) { MapWinGIS.Shape newPolygon = new MapWinGIS.Shape(); int partIndex = 0; newPolygon.Create(MapWinGIS.ShpfileType.SHP_POLYGON); newPolygon.InsertPart(0, ref partIndex); int shpIndex = 0; double t, a, b, tinc, centx, centy; a = RightmostX - LeftmostX; b = HighestY - LowestY; tinc = Math.PI * 2 / (a + b); centx = (LeftmostX + RightmostX) * .5; centy = (LowestY + HighestY) * .5; MapWinGIS.Point newPt = new MapWinGIS.Point(); newPt.x = centx + a; newPt.y = centy; newPt.Z = 0; newPolygon.InsertPoint(newPt, ref shpIndex); for (t = 0; t < Math.PI * 2; t += tinc) { MapWinGIS.Point nextPt = new MapWinGIS.Point(); nextPt.x = centx + a * Math.Cos(t); nextPt.y = centy - b * Math.Sin(t); nextPt.Z = 0; newPolygon.InsertPoint(nextPt, ref shpIndex); } // Finalize -- add it. MapWinGIS.Shapefile sf = (MapWinGIS.Shapefile)g.MapWin.Layers[g.MapWin.Layers.CurrentLayer].GetObject(); if (!sf.EditingShapes || !sf.EditingTable) { sf.StartEditingShapes(true, null); } int addedShapes = sf.NumShapes; sf.EditInsertShape(newPolygon, ref addedShapes); g.CreateUndoPoint(); sf.StopEditingShapes(true, true, null); // And show it: g.UpdateView(); g.MapWin.Plugins.BroadcastMessage("ShapefileEditor: Layer " + g.MapWin.Layers.CurrentLayer.ToString() + ": New Shape Added"); }
public void Moveshape(double dblDistanceX, double dblDistanceY, MapWinGIS.Shape objShape) { int intNumPoints = objShape.numPoints; //m_globals.LogWrite("numPoints = " + intNumPoints.ToString ()); for (int ixPoint = 0; ixPoint < intNumPoints; ixPoint++) { //Move each point of the shape. MovePoint(objShape, ixPoint, dblDistanceX, dblDistanceY); } ; }