public void TestTwoOpenClose()
        {
            ///Simulates two threads using the same provider at the same time..
            var provider = new ShapeFile(TestDataPath, false, true);

            provider.Open();
            provider.Open();
            provider.GetGeometriesInView(GetRandomEnvelope());
            provider.Close();
            provider.GetGeometriesInView(GetRandomEnvelope());
            provider.Close();
        }
        /// <summary>
        /// Open a TileIndex shapefile
        ///
        /// A tileindex is a shapefile that ties together several datasets into a single layer. Therefore, you don’t need to create separate layers for each piece of imagery or each county’s road data; make a tileindex and let SharpMap piece the mosaic together on the fly.
        /// Making a tileindex is easy using gdaltindex for GDAL data sources (rasters). You just run the tool, specifying the index file to create and the list of data sources to add to the index.
        ///
        /// For example, to make a mosaic of several TIFFs:
        ///
        /// gdaltindex imagery.shp imagery/*.tif

        /// See: http://mapserver.org/optimization/tileindex.html
        /// </summary>
        /// <param name="layerName">Name of the layer</param>
        /// <param name="fileName">Path to the ShapeFile containing tile-indexes</param>
        /// <param name="fieldName">FieldName in the shapefile storing full or relative path-names to the datasets</param>
        public GdalTileIndexRasterLayer(string layerName, string fileName, string fieldName) : base(layerName)
        {
            _fileName  = fileName;
            _shapeFile = new ShapeFile(fileName, true);
            _shapeFile.Open();
            _extents = _shapeFile.GetExtents();
            _shapeFile.Close();
            _fieldName = fieldName;
        }
