Exemplo n.º 1
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="node"></param>
        /// <param name="addEnv"></param>
        /// <returns></returns>
        public static Node CreateExpanded(Node node, IEnvelope addEnv)
        {
            IEnvelope expandEnv = new Envelope(addEnv);
            if (node != null) 
                expandEnv.ExpandToInclude(node.env);

            Node largerNode = CreateNode(expandEnv);
            if (node != null) 
                largerNode.InsertNode(node);
            return largerNode;
        }
Exemplo n.º 2
0
		/// <summary>
		/// Transforms a <see cref="IEnvelope" /> object.
		/// </summary>
        /// <param name="box"></param>
		/// <param name="transform"></param>
		/// <returns></returns>
		public static IEnvelope TransformBox(IEnvelope box, IMathTransform transform)
		{
			if (box == null) return null;

            double[][] corners = new double[4][];
            corners[0] = transform.Transform(ToArray(box.MinX, box.MinY)); //LL
            corners[1] = transform.Transform(ToArray(box.MaxX, box.MaxY)); //UR
            corners[2] = transform.Transform(ToArray(box.MinX, box.MaxY)); //UL
            corners[3] = transform.Transform(ToArray(box.MaxX, box.MinY)); //LR

			IEnvelope result = new Envelope();
            foreach (double[] p in corners)
				result.ExpandToInclude(p[0], p[1]);
			return result;
		}
Exemplo n.º 3
0
 /// <summary>
 /// Returns the BoundingBox of the dataset.
 /// </summary>
 /// <returns>BoundingBox</returns>
 public BoundingBox GetExtents()
 {
     Envelope envelope = new Envelope();
     foreach (Feature feature in features)
         envelope.ExpandToInclude(feature.Geometry.EnvelopeInternal);
     return GeometryConverter.ToSharpMapBoundingBox(envelope);
 }
