Example #1
0
        /// <summary>
        /// Convert the shape to WKT
        /// </summary>
        /// <param name="shapefilename">
        /// The shapefilename.
        /// </param>
        /// <param name="shapeIndex">
        /// The shape index.
        /// </param>
        /// <param name="theForm">
        /// The form.
        /// </param>
        /// <returns>
        /// The WKT of the shape
        /// </returns>
        private static string ConvertToWkt(string shapefilename, int shapeIndex, Form1 theForm)
        {
            try
            {
                // Check inputs:
                if (!Helper.CheckShapefileLocation(shapefilename, theForm))
                {
                    return(null);
                }

                // Open the sf:
                var sf = Fileformats.OpenShapefile(shapefilename, theForm);
                if (sf == null)
                {
                    theForm.Error(string.Empty, "Opening input shapefile was unsuccessful");
                    return(null);
                }

                var wkt = sf.Shape[shapeIndex].ExportToWKT();
                if (wkt == null || wkt.Trim() == string.Empty)
                {
                    theForm.Error(string.Empty, "ExportToWKT was unsuccessful");
                    return(null);
                }

                return(wkt);
            }
            catch (Exception exception)
            {
                theForm.Error(string.Empty, "Exception: " + exception.Message);
            }

            return(null);
        }
Example #2
0
        /// <summary>
        /// Convert WKT to shape and test result
        /// </summary>
        /// <param name="shapefilename">
        /// The shapefilename.
        /// </param>
        /// <param name="shapeIndex">
        /// The shape index.
        /// </param>
        /// <param name="wkt">
        /// The wkt.
        /// </param>
        /// <param name="theForm">
        /// The form.
        /// </param>
        /// <returns>
        /// True on success
        /// </returns>
        private static bool ConvertFromWkt(string shapefilename, int shapeIndex, string wkt, Form1 theForm)
        {
            // Convert the WKT
            var shapeWkt = new Shape();

            if (!shapeWkt.ImportFromWKT(wkt))
            {
                theForm.Error(
                    string.Empty,
                    "ImportFromWKT was unsuccessful: " + shapeWkt.ErrorMsg[shapeWkt.LastErrorCode]);
                return(false);
            }

            // Check with the original shape if it is still the same:
            var sf = Fileformats.OpenShapefile(shapefilename, theForm);

            if (Helper.AreShapesDifferent(sf.Shape[shapeIndex], shapeWkt, theForm))
            {
                theForm.Progress(string.Empty, 100, "The two shapes are identical.");
            }

            return(true);
        }
