Esempio n. 1
0
        /// <summary>
        /// Writes a <b>Geometry</b> to the file.
        /// </summary>
        /// <param name="geometry">The <b>Geometry</b> to write to the file.</param>
        /// <exception cref="ArgumentNullException">The geometry is a null reference (Nothing in Visual Basic).</exception>
        public void WriteGeometry(Geometry geometry)
        {
            if (geometry == null)
            {
                throw new ArgumentNullException("geometry");
            }

////			if (typeof(geometry ==  GeometryCollection)
////			{
////				this.WriteGeometryCollection((GeometryCollection)geometry);
////			}

            // Make sure we have the same shape type - if not the file is invalid
            if (_type == ShapeType.Undefined)
            {
                _type = Shapefile.GetShapeType(geometry);
            }
            else if (_type != Shapefile.GetShapeType(geometry))
            {
                throw new ArgumentException(String.Format(System.Globalization.CultureInfo.InvariantCulture, "An invalid shapet type has been encountered - expected '{0}' but got '{1}.", _type, Shapefile.GetShapeType(geometry)), "geometry");
            }

            // Get handler
            ShapeHandler handler = Shapefile.GetShapeHandler(_type);

            // Get the length of the geometry in bytes
            int length = handler.GetLength(geometry);

            // Write record number
            _shpWriter.WriteIntBE(_count + 1);

            // Write record length
            _shpWriter.WriteIntBE(length);

            // Write geometry
            handler.Write(geometry, _shpWriter, _factory);

            // Increase bounds to include geometry if needed
            _bounds.expandToInclude(geometry.getEnvelopeInternal());

            // Every time we write a geometry we need to increment the count
            _count++;

            // Write index information
            _shxWriter.WriteIntBE(_shpLength);
            _shxWriter.WriteIntBE(length);

            // Every time we write a geometry we need to increment the byte length
            _shpLength += HEADER_shpLength + length;
        }
Esempio n. 2
0
        public DataTable Query(Envelope extents)
        {
            DataTable table   = this.GetDataTable();
            ArrayList indexes = new ArrayList(_spatialIndex.query(extents).toArray());

            // Sort the results so we can go through the files sequentially
            indexes.Sort();
            ShapeHandler handler = null;

            switch (_type)
            {
            case ShapeType.Point:
                handler = new PointHandler();
                break;

            case ShapeType.Arc:
                handler = new MultiLineHandler();
                break;

            case ShapeType.Polygon:
                handler = new PolygonHandler();
                break;
            }

            using (BinaryReader dbfReader = new BinaryReader(File.OpenRead(Path.Combine(Path.GetDirectoryName(_path), Path.GetFileNameWithoutExtension(_path) + ".dbf"))))
                using (BigEndianBinaryReader shpReader = new BigEndianBinaryReader(File.OpenRead(_path)))
                {
                    foreach (ShapefileRecordPointer pointer in indexes)
                    {
                        ArrayList record = new ArrayList();

                        // Step 1: Get the geometry
                        // NOTE: We add 8 here to skip the content length and record numer - we
                        //		 already have that information in the pointer object.
                        shpReader.BaseStream.Position = pointer.GeometryOffset + 8;
                        record.Add(handler.Read(shpReader, _factory));

                        // Step 2: Get the attributes
                        dbfReader.BaseStream.Position = pointer.AttributesOffset;
                        record.AddRange(DbaseFileReader.ReadRecord(dbfReader, _dbfHeader));

                        table.Rows.Add(record.ToArray());
                    }
                }

            return(table);
        }
Esempio n. 3
0
        /// <summary>
        /// Reads the shapefile and returns a <b>GeometryCollection</b> representing all the records in the shapefile.
        /// </summary>
        /// <returns>A <b>GeometryCollection</b> representing every record in the shapefile.</returns>
        public GeometryCollection ReadAll()
        {
            java.util.ArrayList list    = new java.util.ArrayList();
            ShapeHandler        handler = Shapefile.GetShapeHandler(_mainHeader.ShapeType);

            if (handler == null)
            {
                throw new NotSupportedException("Unsupported shape type:" + _mainHeader.ShapeType);
            }

            foreach (Geometry geometry in this)
            {
                list.add(geometry);
            }

            Geometry[] geomArray = GeometryFactory.toGeometryArray(list);

            return(_geometryFactory.createGeometryCollection(geomArray));
        }
