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

            provider.Open();
            provider.Open();
            provider.GetGeometriesInView(GetRandomEnvelope());
            provider.Close();
            provider.GetGeometriesInView(GetRandomEnvelope());
            provider.Close();
        }
示例#2
0
        public FeatureDataTable GetFeatureTableFromShapefile(string shapeFilePath)
        {
            GeoAPI.GeometryServiceProvider.Instance = new NetTopologySuite.NtsGeometryServices();
            int cd;

            if (!int.TryParse(_enconding.Text, out cd))
            {
                _status.Text = "Bad code page";
            }

            ShapeFile sf = new ShapeFile(shapeFilePath);

            sf.Encoding = Encoding.GetEncoding(int.Parse(_enconding.Text));
            sf.Open();

            this.shapeSRID    = sf.SRID;
            this.shapeExtends = sf.GetExtents();

            _sRID.Text = this.shapeSRID.ToString();

            FeatureDataSet ds = new FeatureDataSet();

            sf.ExecuteIntersectionQuery(this.shapeExtends, ds);
            //ds.Tables[0].Columns.Remove("Oid");
            return(ds.Tables[0]);
        }
        public FeatureDataTable GetFeatureTableFromShapefile(string shapeFilePath)
        {
            GeoAPI.GeometryServiceProvider.Instance = new NetTopologySuite.NtsGeometryServices();
            int cd;

            if (!int.TryParse(_enconding.Text, out cd))
            {
                _status.Text = "Bad code page";
            }

            ShapeFile sf = new ShapeFile(shapeFilePath);

            sf.Encoding = Encoding.GetEncoding(int.Parse(_enconding.Text));
            sf.Open();

            FeatureDataSet ds = new FeatureDataSet();

            importExtent = sf.GetExtents();
            Debug.WriteLine("Loading " + sf.GetFeatureCount() + " features from shapefile...");

            //sf.ExecuteIntersectionQuery(importExtent, ds);
            ExecuteRobustIntersectionQuery(sf, importExtent, ds);
            //ds.Tables[0].Columns.Remove("Oid");
            return(ds.Tables[0]);
        }
示例#4
0
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            MogreApp.setLocations(prj.getMogreLocations());
            SetupMogre();
            Mogre.SceneManager sm = app.SceneManager;

            foreach (MogreGis.FilterGraph graph in prj.getFilterGraphs())
            {
                foreach (osgGISProjects.Source source in prj.getSources())
                {
                    if (Path.GetExtension(source.getURI()) != ".shp")
                    {
                        throw new NotImplementedException();
                    }

                    if (source.getName() == graph.getName())
                    {
                        MogreGis.FilterEnv   env         = null;
                        MogreGis.FeatureList featureList = null;

                        FeatureDataSet ds = new FeatureDataSet();
                        source.DataSource.Open();
                        source.DataSource.ExecuteIntersectionQuery(source.DataSource.GetExtents(), ds);
                        source.DataSource.Close();
                        FeatureDataTable features = (FeatureDataTable)ds.Tables[0];
                        featureList = MogreGis.Feature.DataTableToList(features);

                        foreach (Script script in prj.getScripts())
                        {
                            Registry.instance().GetEngine("Python").run(script);
                        }

                        foreach (Feature feature in featureList)
                        {
                            SharpMapSpatialReferenceFactory smsrf = new SharpMapSpatialReferenceFactory();
                            ShapeFile shp = new ShapeFile(source.getURI());
                            shp.Open();
                            SharpMapSpatialReference sr;
                            sr = (SharpMapSpatialReference)smsrf.createSRSfromWKT(shp.CoordinateSystem.WKT);
                            feature.getGeometry().SpatialReference = sr;
                        }

                        env = new MogreGis.FilterEnv(sm, "env" + graph.getName());
                        env.setScriptEngine(Registry.instance().GetEngine("Python"));
                        foreach (MogreGis.Filter filter in graph.getFilters())
                        {
                            if (filter is MogreGis.FragmentFilter)
                            {
                                (filter as MogreGis.FragmentFilter).process(featureList, env);
                            }
                            if (filter is MogreGis.FeatureFilter)
                            {
                                featureList = (filter as MogreGis.FeatureFilter).process(featureList, env);
                            }
                        }
                    }
                }
            }
            app.getRoot().StartRendering();
        }
示例#5
0
        private void LoadBoundary(String FileName, bool Counties)
        {
            CoordinateTransformationFactory ctfac = new CoordinateTransformationFactory();
            ICoordinateSystem         SourceProj  = ProjNet.Converters.WellKnownText.CoordinateSystemWktReader.Parse(File.ReadAllText(FileName.ToLower().Replace(".shp", ".prj"))) as ICoordinateSystem;
            ICoordinateSystem         DestProj    = GeographicCoordinateSystem.WGS84;
            ICoordinateTransformation XF          = ctfac.CreateFromCoordinateSystems(SourceProj, DestProj);

            using (ShapeFile sF = ShapeFile.Open(FileName))
                foreach (Shape shp in sF.GetAllShapes())
                {
                    Sim_Boundary NewBoundary = new Sim_Boundary(shp, XF, this);
                    if (Counties)
                    {
                        Boundaries.Add(NewBoundary);
                    }
                    else if (NewBoundary.Contains(Boundaries[0]))
                    {
                        NewBoundary.Name = "STATE";
                        Boundaries.Add(NewBoundary);
                    }
                }

            if (Counties)
            {
                Centroid_X /= CoordinateCount;
                Centroid_Y /= CoordinateCount;
            }
        }