Example #3
0
        /// <summary>
        /// Get the closest point
        /// </summary>
        /// <param name="inputShapefile">
        /// The input shapefile.
        /// </param>
        /// <param name="searchShapefile">
        /// The search shapefile.
        /// </param>
        /// <param name="theForm">
        /// The form.
        /// </param>
        /// <returns>
        /// True on success
        /// </returns>
        private static bool ClosestPoint(string inputShapefile, string searchShapefile, Form1 theForm)
        {
            try
            {
                // Check inputs:
                if (!Helper.CheckShapefileLocation(inputShapefile, theForm))
                {
                    return(false);
                }

                if (!Helper.CheckShapefileLocation(searchShapefile, theForm))
                {
                    return(false);
                }

                // Open the sf:
                var inputSf = Fileformats.OpenShapefile(inputShapefile, theForm);
                if (inputSf == null)
                {
                    theForm.Error(string.Empty, "Opening input shapefile was unsuccessful");
                    return(false);
                }

                var searchSf = Fileformats.OpenShapefile(searchShapefile, theForm);
                if (searchSf == null)
                {
                    theForm.Error(string.Empty, "Opening search shapefile was unsuccessful");
                    return(false);
                }

                // Create resulting shapefile:
                var linksSf = new Shapefile {
                    GlobalCallback = theForm
                };
                linksSf.CreateNew(string.Empty, ShpfileType.SHP_POLYLINE);
                var fieldIndex = linksSf.EditAddField("FoundId", FieldType.INTEGER_FIELD, 0, 0);

                // Get a random shape
                var index            = new Random().Next(inputSf.NumShapes - 1);
                var randomInputShape = inputSf.Shape[index];

                // Select the shape:
                var utils = new Utils {
                    GlobalCallback = theForm
                };
                inputSf.SelectionColor       = utils.ColorByName(tkMapColor.Yellow);
                inputSf.ShapeSelected[index] = true;

                // Load the files:
                MyAxMap.RemoveAllLayers();
                MyAxMap.AddLayer(searchSf, true);
                MyAxMap.AddLayer(inputSf, true);

                // To store the lenght and index:
                var minLength    = double.MaxValue;
                var closestIndex = -1;

                // Search around the location until at least on shape is found.
                // To optimize searching make sure a spatial index is used:
                if (!searchSf.HasSpatialIndex)
                {
                    searchSf.CreateSpatialIndex(searchSf.Filename);
                }

                searchSf.UseSpatialIndex = true;

                // create start search box:
                var searchExtent = randomInputShape.Extents;

                // Make the start tolerance depending on the projection:
                var tolerance = 2D;
                if (searchSf.GeoProjection.IsGeographic)
                {
                    tolerance = 0.01;
                }

                var    foundShapeId = -1;
                object results      = null;

                // Search in increasing circles:
                var notFound = true;

                // TODO: Add continious loop prevention
                while (notFound)
                {
                    if (searchSf.SelectShapes(searchExtent, tolerance, SelectMode.INTERSECTION, ref results))
                    {
                        var shapeIds = results as int[];

                        // Use the first one:
                        if (shapeIds != null)
                        {
                            foreach (var shapeId in shapeIds)
                            {
                                foundShapeId = shapeId;

                                // When the shapes intersect you get wrong values:
                                var intersects = randomInputShape.Intersects(searchSf.Shape[foundShapeId]);

                                if (intersects)
                                {
                                    continue;
                                }

                                // stop searching:
                                notFound = false;
                                break;
                            }
                        }
                    }

                    // increase tolerance:
                    tolerance = tolerance + tolerance;
                }

                if (foundShapeId == -1)
                {
                    theForm.Error(string.Empty, "Error! Could not find any shapes");
                    return(false);
                }

                // Select the found shape:
                searchSf.SelectionColor = utils.ColorByName(tkMapColor.Red);
                searchSf.ShapeSelected[foundShapeId] = true;

                var link = randomInputShape.ClosestPoints(searchSf.Shape[foundShapeId]);
                if (link != null && link.numPoints > 1)
                {
                    if (link.IsValid)
                    {
                        var shapeId = linksSf.EditAddShape(link);
                        linksSf.EditCellValue(fieldIndex, shapeId, foundShapeId);
                        if (minLength > link.Length)
                        {
                            minLength    = link.Length;
                            closestIndex = foundShapeId;
                        }
                    }
                    else
                    {
                        theForm.Error(string.Empty, "Found link line is invalid: " + link.IsValidReason);
                        return(false);
                    }
                }
                else
                {
                    theForm.Error(string.Empty, "pointShp.ClosestPoints() could not find anything");
                    return(false);
                }

                linksSf.DefaultDrawingOptions.LineColor = utils.ColorByName(tkMapColor.Black);
                linksSf.DefaultDrawingOptions.LineWidth = 2;
                MyAxMap.AddLayer(linksSf, true);
                linksSf.GenerateLabels(fieldIndex, tkLabelPositioning.lpMiddleSegment);
                linksSf.Labels.OffsetX = 10;
                linksSf.Labels.OffsetY = 10;

                MyAxMap.ZoomToMaxExtents();

                // Wait to show the map:
                Application.DoEvents();

                theForm.Progress(
                    string.Format(
                        "The closest shape is {0}, has a value of {1} and a length of {2}",
                        closestIndex,
                        searchSf.CellValue[0, closestIndex],
                        minLength));

                // Save result:
                var newFilename = inputSf.Filename.Replace(".shp", "-Closest.shp");
                Helper.DeleteShapefile(newFilename);
                if (!linksSf.SaveAs(newFilename, theForm))
                {
                    return(false);
                }

                theForm.Progress(string.Empty, 100, "The resulting shapefile has been saved as " + newFilename);
            }
            catch (Exception exception)
            {
                theForm.Error(string.Empty, "Exception: " + exception.Message);
                return(false);
            }

            return(true);
        }