Esempio n. 4
0
			/// <summary>
			/// Initializes a new instance of the ShapefileEnumerator class.
			/// </summary>
			public ShapefileEnumerator(ShapefileReader shapefile)
			{
				
				_parent = shapefile;

				// create a file stream for each enumerator that is given out. This allows the same file
				// to have one or more enumerator. If we used the parents stream - than only one IEnumerator 
				// could be given out.
				FileStream stream = new FileStream(_parent._filename, System.IO.FileMode.Open, FileAccess.Read, FileShare.Read);
				_shpBinaryReader = new BigEndianBinaryReader(stream);
				
				// skip header - since parent has already read this.
				_shpBinaryReader.ReadBytes(100);
				ShapeType type = _parent._mainHeader.ShapeType;
				_handler = Shapefile.GetShapeHandler(type);
				if (_handler == null) 
				{
					throw new NotSupportedException("Unsuported shape type:" + type);
				}
			}
Esempio n. 5
0
            /// <summary>
            /// Initializes a new instance of the <see cref="ShapefileEnumerator">ShapefileEnumerator</see> class.
            /// </summary>
            public ShapefileEnumerator(ShapefileReader shapefile)
            {
                _parent = shapefile;

                // create a file stream for each enumerator that is given out. This allows the same file
                // to have one or more enumerator. If we used the parents stream only one IEnumerator
                // could be given out.
                _shpBinaryReader = new BigEndianBinaryReader(new FileStream(_parent._filename, System.IO.FileMode.Open, FileAccess.Read, FileShare.Read));

                // skip header - since parent has already read this.
                _shpBinaryReader.ReadBytes(100);
                ShapeType type = _parent._mainHeader.ShapeType;

                _handler = Shapefile.GetShapeHandler(type);

                if (_handler == null)
                {
                    throw new NotSupportedException("Unsuported shape type:" + type);
                }
            }
Esempio n. 6
0
        /// <summary>
        /// Reads the shapefile and returns a GeometryCollection representing all the records in the shapefile.
        /// </summary>
        /// <returns>GeometryCollection representing every record in the shapefile.</returns>
        public GeometryCollection ReadAll()
        {
            ArrayList    list    = new ArrayList();
            ShapeType    type    = _mainHeader.ShapeType;
            ShapeHandler handler = Shapefile.GetShapeHandler(type);

            if (handler == null)
            {
                throw new NotSupportedException("Unsupported shape type:" + type);
            }

            int i = 0;

            foreach (Geometry geometry in this)
            {
                list.Add(geometry);
                i++;
            }

            Geometry[] geomArray = GeometryFactory.ToGeometryArray(list);
            return(_geometryFactory.CreateGeometryCollection(geomArray));
            //return geometryCollection;
        }