Exemplo n.º 4
0
        /// <summary>
        /// Retrieves the contents of the specified table, and writes them to a shapefile
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public bool ExportGriddedShapefile(string tableName)
        {
            try
            {
                _log.DebugFormat("Retrieving contents of job {0}", tableName);
                //don't filter out geometries, we'll do that at the cell level
                var exportFeatures = GetShapeFeaturesToExport(tableName, false);
                if ((exportFeatures == null) || (exportFeatures.Count == 0))
                {
                    _log.ErrorFormat("Export of Job \"{0}\" failed, no features to export!", tableName);
                    return false;
                }

                ICoordinateSystem outputCrs = GeographicCoordinateSystem.WGS84;
                if (!string.IsNullOrEmpty(this.OutputProjectionFilename))
                {
                    outputCrs = Utilities.GetCoordinateSystemByWKTFile(this.OutputProjectionFilename);
                }

                //if we need to reproject:
                List<IGeometry> filteringGeoms = GetFilteringGeometries(this.ExportFilterFilename, outputCrs);

                //put everything into a basic spatial index
                Envelope env = new Envelope();
                var index = new GisSharpBlog.NetTopologySuite.Index.Strtree.STRtree();
                for (int i = 0; i < exportFeatures.Count; i++)
                {
                    Feature f = exportFeatures[i];
                    index.Insert(f.Geometry.EnvelopeInternal, f);
                    env.ExpandToInclude(f.Geometry.EnvelopeInternal);
                }
                if (IsCancelled()) { _log.Debug("Job Cancelled..."); return false; }
                index.Build();

                //adjust envelope to only scan area inside filtering geometries
                if (!string.IsNullOrEmpty(this.GridEnvelopeFilename))
                {
                    //a specified envelope file overrides the envelope of the filtering geometries
                    env = GetGridEnvelope();
                }
                else if ((filteringGeoms != null) && (filteringGeoms.Count > 0))
                {
                    //in the absence ... //TODO: finish--
                    env = new Envelope();
                    for (int i = 0; i < filteringGeoms.Count; i++)
                    {
                        env.ExpandToInclude(filteringGeoms[i].EnvelopeInternal);
                    }
                }

                //progress tracking
                DateTime start = DateTime.Now, lastCheck = DateTime.Now;
                int lastProgress = 0;

                var features = new List<Feature>(exportFeatures.Count);

                double cellWidth = GridCellWidth;
                double cellHeight = GridCellHeight;
                bool discardEmptyGridCells = !IncludeEmptyGridCells;

                int numRows = (int)Math.Ceiling(env.Height / cellHeight);
                int numCols = (int)Math.Ceiling(env.Width / cellWidth);
                int expectedCells = numRows * numCols;

                if (expectedCells > 1000000)
                {
                    _log.Warn("**********************");
                    _log.Warn("Your selected area will produce a shapefile with over a million cells, is that a good idea?");
                    _log.WarnFormat("Area of {0}, Expected Cell Count of {1}", env.Area, expectedCells);
                    _log.Warn("**********************");
                }

                DbaseFileHeader header = null;
                using (var conn = DbClient.GetConnection())
                {
                    //Dictionary<string, DataRow> shapeDict = GetShapeRowsByLOGRECNO(conn);
                    var variablesDT = DataClient.GetMagicTable(conn, DbClient, string.Format("SELECT * FROM \"{0}\" where 0 = 1 ", tableName));
                    header = ShapefileHelper.SetupHeader(variablesDT);
                }
                ShapefileHelper.AddColumn(header, "CELLID", typeof(string));
                ShapefileHelper.AddColumn(header, "GEOID", typeof(string));
                if (this.AddStrippedGEOIDcolumn)
                {
                    ShapefileHelper.AddColumn(header, "GEOID_STRP", typeof(string));
                }

                //lets not add these to the fishnet exports just yet
                //if (this.AddGeometryAttributesToOutput)
                //{
                //    ShapefileHelper.AddColumn(header, "AREA", typeof(double));
                //    ShapefileHelper.AddColumn(header, "PERIMETER", typeof(double));
                //    ShapefileHelper.AddColumn(header, "CENTROID", typeof(double));
                //}

                int cellCount = 0;
                int xidx = 0;
                for (double x = env.MinX; x < env.MaxX; x += cellWidth)
                {
                    xidx++;
                    int yidx = 0;
                    for (double y = env.MinY; y < env.MaxY; y += cellHeight)
                    {
                        yidx++;
                        cellCount++;
                        string cellID = string.Format("{0}_{1}", xidx, yidx);

                        Envelope cellEnv = new Envelope(x, x + cellWidth, y, y + cellHeight);
                        IGeometry cellCenter = new Point(cellEnv.Centre);
                        IGeometry cellGeom = Utilities.IEnvToIGeometry(cellEnv);

                        Feature found = null;
                        IList mightMatch = index.Query(cellGeom.EnvelopeInternal);
                        foreach (Feature f in mightMatch)
                        {
                            if (f.Geometry.Contains(cellCenter))
                            {
                                found = f;
                                break;
                            }
                        }

                        if ((found == null) && (discardEmptyGridCells))
                        {
                            //_log.DebugFormat("No feature found for cell {0}", cellID);
                            continue;
                        }

                        //if we have filtering geometries, skip a cell if it isn't included
                        if (!IsIncluded(cellGeom, filteringGeoms))
                        {
                            continue;
                        }

                        if ((cellCount % 1000) == 0)
                        {
                            int step = (int)((((double)cellCount) / ((double)expectedCells)) * 100.0);
                            TimeSpan elapsed = (DateTime.Now - lastCheck);
                            if ((step != lastProgress) && (elapsed.TotalSeconds > 1))
                            {
                                _log.DebugFormat("{0:###.##}% complete, {1:#0.0#} seconds, {2} built, {3} checked, {4} left",
                                   step, (DateTime.Now - start).TotalSeconds,
                                   features.Count,
                                   cellCount,
                                   expectedCells - cellCount
                                   );
                                lastCheck = DateTime.Now;
                                lastProgress = step;

                                if (IsCancelled()) { _log.Debug("Job Cancelled..."); return false; }
                            }
                        }

                        //this is a lot of work just to add an id...
                        AttributesTable attribs = new AttributesTable();
                        if (found != null)
                        {
                            //if (!found.Attributes.GetNames().Contains("GEOID"))
                            //    throw new Exception("GEOID NOT FOUND!!!!");
                            foreach (string name in found.Attributes.GetNames())
                            {
                                attribs.AddAttribute(name, found.Attributes[name]);
                            }
                            attribs.AddAttribute("CELLID", cellID);
                        }
                        else
                        {
                            foreach (var field in header.Fields)
                            {
                                attribs.AddAttribute(field.Name, null);
                            }
                            attribs["CELLID"] = cellID;
                        }

                        features.Add(new Feature(cellGeom, attribs));
                    }
                }
                _log.Debug("Done building cells, Saving Shapefile...");
                header.NumRecords = features.Count;

                if (features.Count == 0)
                {
                    _log.Error("No features found, exiting!");
                    return false;
                }

                string newShapefilename = Path.Combine(Environment.CurrentDirectory, tableName);
                if (!string.IsNullOrEmpty(OutputFolder))
                {
                    newShapefilename = Path.Combine(OutputFolder, tableName);
                }

                if (IsCancelled()) { _log.Debug("Job Cancelled..."); return false; }
                var writer = new ShapefileDataWriter(newShapefilename, ShapefileHelper.GetGeomFactory());
                writer.Header = header;
                writer.Write(features);

                if (!string.IsNullOrEmpty(this.OutputProjectionFilename))
                {
                    //Reproject everything in this file to the requested projection...
                    ShapefileHelper.MakeOutputProjFile(this.OutputProjectionFilename, newShapefilename);
                }
                else
                {
                    ShapefileHelper.MakeCensusProjFile(newShapefilename);
                }

                _log.Debug("Done! Shapefile exported successfully");
                return true;
            }
            catch (FileNotFoundException notFound)
            {
                string msg = "A needed file couldn't be found: " + notFound.FileName;
                _log.Error(msg);
                _log.Fatal("The export cannot continue.  Exiting...");
                throw new ApplicationException(msg);
            }
            catch (Exception ex)
            {
                _log.Error("Error while exporting shapefile", ex);
            }
            return false;
        }