Example #4
0
        /// <summary>
        /// Clip the shapefile
        /// </summary>
        /// <param name="shapefilename">
        /// The shapefile name
        /// </param>
        /// <param name="overlayFilename">
        /// The name of the overlay shapefile
        /// </param>
        /// <param name="theForm">
        /// The form
        /// </param>
        /// <returns>
        /// True on success
        /// </returns>
        private static bool ClipShapefile(string shapefilename, string overlayFilename, Form1 theForm)
        {
            try
            {
                // Check inputs:
                if (!Helper.CheckShapefileLocation(shapefilename, theForm))
                {
                    return(false);
                }

                if (!Helper.CheckShapefileLocation(overlayFilename, theForm))
                {
                    return(false);
                }

                // Open the sf:
                var sf = Fileformats.OpenShapefile(shapefilename, theForm);
                if (sf == null)
                {
                    theForm.Error(string.Empty, "Opening input shapefile was unsuccessful");
                    return(false);
                }

                var overlaySf = Fileformats.OpenShapefile(overlayFilename, theForm);
                if (overlaySf == null)
                {
                    theForm.Error(string.Empty, "Opening overlay shapefile was unsuccessful");
                    return(false);
                }

                theForm.Progress(string.Format(
                                     "Clipping {0} ({1}) with {2} ({3})",
                                     Path.GetFileName(shapefilename),
                                     sf.ShapefileType,
                                     Path.GetFileName(overlayFilename),
                                     overlaySf.ShapefileType));

                var globalSettings = new GlobalSettings();
                globalSettings.ResetGdalError();
                theForm.Progress(string.Empty, 0, "Start clipping " + Path.GetFileName(shapefilename));

                // selecting only part of overlay, then the check about the varying
                // number of shapes in input/output will work
                var max = Math.Max(overlaySf.NumShapes / 2, 1);
                for (var i = 0; i < max; i++)
                {
                    overlaySf.ShapeSelected[i] = true;
                }

                var clippedSf = sf.Clip(false, overlaySf, true);

                // Do some checks:
                if (!Helper.CheckShapefile(sf, clippedSf, globalSettings.GdalLastErrorMsg, theForm))
                {
                    return(false);
                }

                Helper.ColorShapes(ref clippedSf, 0, tkMapColor.DarkRed, tkMapColor.LightSeaGreen, true);

                // Count the resulting shapes it should be higher than the input shapefile.
                var numClippedSf = clippedSf.NumShapes;
                var numInputSf   = sf.NumShapes;

                // Reset map:
                MyAxMap.Clear();

                if (numClippedSf == numInputSf)
                {
                    // Nothing was clipped
                    theForm.Error(
                        string.Empty,
                        "The resulting shapefile has the same number of shapes as the input shapefile. Either the input files are incorrect or the clipping function doesn't behaves as expected.");
                    MyAxMap.AddLayer(sf, true);
                    MyAxMap.AddLayer(overlaySf, true);

                    // Wait to show the map:
                    Application.DoEvents();

                    return(false);
                }

                // Save result:
                if (overlayFilename != null)
                {
                    var newFilename = shapefilename.Replace(
                        ".shp",
                        string.Format("-{0}", Path.GetFileName(overlayFilename).Replace(".shp", "-clipped.shp")));
                    Helper.DeleteShapefile(newFilename);
                    clippedSf.SaveAs(newFilename, theForm);
                    theForm.Progress(string.Empty, 100, "The resulting shapefile has been saved as " + newFilename);

                    // Load the files:
                    Fileformats.OpenShapefileAsLayer(overlayFilename, theForm, false);
                    if (MyAxMap.AddLayer(clippedSf, true) == -1)
                    {
                        theForm.Error(string.Empty, "Could not add the clipped shapefile to the map");
                        return(false);
                    }

                    // Wait to show the map:
                    Application.DoEvents();
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception exception)
            {
                theForm.Error(string.Empty, "Exception: " + exception.Message);
            }

            theForm.Progress(string.Empty, 100, "This clipping has finished.");
            return(true);
        }
Example #5
0
        /// <summary>
        /// Buffer the shapefile
        /// </summary>
        /// <param name="shapefilename">
        /// The shapefilename.
        /// </param>
        /// <param name="theForm">
        /// The form.
        /// </param>
        /// <returns>
        /// True on success
        /// </returns>
        private static bool BufferShapefile(string shapefilename, Form1 theForm)
        {
            try
            {
                // Check inputs:
                if (!Helper.CheckShapefileLocation(shapefilename, theForm))
                {
                    return(false);
                }

                // Open the sf:
                var sf = Fileformats.OpenShapefile(shapefilename, theForm);
                if (sf == null)
                {
                    theForm.Error(string.Empty, "Opening input shapefile was unsuccessful");
                    return(false);
                }

                var globalSettings = new GlobalSettings();
                globalSettings.ResetGdalError();
                theForm.Progress(string.Empty, 100, "Start buffering " + Path.GetFileName(shapefilename));

                // Make the distance depending on the projection.
                var distance = 1000.0;
                if (sf.GeoProjection.IsGeographic)
                {
                    distance = 0.1;
                }

                var bufferedSf = sf.BufferByDistance(distance, 16, false, false);

                // Do some checks:
                if (!Helper.CheckShapefile(sf, bufferedSf, globalSettings.GdalLastErrorMsg, theForm))
                {
                    return(false);
                }

                Helper.ColorShapes(ref bufferedSf, 0, tkMapColor.LightBlue, tkMapColor.LightYellow, true);

                // Save result:
                var newFilename = shapefilename.Replace(".shp", "-buffered.shp");
                Helper.DeleteShapefile(newFilename);
                bufferedSf.SaveAs(newFilename, theForm);
                theForm.Progress(string.Empty, 100, "The resulting shapefile has been saved as " + newFilename);

                // Load the files:
                MyAxMap.Clear();
                Fileformats.OpenShapefileAsLayer(shapefilename, theForm, true);
                bufferedSf.DefaultDrawingOptions.FillVisible = false;
                if (MyAxMap.AddLayer(bufferedSf, true) == -1)
                {
                    theForm.Error(string.Empty, "Could not add the buffered shapefile to the map");
                    return(false);
                }

                // Wait to show the map:
                Application.DoEvents();
            }
            catch (Exception exception)
            {
                theForm.Error(string.Empty, "Exception: " + exception.Message);
            }

            return(true);
        }
Example #6
0
        /// <summary>
        /// Dissolve the shapefile
        /// </summary>
        /// <param name="shapefilename">
        /// The shapefilename.
        /// </param>
        /// <param name="fieldIndex">
        /// The field index.
        /// </param>
        /// <param name="theForm">
        /// The form.
        /// </param>
        /// <returns>
        /// True on success
        /// </returns>
        internal static bool DissolveShapefile(string shapefilename, int fieldIndex, Form1 theForm)
        {
            try
            {
                // Check inputs:
                if (!Helper.CheckShapefileLocation(shapefilename, theForm))
                {
                    return(false);
                }

                // Open the sf:
                var sf = Fileformats.OpenShapefile(shapefilename, theForm);
                if (sf == null)
                {
                    theForm.Error(string.Empty, "Opening input shapefile was unsuccessful");
                    return(false);
                }

                var globalSettings = new GlobalSettings();
                globalSettings.ResetGdalError();
                theForm.Progress(string.Empty, 0, "Start dissolving " + Path.GetFileName(shapefilename));

                var dissolvedSf = sf.Dissolve(fieldIndex, false);

                // Do some checks:
                if (!Helper.CheckShapefile(sf, dissolvedSf, globalSettings.GdalLastErrorMsg, theForm))
                {
                    return(false);
                }

                // The resulting shapefile has only 1 field:
                Helper.ColorShapes(ref dissolvedSf, 0, tkMapColor.BlueViolet, tkMapColor.Wheat, true);

                // Save result:
                var newFilename = shapefilename.Replace(".shp", "-dissolved.shp");
                Helper.DeleteShapefile(newFilename);
                dissolvedSf.SaveAs(newFilename, theForm);
                theForm.Progress(string.Empty, 100, "The resulting shapefile has been saved as " + newFilename);

                // Load the files:
                MyAxMap.Clear();
                if (MyAxMap.AddLayer(dissolvedSf, true) == -1)
                {
                    theForm.Error(string.Empty, "Cannot open dissolved shapefiles");
                    return(false);
                }

                sf.DefaultDrawingOptions.FillVisible = false;

                // MyAxMap.AddLayer(sf, true);

                // Wait to show the map:
                Application.DoEvents();

                var msg = string.Format(
                    "The dissolved shapefile now has {0} shapes instead of {1} and has {2} rows",
                    dissolvedSf.NumShapes,
                    sf.NumShapes,
                    dissolvedSf.Table.NumRows);
                theForm.Progress(msg);
            }
            catch (Exception exception)
            {
                theForm.Error(string.Empty, "Exception: " + exception.Message);
            }

            theForm.Progress(string.Empty, 100, "The Dissolve shapefile test has finished");

            return(true);
        }
Example #7
0
        /// <summary>
        /// Run the intersect shapefile test
        /// </summary>
        /// <param name="shapefilename">
        /// The shapefile name
        /// </param>
        /// <param name="overlayFilename">
        /// The name of the overlay shapefile
        /// </param>
        /// <param name="theForm">
        /// The the form.
        /// </param>
        /// <returns>
        /// True on success
        /// </returns>
        internal static bool IntersectShapefile(string shapefilename, string overlayFilename, Form1 theForm)
        {
            try
            {
                // Check inputs:
                if (!Helper.CheckShapefileLocation(shapefilename, theForm))
                {
                    return(false);
                }

                if (!Helper.CheckShapefileLocation(overlayFilename, theForm))
                {
                    return(false);
                }

                // Open the sf:
                var sf = Fileformats.OpenShapefile(shapefilename, theForm);
                if (sf == null)
                {
                    theForm.Error(string.Empty, "Opening input shapefile was unsuccessful");
                    return(false);
                }

                var overlaySf = Fileformats.OpenShapefile(overlayFilename, theForm);
                if (overlaySf == null)
                {
                    theForm.Error(string.Empty, "Opening overlay shapefile was unsuccessful");
                    return(false);
                }

                var globalSettings = new GlobalSettings();
                globalSettings.ResetGdalError();
                theForm.Progress(string.Empty, 0, "Start intersecting " + Path.GetFileName(shapefilename));

                // var intersectedSf = sf.Union(false, overlaySf, false);

                // With SHP_NULLSHAPE the most obvious type will be used:
                var intersectedSf = sf.GetIntersection(false, overlaySf, false, ShpfileType.SHP_NULLSHAPE, theForm);

                // Do some checks:)
                if (!Helper.CheckShapefile(sf, intersectedSf, globalSettings.GdalLastErrorMsg, theForm))
                {
                    return(false);
                }

                theForm.Progress("Coloring the resulting shapefile.");
                Helper.ColorShapes(ref intersectedSf, 0, tkMapColor.BlueViolet, tkMapColor.DarkRed, true);

                // Save result:
                var newFilename = overlayFilename.Replace(".shp", "-intersected.shp");
                Helper.DeleteShapefile(newFilename);
                intersectedSf.SaveAs(newFilename, theForm);
                theForm.Progress(string.Empty, 100, "The resulting shapefile has been saved as " + newFilename);

                // Load the files:
                MyAxMap.RemoveAllLayers();
                if (MyAxMap.AddLayer(intersectedSf, true) == -1)
                {
                    theForm.Error(string.Empty, "Could not add the intersected shapefile to the map");
                    return(false);
                }

                // Wait to show the map:
                Application.DoEvents();

                // MyAxMap.AddLayer(overlaySf, true);
            }
            catch (Exception exception)
            {
                theForm.Error(string.Empty, "Exception: " + exception.Message);
            }

            return(true);
        }
Example #8
0
        /// <summary>
        /// The simplify shapefile.
        /// </summary>
        /// <param name="shapefilename">
        /// The shapefilename.
        /// </param>
        /// <param name="theForm">
        /// The form.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        private static bool SimplifyShapefile(string shapefilename, Form1 theForm)
        {
            try
            {
                // Check inputs:
                if (!Helper.CheckShapefileLocation(shapefilename, theForm))
                {
                    return(false);
                }

                // Open the sf:
                var sf = Fileformats.OpenShapefile(shapefilename, theForm);
                if (sf == null)
                {
                    theForm.Error(string.Empty, "Opening input shapefile was unsuccessful");
                    return(false);
                }

                var globalSettings = new GlobalSettings();
                globalSettings.ResetGdalError();
                theForm.Progress(string.Empty, 0, "Start simplifying " + Path.GetFileName(shapefilename));

                // Make the tolerance depending on the projection.
                var tolerance = 10d;
                if (sf.GeoProjection.IsGeographic)
                {
                    tolerance = 0.1;
                }

                var simplifiedSf = sf.SimplifyLines(tolerance, false);

                // Do some checks:
                if (!Helper.CheckShapefile(sf, simplifiedSf, globalSettings.GdalLastErrorMsg, theForm))
                {
                    return(false);
                }

                // give the resulting lines a good width and color:
                var utils = new Utils {
                    GlobalCallback = theForm
                };
                simplifiedSf.DefaultDrawingOptions.LineWidth   = 2;
                simplifiedSf.DefaultDrawingOptions.LineColor   = utils.ColorByName(tkMapColor.OrangeRed);
                simplifiedSf.DefaultDrawingOptions.LineStipple = tkDashStyle.dsSolid;

                // Save result:
                var newFilename = shapefilename.Replace(".shp", "-simplified.shp");
                Helper.DeleteShapefile(newFilename);
                simplifiedSf.SaveAs(newFilename, theForm);
                theForm.Progress(string.Empty, 100, "The resulting shapefile has been saved as " + newFilename);

                // Load the files:
                MyAxMap.Clear();
                if (MyAxMap.AddLayer(simplifiedSf, true) == -1)
                {
                    theForm.Error(string.Empty, "Could not add the simplified shapefile to the map");
                    return(false);
                }

                Fileformats.OpenShapefileAsLayer(shapefilename, theForm, false);

                // Wait to show the map:
                Application.DoEvents();
            }
            catch (Exception exception)
            {
                theForm.Error(string.Empty, "Exception: " + exception.Message);
            }

            return(true);
        }