Exemple #3
0
        /// <summary>
        /// Open a TileIndex shapefile
        ///
        /// A tileindex is a shapefile that ties together several datasets into a single layer. Therefore, you don’t need to create separate layers for each piece of imagery or each county’s road data; make a tileindex and let SharpMap piece the mosaic together on the fly.
        /// Making a tileindex is easy using gdaltindex for GDAL data sources (rasters). You just run the tool, specifying the index file to create and the list of data sources to add to the index.
        ///
        /// For example, to make a mosaic of several TIFFs:
        ///
        /// gdaltindex imagery.shp imagery/*.tif

        /// See: http://mapserver.org/optimization/tileindex.html
        /// </summary>
        /// <param name="layerName">Name of the layer</param>
        /// <param name="fileName">Path to the ShapeFile containing tile-indexes</param>
        /// <param name="fieldName">FieldName in the shapefile storing full or relative path-names to the datasets</param>
        public GdalTileIndexRasterLayer(string layerName, string fileName, string fieldName) : base(layerName)
        {
            _fileName  = fileName;
            _shapeFile = new ShapeFile(fileName, true);
            _shapeFile.Open();
            _extents = _shapeFile.GetExtents();
            _shapeFile.Close();
            _fieldName    = fieldName;
            _openDatasets = new Dictionary <string, CacheHolder>();
        }
        public void TestTwoThreadsUsingDifferentProviders()
        {
            var provider1 = new ShapeFile(TestDataPath, false, true);
            var provider2 = new ShapeFile(TestDataPath, false, true);

            provider1.Open();
            provider2.Open();
            provider1.GetGeometriesInView(GetRandomEnvelope());
            provider1.Close();
            provider2.GetGeometriesInView(GetRandomEnvelope());
            provider2.Close();
        }
        /// <summary>
        /// This method returns a FeatureDataTable containing all the rows from the shapefile that intersect the testGeometry.
        /// The ShapeFile.ExecuteIntersectionQuery method only tests bounding boxes so we use the FilterDelegate property to add a true
        /// intersection test using NetTopologySuite
        /// </summary>
        /// <param name="pathToShapefile">The path to the shapefile</param>
        /// <param name="testGeometry">The geometry that we want to test against</param>
        /// <returns></returns>
        public FeatureDataTable GetIntersectingFeaturesUsingFilterDelegate(string pathToShapefile, SMGeometry testGeometry)
        {
            //create a new shapefile provider
            using (ShapeFile shapefile = new ShapeFile(pathToShapefile))
            {
                //create an nts GeometryFactory
                GeometryFactory geometryFactory = new GeometryFactory();

                //convert the testGeometry into the equivalent NTS geometry
                GeoAPI.Geometries.IGeometry testGeometryAsNtsGeom = GeometryConverter.ToNTSGeometry(testGeometry, geometryFactory);

                SMGeometry check = GeometryConverter.ToSharpMapGeometry(testGeometryAsNtsGeom);
                if (!check.Equals(testGeometry))
                {
                    throw new ApplicationException("conversion error");
                }

                //set the shapefile providers' FilterDelegate property to a new anonymous method
                //this delegate method will be called for each potential row
                shapefile.FilterDelegate = delegate(FeatureDataRow featureDataRow)
                {
                    //get the geometry from the featureDataRow
                    SMGeometry rowGeometry = featureDataRow.Geometry;
                    //convert it to the equivalent NTS geometry
                    GeoAPI.Geometries.IGeometry compareGeometryAsNtsGeometry =
                        GeometryConverter.ToNTSGeometry(rowGeometry, geometryFactory);
                    //do the test. Note that the testGeometryAsNtsGeometry is available here because it is
                    //declared in the same scope as the anonymous method.
                    bool intersects =
                        testGeometryAsNtsGeom.Intersects(compareGeometryAsNtsGeometry);
                    //return the result
                    return(intersects);
                };


                //create a new FeatureDataSet
                FeatureDataSet featureDataSet = new FeatureDataSet();
                //open the shapefile
                shapefile.Open();
                //call ExecuteIntersectionQuery. The FilterDelegate will be used to limit the result set
                shapefile.ExecuteIntersectionQuery(testGeometry, featureDataSet);
                //close the shapefile
                shapefile.Close();
                //return the populated FeatureDataTable
                return(featureDataSet.Tables[0]);
            }
        }
        public override void Render(IGraphics g, Map map)
        {
            try
            {
                _shapeFile.Open();
                var ds = new FeatureDataSet();
                _shapeFile.ExecuteIntersectionQuery(map.Envelope, ds);

                var dt = ds.Tables[0];
                foreach (FeatureDataRow fdr in dt.Rows)
                {
                    if (fdr.Geometry.EnvelopeInternal.Intersects(map.Envelope))
                    {
                        var file = fdr[_fieldName] as string;
                        if (!Path.IsPathRooted(file))
                        {
                            file = Path.Combine(Path.GetDirectoryName(_fileName), file);
                        }

                        if (_logger.IsDebugEnabled)
                        {
                            _logger.Debug("Drawing " + file);
                        }

                        OpenDataset(file);

                        base.Render(g, map);
                        _envelope = null;
                        if (_gdalDataset != null)
                        {
                            _gdalDataset.Dispose();
                            _gdalDataset = null;
                        }
                    }
                }
            }
            catch (Exception)
            {
                _shapeFile.Close();
            }
        }
        public void ShowFeature(Predicate <System.Data.DataRow> p = null)
        {
            List <SharpMap.Geometries.Geometry> geometries = new List <SharpMap.Geometries.Geometry>();

            m_shapeFileData.Open();
            for (uint i = 0; i < m_shapeFileData.GetFeatureCount(); ++i)
            {
                SharpMap.Data.FeatureDataRow featureDataRow = m_shapeFileData.GetFeature(i);
                if (p == null || p(featureDataRow))
                {
                    geometries.Add(m_shapeFileData.GetGeometryByID(i));
                }
            }
            m_shapeFileData.Close();

            m_shapeLayer.DataSource = new GeometryFeatureProvider(geometries);
            if (myMap.Layers.IndexOf(m_shapeLayer) == -1)
            {
                myMap.Layers.Add(m_shapeLayer);
            }

            //myMap.ZoomToExtents();
        }
Exemple #8
0
        public override void Render(Graphics g, IMapViewPort map)
        {
            try
            {
                _shapeFile.Open();
                var ds = new FeatureDataSet();
                _shapeFile.ExecuteIntersectionQuery(map.Envelope, ds);

                var dt = ds.Tables[0];
                foreach (FeatureDataRow fdr in dt.Rows)
                {
                    if (fdr.Geometry.EnvelopeInternal.Intersects(map.Envelope))
                    {
                        var file = fdr[_fieldName] as string;
                        if (!Path.IsPathRooted(file))
                        {
                            file = Path.Combine(Path.GetDirectoryName(_fileName), file);
                        }

                        if (file == null)
                        {
                            continue;
                        }

                        if (_logger.IsDebugEnabled)
                        {
                            _logger.Debug("Drawing " + file);
                        }

                        if (!_openDatasets.ContainsKey(file))
                        {
                            OpenDataset(file);
                            _openDatasets.Add(file, new CacheHolder()
                            {
                                Bands       = Bands,
                                Dataset     = _gdalDataset,
                                Envelope    = _envelope,
                                HistoBounds = HistoBounds,
                                ImageSize   = _imageSize,
                                Projection  = Projection
                            });
                        }
                        else
                        {
                            CacheHolder hld = _openDatasets[file];
                            Bands        = hld.Bands;
                            _gdalDataset = hld.Dataset;
                            _envelope    = hld.Envelope;
                            HistoBounds  = hld.HistoBounds;
                            _imageSize   = hld.ImageSize;
                            Projection   = hld.Projection;
                        }

                        base.Render(g, map);
                        _envelope    = null;
                        _gdalDataset = null;
                    }
                }
            }
            catch (Exception)
            {
                _shapeFile.Close();
            }
        }