示例#6
0
        /************************************************************************************************************************/
        /*****PRIVATE METHODS****************************************************************************************************/
        /************************************************************************************************************************/

        private void UpdateSpeciesGeographyForTaxonomicClass(String taxonomicClass)
        {
            var shapeFileInfo = GetShapeFileInfo(taxonomicClass);

            using (var shapeFile = new ShapeFile(shapeFileInfo.FullName))
            {
                shapeFile.Open();
                const double minLatitude  = -3.5;
                const double maxLatitude  = 0.0;
                const double maxLongitude = 180.0;
                const double minLongitude = -180.0;
                const double interval     = 0.5;

                for (var latitude = minLatitude; latitude < maxLatitude; Math.Round(latitude = latitude + interval, 1))
                {
                    for (var longitude = minLongitude; longitude < maxLongitude; Math.Round(longitude = longitude + interval, 1))
                    {
                        var point = GeographyPoint.Create(latitude, longitude);
AttemptUpdate:

                        try
                        {
                            UpdateSpeciesGeographyTableIfNeeded(shapeFile, point, taxonomicClass);
                        }
                        catch (Exception e)
                        {
                            Trace.TraceError(e.Message, e);
                            goto AttemptUpdate;
                        }
                    }
                }
            }
        }
        /// <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;
        }
示例#8
0
        public VectorLayer getPolygonPoints(PointF points, VectorLayer veclayer)
        {
            //VectorLayer veclayer = (VectorLayer)m_viewBox.Map.GetLayerByName("province");
            SharpMap.Layers.VectorLayer laySelected = new SharpMap.Layers.VectorLayer("Selection");;
            CustomTheme myTheme = new CustomTheme(FeatureColoured);
            ShapeFile   vecshp  = (ShapeFile)veclayer.DataSource;
            ShapeFile   shp     = vecshp;

            if (!shp.IsOpen)
            {
                shp.Open();
            }

            FeatureDataSet   featDataSet   = new FeatureDataSet();
            FeatureDataTable featDataTable = null;
            //将point的大地坐标转为经纬度
            Projection pj = new Projection();

            points = pj.GetLatLonFromXY(points, cfg.pjPara);


            //   获取feature数量
            uint featCount = (uint)shp.GetFeatureCount();

            for (uint index = 0; index < featCount; index++)
            {
                FeatureDataRow r = shp.GetFeature(index);
                GeoAPI.Geometries.Coordinate[] geomes = r.Geometry.Coordinates;
                double[] geomsX = new double[geomes.Length];
                double[] geomsY = new double[geomes.Length];
                for (int j = 0; j < geomes.Length; j++)
                {
                    geomsX[j] = geomes[j].X;
                    geomsY[j] = geomes[j].Y;
                }

                if ((points.X < geomsX.Min()) || (points.X > geomsX.Max()) || (points.Y < geomsY.Min()) || (points.Y > geomsY.Max()))
                {
                    continue;
                }

                PointF p1 = new PointF();
                p1.X = points.X;
                p1.Y = points.Y;
                if (InPolygon(geomes, p1))
                {
                    //首先把geomes传出去,供其他使用
                    ContourGeomes = geomes;
                    //如果在某区域内,选中某个区域,放入新图层
                    laySelected.DataSource = new SharpMap.Data.Providers.GeometryProvider(shp.GetFeature(index));
                    polygon = ((NetTopologySuite.Geometries.Polygon)r.Geometry);
                    laySelected.Style.Fill = new System.Drawing.SolidBrush(Color.HotPink);
                    laySelected.CoordinateTransformation = veclayer.CoordinateTransformation;
                }
            }
            return(laySelected);
        }
示例#9
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>();
        }
示例#10
0
        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]);
            }
        }
示例#12
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();
            }
        }
示例#13
0
        public void TestShapeFile(SqlServerSpatialObjectType spatialType)
        {
            using (var p = new ShapeFile(TestUtility.GetPathToTestFile("SPATIAL_F_SKARVMUFF.shp"), true))
            {
                p.Open();

                var env = p.GetExtents();
                if (spatialType == SqlServerSpatialObjectType.Geography && (env.MaxY > 90 || env.MaxY < -90))
                {
                    Assert.Ignore("Test file Y values exceed valid latitudes");
                }

                for (uint i = 0; i < p.GetFeatureCount(); i++)
                {
                    var fdr = p.GetFeature(i);
                    if (fdr.Geometry == null)
                    {
                        continue;
                    }

                    try
                    {
                        fdr.Geometry.SRID = 4326;
                        var res = ToSqlServerAndBack(fdr.Geometry, spatialType);
                        Assert.AreEqual(fdr.Geometry, res);
                        System.Diagnostics.Trace.WriteLine(string.Format("Feature {0} ({1}) converted!", i, fdr[0]));
                    }
                    catch (SqlGeometryConverterException)
                    {
                        System.Diagnostics.Trace.WriteLine(string.Format("Feature {0} ({1}) conversion failed!", i, fdr[0]));
                    }
                    catch (SqlGeographyConverterException)
                    {
                        System.Diagnostics.Trace.WriteLine(string.Format("Feature {0} ({1}) conversion failed!", i, fdr[0]));
                    }
                }
            }
        }
        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();
        }
示例#15
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);
        }
示例#16
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();
            }
        }
示例#17
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));
        }