Esempio n. 7
0
        /// <summary>
        /// Writes a shapefile to disk.
        /// </summary>
        /// <remarks>
        /// <para>Assumes the type given for the first geometry is the same for all subsequent geometries.
        /// For example, is, if the first Geometry is a Multi-polygon/ Polygon, the subsequent geometies are
        /// Muli-polygon/ polygon and not lines or points.</para>
        /// <para>The dbase file for the corresponding shapefile contains one column called row. It contains
        /// the row number.</para>
        /// </remarks>
        /// <param name="filename">The filename to write to (minus the .shp extension).</param>
        /// <param name="geometryCollection">The GeometryCollection to write.</param>
        /// <param name="geometryFactory">The geometry factory to use.</param>
        public static void Write(string filename, GeometryCollection geometryCollection, GeometryFactory geometryFactory)
        {
            System.IO.FileStream  shpStream       = new System.IO.FileStream(filename + ".shp", System.IO.FileMode.Create);
            System.IO.FileStream  shxStream       = new System.IO.FileStream(filename + ".shx", System.IO.FileMode.Create);
            BigEndianBinaryWriter shpBinaryWriter = new BigEndianBinaryWriter(shpStream);
            BigEndianBinaryWriter shxBinaryWriter = new BigEndianBinaryWriter(shxStream);

            // assumes
            ShapeHandler handler = Shapefile.GetShapeHandler(Shapefile.GetShapeType(geometryCollection[0]));

            Geometry body;
            int      numShapes = geometryCollection.GetNumGeometries();
            // calc the length of the shp file, so it can put in the header.
            int shpLength = 50;

            for (int i = 0; i < numShapes; i++)
            {
                body       = geometryCollection[i];
                shpLength += 4;                       // length of header in WORDS
                shpLength += handler.GetLength(body); // length of shape in WORDS
            }

            int shxLength = 50 + (4 * numShapes);


            // write the .shp header
            ShapefileHeader shpHeader = new ShapefileHeader();

            shpHeader.FileLength = shpLength;

            // get envelopse in external coordinates
            Envelope env    = geometryCollection.GetEnvelopeInternal();
            Envelope bounds = ShapeHandler.GetEnvelopeExternal(geometryFactory.PrecisionModel, env);

            shpHeader.Bounds = bounds;


            // assumes Geometry type of the first item will the same for all other items
            // in the collection.
            shpHeader.ShapeType = Shapefile.GetShapeType(geometryCollection[0]);
            shpHeader.Write(shpBinaryWriter);

            // write the .shx header
            ShapefileHeader shxHeader = new ShapefileHeader();

            shxHeader.FileLength = shxLength;
            shxHeader.Bounds     = shpHeader.Bounds;

            // assumes Geometry type of the first item will the same for all other items
            // in the collection.
            shxHeader.ShapeType = Shapefile.GetShapeType(geometryCollection[0]);
            shxHeader.Write(shxBinaryWriter);



            // write the individual records.
            int _pos = 50;             // header length in WORDS

            for (int i = 0; i < numShapes; i++)
            {
                body = geometryCollection[i];
                int recordLength = handler.GetLength(body);
                Debug.Assert(Shapefile.GetShapeType(body) != shpHeader.ShapeType, String.Format("Item {0} in the GeometryCollection is not the same Shapetype as Item 0.", i));
                shpBinaryWriter.WriteIntBE(i + 1);
                shpBinaryWriter.WriteIntBE(recordLength);


                shxBinaryWriter.WriteIntBE(_pos);
                shxBinaryWriter.WriteIntBE(recordLength);

                _pos += 4;                 // length of header in WORDS
                handler.Write(body, shpBinaryWriter, geometryFactory);
                _pos += recordLength;      // length of shape in WORDS
            }

            shxBinaryWriter.Flush();
            shxBinaryWriter.Close();
            shpBinaryWriter.Flush();
            shpBinaryWriter.Close();

            Debug.Assert(_pos != shpLength, "File length in header and actual file length do not match.");
            //stream.Close();
            //Trace.WriteLineIf(Shapefile.TraceSwitch.Enabled,"File length pos:"+_pos*2+" bytes");
            //Trace.WriteLineIf(Shapefile.TraceSwitch.Enabled,"File length pos "+_pos+ " words");

            WriteDummyDbf(filename + ".dbf", numShapes);
        }