Exemple #9
0
        public JsonResult GetData(float w, float n, float e, float s, int z)
        {
            string format = String.Format("~/App_Data/berlin/{0}", "osmbuildings.shp");
            string path   = this.HttpContext.Server.MapPath(format);

            if (!System.IO.File.Exists(path))
            {
                throw new FileNotFoundException("file not found", path);
            }

            Point start = this.GeoToPixel(n, w, z);
            var   meta  = new { n, w, s, e, x = start.X, y = start.Y, z };

            Envelope bbox = new Envelope();

            bbox.ExpandToInclude(new Coordinate(n, w));
            bbox.ExpandToInclude(new Coordinate(s, e));

            FeatureDataSet ds = new FeatureDataSet();

            using (ShapeFile provider = new ShapeFile(path))
            {
                provider.DoTrueIntersectionQuery = true;
                provider.Open();
                provider.ExecuteIntersectionQuery(bbox, ds);
                provider.Close();
            }

            int              zz    = MaxZoom - z;
            List <object>    data  = new List <object>();
            FeatureDataTable table = ds.Tables[0];

            foreach (FeatureDataRow row in table)
            {
                int c = (short)(row["height"]);
                if (c == 0)
                {
                    c = 5; // default value for "null" (zero) heights
                }
                int h = c * ScaleZ >> zz;
                if (h <= 1)
                {
                    h = 1;
                }

                IGeometry    geometry = row.Geometry;
                Coordinate[] coords   = geometry.Coordinates;
                int          total    = coords.Length;
                double[]     values   = new double[total * 2];
                int          i        = 0;
                foreach (Coordinate curr in coords)
                {
                    Point p = this.GeoToPixel(curr.X, curr.Y, z);
                    values[i++] = p.X - start.X;
                    values[i++] = p.Y - start.Y;
                }
                data.Add(new object[] { h, values });
            }

            return(this.Json(new { meta, data }, JsonRequestBehavior.AllowGet));
        }
Exemple #10
0
        public static int ReadShapefile(string file, out List <Geometry> features, out List <double> intervals, out List <int> types, out List <double> heights)
        {
            int flag = 0;

            features  = new List <Geometry>();
            types     = new List <int>();
            heights   = new List <double>();
            intervals = new List <double>();
            ShapeFile shp = null;

            try
            {
                shp = new ShapeFile(file);
            }
            catch (Exception e)
            {
                MainConsole.Instance.Output("Shapefile open failed!");
                throw new Exception("ShapeFile not exists! " + e.Message + e.StackTrace);
            }
            shp.Open();
            switch (shp.ShapeType)
            {
            case ShapeType.Point:
                flag = 0;
                break;

            case ShapeType.PolyLine:
                flag = 1;
                break;

            case ShapeType.Polygon:
                flag = 2;
                break;

            default:
                flag = -1;
                return(flag);
            }

            FeatureDataSet ds   = new FeatureDataSet();
            BoundingBox    bbox = shp.GetExtents();

            shp.ExecuteIntersectionQuery(bbox, ds);
            FeatureDataTable table = ds.Tables[0] as FeatureDataTable;

            try
            {
                foreach (FeatureDataRow row in table.Rows)
                {
                    features.Add(row.Geometry);
                    heights.Add(Convert.ToDouble(row["Height"]));
                    types.Add(Convert.ToInt32(row["Type"]));
                    if (flag != 0)
                    {
                        intervals.Add(Convert.ToDouble(row["Interval"]));
                    }
                }
            }
            catch (Exception e)
            {
                throw new Exception("Attribute in shapefile incorrect with " + e.Message + e.StackTrace);
            }

            shp.Close();
            return(flag);
        }