Exemplo n.º 5
0
 /// <summary>
 /// Returns the BoundingBox of the dataset.
 /// </summary>
 /// <returns>BoundingBox</returns>
 public override BoundingBox GetExtents()
 {
     var envelope = new Envelope();
     foreach (var feature in _features)
         envelope.ExpandToInclude(feature.Geometry.EnvelopeInternal);
     return envelope;
 }
Exemplo n.º 6
0
        public override void Start()
        {
            IPoint interiorPoint = Factory.CreatePoint(new Coordinate(130, 150));
            IPoint exteriorPoint = Factory.CreatePoint(new Coordinate(650, 1500));
            ILineString aLine = Factory.CreateLineString(new ICoordinate[] { new Coordinate(23, 32.2), new Coordinate(10, 222) });
            ILineString anotherLine = Factory.CreateLineString(new ICoordinate[] { new Coordinate(0, 1), new Coordinate(30, 30) });
            ILineString intersectLine = Factory.CreateLineString(new ICoordinate[] { new Coordinate(0, 1), new Coordinate(300, 300) });            

            try
            {               
                Write(polygon.Area);
                Write(polygon.Boundary);
                Write(polygon.BoundaryDimension);
                Write(polygon.Centroid);
                Write(polygon.Coordinate);
                Write(polygon.Coordinates.Length);
                Write(polygon.Dimension);
                Write(polygon.Envelope);
                Write(polygon.EnvelopeInternal);
                Write(polygon.ExteriorRing);
                Write(polygon.InteriorPoint);
                Write(polygon.InteriorRings.Length);
                Write(polygon.IsEmpty);
                Write(polygon.IsSimple);
                Write(polygon.IsValid);
                Write(polygon.Length);
                Write(polygon.NumInteriorRings);
                Write(polygon.NumPoints);                
                if (polygon.UserData != null)
                    Write(polygon.UserData);
                else Write("UserData null");
             
                Write(polygon.Buffer(10));
                Write(polygon.Buffer(10, BufferStyle.CapButt));                
                Write(polygon.Buffer(10, BufferStyle.CapSquare));
                Write(polygon.Buffer(10, 20));
                Write(polygon.Buffer(10, 20, BufferStyle.CapButt));                
                Write(polygon.Buffer(10, 20, BufferStyle.CapSquare));
                Write(polygon.Contains(interiorPoint));
                Write(polygon.Contains(exteriorPoint));
                Write(polygon.Contains(aLine));
                Write(polygon.Contains(anotherLine));
                Write(polygon.Crosses(interiorPoint));
                Write(polygon.Crosses(exteriorPoint));
                Write(polygon.Crosses(aLine));
                Write(polygon.Crosses(anotherLine));
                Write(polygon.Difference(interiorPoint));
                Write(polygon.Difference(exteriorPoint));
                Write(polygon.Difference(aLine));
                Write(polygon.Difference(anotherLine));
                Write(polygon.Disjoint(interiorPoint));
                Write(polygon.Disjoint(exteriorPoint));
                Write(polygon.Disjoint(aLine));
                Write(polygon.Disjoint(anotherLine));
                Write(polygon.Distance(interiorPoint));
                Write(polygon.Distance(exteriorPoint));
                Write(polygon.Distance(aLine));
                Write(polygon.Distance(anotherLine));
                Write(polygon.Intersection(interiorPoint));
                Write(polygon.Intersection(exteriorPoint));
                Write(polygon.Intersection(aLine));
                Write(polygon.Intersection(anotherLine));
                Write(polygon.Intersects(interiorPoint));
                Write(polygon.Intersects(exteriorPoint));
                Write(polygon.Intersects(aLine));
                Write(polygon.Intersects(anotherLine));
                Write(polygon.IsWithinDistance(interiorPoint, 300));
                Write(polygon.IsWithinDistance(exteriorPoint, 300));
                Write(polygon.IsWithinDistance(aLine, 300));
                Write(polygon.IsWithinDistance(anotherLine, 300));
                Write(polygon.Overlaps(interiorPoint));
                Write(polygon.Overlaps(exteriorPoint));
                Write(polygon.Overlaps(aLine));
                Write(polygon.Overlaps(anotherLine));
                Write(polygon.Relate(interiorPoint));
                Write(polygon.Relate(exteriorPoint));
                Write(polygon.Relate(aLine));
                Write(polygon.Relate(anotherLine));
                Write(polygon.SymmetricDifference(interiorPoint));
                Write(polygon.SymmetricDifference(exteriorPoint));
                Write(polygon.SymmetricDifference(aLine));
                Write(polygon.SymmetricDifference(anotherLine));
                Write(polygon.ToString());
                Write(polygon.AsText());
                Write(polygon.Touches(interiorPoint));
                Write(polygon.Touches(exteriorPoint));
                Write(polygon.Touches(aLine));
                Write(polygon.Touches(anotherLine));
                Write(polygon.Union(interiorPoint));
                Write(polygon.Union(exteriorPoint));
                Write(polygon.Union(aLine));
                Write(polygon.Union(anotherLine));

                string aPoly = "POLYGON ((20 20, 100 20, 100 100, 20 100, 20 20))";
                string anotherPoly = "POLYGON ((20 20, 100 20, 100 100, 20 100, 20 20), (50 50, 60 50, 60 60, 50 60, 50 50))";                
                IGeometry geom1 = Reader.Read(aPoly);
                Write(geom1.AsText());                                
                IGeometry geom2 = Reader.Read(anotherPoly);
                Write(geom2.AsText());

                // ExpandToInclude tests
                Envelope envelope = new Envelope(0, 0, 0, 0);
                envelope.ExpandToInclude(geom1.EnvelopeInternal);
                envelope.ExpandToInclude(geom2.EnvelopeInternal);
                Write(envelope.ToString());

                // The polygon is not correctly ordered! Calling normalize we fix the problem...
                polygon.Normalize();

                byte[] bytes = polygon.AsBinary();
                IGeometry test1 = new WKBReader().Read(bytes);
                Write(test1.ToString());

                bytes = new GDBWriter().Write(polygon);
                test1 = new GDBReader().Read(bytes);
                Write(test1.ToString());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }        
Exemplo n.º 7
0
 /// <summary>
 /// 
 /// </summary>
 /// <returns></returns>
 protected override IEnvelope ComputeEnvelopeInternal()
 {
     IEnvelope envelope = new Envelope();
     for (int i = 0; i < geometries.Length; i++) 
         envelope.ExpandToInclude(geometries[i].EnvelopeInternal);
     return envelope;
 }
Exemplo n.º 8
0
        /// <summary>
        /// Gets the extents of the map based on the extents of all the layers in the layers collection
        /// </summary>
        /// <returns>Full map extents</returns>
        public virtual IEnvelope GetExtents()
        {
            if (Layers == null || Layers.Count == 0)
            {
                return null;
            }

            IEnvelope envelope = new Envelope();
            for (int i = 0; i < Layers.Count; i++)
            {
                if (Layers[i].IsVisible)
                {
                    if (Layers[i].Envelope != null && !Layers[i].Envelope.IsNull)
                    {
                        envelope.ExpandToInclude(Layers[i].Envelope);
                    }
                }
            }

            return envelope;
        }
Exemplo n.º 9
0
 /// <summary>
 /// Returns the BoundingBox of the dataset.
 /// </summary>
 /// <returns>BoundingBox</returns>
 public IEnvelope GetExtents()
 {            
     IEnvelope envelope = new Envelope();
     foreach (IFeature feature in features)
         envelope.ExpandToInclude(feature.Geometry.EnvelopeInternal);
     return envelope;
 }
Exemplo n.º 10
0
	    /// <summary>
        /// Boundingbox of dataset
        /// </summary>
        /// <returns>boundingbox</returns>
        public virtual IEnvelope GetExtents()
        {
            IEnvelope envelope = new Envelope();

            for (int i = 0; i < Geometries.Count; i++)
            {
                if (!Geometries[i].IsEmpty)
                {
                    envelope.ExpandToInclude(Geometries[i].EnvelopeInternal);
                }
            }
	        
            return envelope;
        }
Exemplo n.º 11
0
        /// <summary>
        /// Computes the full extents of the data source as a 
        /// <see cref="IEnvelope"/>.
        /// </summary>
        /// <returns>
        /// An Envelope instance which minimally bounds all the features
        /// available in this data source.
        /// </returns>
        public IEnvelope GetExtents()
        {
            IEnvelope envelope = new Envelope();

            foreach (DataRowView row in Table.DefaultView)
            {
                ICoordinate coordinate = new Coordinate((double) row[XColumn], (double) row[YColumn]);

                if (!envelope.Contains(coordinate))
                {
                    envelope.ExpandToInclude(coordinate);
                }
            }

            return envelope;
        }
Exemplo n.º 12
0
        public virtual IEnvelope GetExtents()
        {
            IEnvelope envelope = new Envelope();

            if (Features == null) 
                return envelope;

            foreach (IFeature feature in Features)
            {
                if(feature.Geometry == null)
                {
                    continue;
                }

                // HACK: probably we should not use EnvelopeInternal here but Envelope

                if (envelope.IsNull)
                {
                    envelope = (IEnvelope)feature.Geometry.EnvelopeInternal.Clone();
                }

                envelope.ExpandToInclude(feature.Geometry.EnvelopeInternal);
            }

            return envelope;
        }