Esempio n. 8
0
        /// <summary>
        /// Writes a <b>Geometry</b> to the given binary wirter.
        /// </summary>
        /// <param name="geometry">The geometry to write.</param>
        /// <param name="writer">The file stream to write to.</param>
        /// <param name="factory">The geometry factory to use.</param>
        public override void Write(Geometry geometry, BinaryWriter writer, GeometryFactory factory)
        {
            /* This makes exporting really slow for complex polygons
             * if (geometry.isValid() == false)
             * {
             *      Trace.WriteLine("Invalid polygon being written.");
             * }*/

            GeometryCollection multi;

            if (geometry is GeometryCollection)
            {
                multi = (GeometryCollection)geometry;
            }
            else
            {
                GeometryFactory gf = new GeometryFactory(geometry.getPrecisionModel());
                //multi = new MultiPolygon(new Polygon[]{(Polygon) geometry}, geometry.PrecisionModel, geometry.GetSRID());
                multi = gf.createMultiPolygon(new Polygon[] { (Polygon)geometry });
            }
            //file.setLittleEndianMode(true);
            writer.Write(int.Parse(Enum.Format(typeof(ShapeType), this.ShapeType, "d")));

            Envelope box    = multi.getEnvelopeInternal();
            Envelope bounds = ShapeHandler.GetEnvelopeExternal(factory.getPrecisionModel(), box);

            writer.Write(bounds.getMinX());
            writer.Write(bounds.getMinY());
            writer.Write(bounds.getMaxX());
            writer.Write(bounds.getMaxY());

            int numParts  = GetNumParts(multi);
            int numPoints = multi.getNumPoints();

            writer.Write(numParts);
            writer.Write(numPoints);


            // write the offsets to the points
            int offset = 0;

            for (int part = 0; part < multi.getNumGeometries(); part++)
            {
                // offset to the shell points
                Polygon polygon = (Polygon)multi.getGeometryN(part);
                writer.Write(offset);
                offset = offset + polygon.getExteriorRing().getNumPoints();
                // offstes to the holes

                for (int i = 0; i < polygon.getNumInteriorRing(); i++)
                {
                    writer.Write(offset);
                    offset = offset + polygon.getInteriorRingN(i).getNumPoints();
                }
            }


            // write the points
            for (int part = 0; part < multi.getNumGeometries(); part++)
            {
                Polygon      poly   = (Polygon)multi.getGeometryN(part);
                Coordinate[] coords = poly.getExteriorRing().getCoordinates();
                if (com.vividsolutions.jts.algorithm.RobustCGAlgorithms.isCCW(coords) == true)
                {
                    Array.Reverse(coords);
                    //coords = coords.ReverseCoordinateOrder();
                }
                WriteCoords(coords, writer, factory);

                for (int i = 0; i < poly.getNumInteriorRing(); i++)
                {
                    Coordinate[] coords2 = poly.getInteriorRingN(i).getCoordinates();
                    if (com.vividsolutions.jts.algorithm.RobustCGAlgorithms.isCCW(coords2) == false)
                    {
                        Array.Reverse(coords2);
                        //coords = coords.ReverseCoordinateOrder();
                    }
                    WriteCoords(coords2, writer, factory);
                }
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Writes a Geometry to the given binary wirter.
        /// </summary>
        /// <param name="geometry">The geometry to write.</param>
        /// <param name="file">The file stream to write to.</param>
        /// <param name="geometryFactory">The geometry factory to use.</param>
        public override void Write(Geometry geometry, System.IO.BinaryWriter file, GeometryFactory geometryFactory)
        {
            if (geometry.IsValid() == false)
            {
                Trace.WriteLine("Invalid polygon being written.");
            }
            GeometryCollection multi;

            if (geometry is GeometryCollection)
            {
                multi = (GeometryCollection)geometry;
            }
            else
            {
                GeometryFactory gf = new GeometryFactory(geometry.PrecisionModel, geometry.GetSRID());
                //multi = new MultiPolygon(new Polygon[]{(Polygon) geometry}, geometry.PrecisionModel, geometry.GetSRID());
                multi = gf.CreateMultiPolygon(new Polygon[] { (Polygon)geometry });
            }
            //file.setLittleEndianMode(true);
            file.Write(int.Parse(Enum.Format(typeof(ShapeType), this.ShapeType, "d")));

            Envelope box    = multi.GetEnvelopeInternal();
            Envelope bounds = ShapeHandler.GetEnvelopeExternal(geometryFactory.PrecisionModel, box);

            file.Write(bounds.MinX);
            file.Write(bounds.MinY);
            file.Write(bounds.MaxX);
            file.Write(bounds.MaxY);

            int numParts  = GetNumParts(multi);
            int numPoints = multi.GetNumPoints();

            file.Write(numParts);
            file.Write(numPoints);


            // write the offsets to the points
            int offset = 0;

            for (int part = 0; part < multi.Count; part++)
            {
                // offset to the shell points
                Polygon polygon = (Polygon)multi[part];
                file.Write(offset);
                offset = offset + polygon.Shell.GetNumPoints();
                // offstes to the holes
                foreach (LinearRing ring in polygon.Holes)
                {
                    file.Write(offset);
                    offset = offset + ring.GetNumPoints();
                }
            }


            // write the points
            for (int part = 0; part < multi.Count; part++)
            {
                Polygon     poly   = (Polygon)multi[part];
                Coordinates points = poly.Shell.GetCoordinates();
                if (_cga.IsCCW(points) == true)
                {
                    //points = points.ReverseCoordinateOrder();
                }
                WriteCoords(points, file, geometryFactory);
                foreach (LinearRing ring in poly.Holes)
                {
                    Coordinates points2 = ring.GetCoordinates();
                    if (_cga.IsCCW(points2) == false)
                    {
                        //points2 = points2.ReverseCoordinateOrder();
                    }
                    WriteCoords(points2, file, geometryFactory);
                }
            }
        }