Shapefile dataprovider

The ShapeFile provider is used for accessing ESRI ShapeFiles. The ShapeFile should at least contain the [filename].shp, [filename].idx, and if feature-data is to be used, also [filename].dbf file.

The first time the ShapeFile is accessed, SharpMap will automatically create a spatial index of the shp-file, and save it as [filename].shp.sidx. If you change or update the contents of the .shp file, delete the .sidx file to force SharpMap to rebuilt it. In web applications, the index will automatically be cached to memory for faster access, so to reload the index, you will need to restart the web application as well.

M and Z values in a shapefile is ignored by SharpMap.

Inheritance: SharpMap.Data.Providers.IProvider, IDisposable
Esempio n. 1
0
 public void GetFeatureShouldWorkForShapeFileWithoutObjectID()
 {
     string path = @"..\..\..\..\data\gemeenten.shp";
     var s = new ShapeFile(path);
     var feature = s.Features[0];
     Assert.LessOrEqual(0, s.IndexOf((IFeature)feature));
 }
Esempio n. 2
0
 public void GetFeatureShouldWorkForShapeFile()
 {
     string path = @"..\..\..\..\data\Europe_Lakes.shp";
     var s = new ShapeFile(path);
     var feature = s.Features[1];
     Assert.LessOrEqual(0, s.IndexOf((IFeature)feature));
 }
Esempio n. 3
0
        public static Map Spherical()
        {
            ICoordinateTransformation transformation = ProjHelper.LatLonToGoogle();
            HttpContext context = HttpContext.Current;
            Map map = new Map(new Size(1, 1));

            IDictionary<string, LayerData> dict = Nyc;
            foreach (string layer in dict.Keys)
            {
                string format = String.Format("~/App_Data/{0}", layer);
                string path = context.Server.MapPath(format);
                if (!File.Exists(path))
                    throw new FileNotFoundException("file not found", path);

                string name = Path.GetFileNameWithoutExtension(layer);
                LayerData data = dict[layer];
                ShapeFile source = new ShapeFile(path, true);
                VectorLayer item = new VectorLayer(name, source)
                {
                    SRID = 4326,
                    TargetSRID = 900913,
                    CoordinateTransformation = transformation,
                    Style = (VectorStyle)data.Style,
                    SmoothingMode = SmoothingMode.AntiAlias
                };
                map.Layers.Add(item);
            }
            return map;
        }
Esempio n. 4
0
            public bool MoveNext()
            {
                if (_shpStream.Position >= _shpHeader.FileLength)
                {
                    _current = new ShapeFileIndexEntry();
                    return(false);
                }

                // Get the record offset
                var recordOffset = (int)_shpStream.Position;

                // Get the oid
                var oid = ShapeFile.SwapByteOrder(_shpReader.ReadInt32());

                Debug.Assert(oid == _lastOid + 1);
                _lastOid = oid;

                // Get the record length
                var recordLength = 2 * ShapeFile.SwapByteOrder(_shpReader.ReadInt32());

                // Set the current ShapeFileIndexEntry
                _current = new ShapeFileIndexEntry(recordOffset, recordLength);

                // Adjust the streams position
                _shpStream.Seek(recordLength, SeekOrigin.Current);

                return(true);
            }
Esempio n. 5
0
        /// <summary>
        /// Creates an instance of this class using the provided <paramref name="headerReader"/>.
        /// </summary>
        /// <param name="headerReader">The stream holding the header information</param>
        public ShapeFileHeader(BinaryReader headerReader)
        {
            // Check file header
            if (headerReader.ReadInt32() != 170328064)
            {
                //File Code is actually 9994, but in Little Endian Byte Order this is '170328064'
                throw (new ApplicationException("Invalid Shapefile (.shp)"));
            }

            // Get file length
            headerReader.BaseStream.Seek(20, SeekOrigin.Current);
            FileLength = 2 * ShapeFile.SwapByteOrder(headerReader.ReadInt32());

            // Check file Version
            if (headerReader.ReadInt32() != ShapeFileVersion)
            {
                throw (new ApplicationException("Invalid Shapefile version"));
            }

            // Get the shape type
            ShapeType = (ShapeType)headerReader.ReadInt32();

            // Get the bounding box
            _envelope = new Envelope(new Coordinate(headerReader.ReadDouble(), headerReader.ReadDouble()),
                                     new Coordinate(headerReader.ReadDouble(), headerReader.ReadDouble()));

            // Get the Z-range
            ZRange = Interval.Create(headerReader.ReadDouble(), headerReader.ReadDouble());

            // Get the Z-range
            MRange = Interval.Create(ParseNoDataValue(headerReader.ReadDouble()),
                                     ParseNoDataValue(headerReader.ReadDouble()));
        }
Esempio n. 6
0
 public void ContainsShouldWorkForShapeFile()
 {
     string path = TestHelper.GetTestDataPath(@"DeltaShell\DeltaShell.Plugins.SharpMapGis.Tests\", "Europe_Lakes.shp");
     var s = new ShapeFile(path);
     var feature = s.Features[0];
     s.Contains((IFeature)feature); // -> should not throw an exception
 }
Esempio n. 7
0
        public void FeatureCount()
        {
            string path = TestHelper.GetTestDataPath(@"DeltaShell\DeltaShell.Plugins.SharpMapGis.Tests\", "Europe_Lakes.shp");
            IFeatureProvider dataSource = new ShapeFile(path);
            Assert.AreEqual(37, dataSource.Features.Count);

            Assert.IsTrue(dataSource.Features.Count == dataSource.GetFeatures(dataSource.GetExtents()).Count);
        }
        public ILayer Create(string layerName, string connectionInfo)
        {
            ShapeFile shapeFileData = new ShapeFile(connectionInfo);

            VectorLayer shapeFileLayer = new VectorLayer(layerName, shapeFileData);

            return shapeFileLayer;
        }
Esempio n. 9
0
 public void LoadFromFile()
 {
     string filePath = Path.GetFullPath(TestHelper.GetDataDir() + @"\rivers.shp");
     IFeatureProvider dataSource = new ShapeFile(filePath, false);
     VectorLayer vectorLayer = new VectorLayer("rivers", dataSource);
     Assert.AreEqual("rivers", vectorLayer.Name);
     Assert.AreEqual(dataSource, vectorLayer.DataSource);
 }
Esempio n. 10
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;
        }
Esempio n. 11
0
        /**
         * Sets the URI of the object to which this source record refers.
         */
        public void setURI(string value)
        {
            if (!string.IsNullOrEmpty(value) && value.EndsWith(".shp"))
            {
                DataSource = new SharpMap.Data.Providers.ShapeFile(value);
            }

            uri = value;
        }
Esempio n. 12
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>();
        }
Esempio n. 13
0
 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();
 }
Esempio n. 14
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();
 }
        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);
        }
        public Envelope GetExtents()
        {
            if (BBox == null) {

                using (ShapeFile shapefile = new ShapeFile (ShpFileName)) {
                    shapefile.Open ();

                    // Get extents, assign to svg "viewbox" attribute.
                    BBox = shapefile.GetExtents ();
                    shapefile.Close ();
                }
            }
            return BBox;
        }
        private Collection<IGeometry> GetBorders()
        {
            Collection<IGeometry> stateBorders;
            using (ShapeFile shapefile = new ShapeFile (ShpFileName)) {
                shapefile.Open ();

                // Get extents, assign to svg "viewbox" attribute.
                Envelope bbox = shapefile.GetExtents ();
                stateBorders = shapefile.GetGeometriesInView (bbox);

                shapefile.Close ();
            }
            return stateBorders;
        }
Esempio n. 18
0
    public SharpMap.Map InitializeMap(System.Drawing.Size size)
    {
        HttpContext.Current.Trace.Write("Initializing map...");

        //Initialize a new map of size 'imagesize'
        SharpMap.Map map = new SharpMap.Map(size);

        //Set up the countries layer
        SharpMap.Layers.VectorLayer layCountries = new SharpMap.Layers.VectorLayer("Countries");
        //Set the datasource to a shapefile in the App_data folder
        SharpMap.Data.Providers.ShapeFile datasource = new SharpMap.Data.Providers.ShapeFile(HttpContext.Current.Server.MapPath(@"~\App_data\USA\states.shp"), true);
        layCountries.DataSource = datasource;
        datacoordsys            = datasource.CoordinateSystem;

        //Set fill-style to green
        layCountries.Style.Fill = new SolidBrush(Color.Green);
        //Set the polygons to have a black outline
        layCountries.Style.Outline            = System.Drawing.Pens.Black;
        layCountries.Style.EnableOutline      = true;
        layCountries.CoordinateTransformation = GetTransform(ddlProjection.SelectedValue);
        if (layCountries.CoordinateTransformation != null)
        {
            litInputCoordsys.Text = layCountries.CoordinateTransformation.TargetCS.WKT;
            litCoordsys.Text      = layCountries.CoordinateTransformation.SourceCS.WKT;
            litTransform.Text     = layCountries.CoordinateTransformation.MathTransform.WKT;
        }
        else
        {
            litInputCoordsys.Text = datasource.CoordinateSystem.WKT;
            litCoordsys.Text      = "None";
            litTransform.Text     = "None";
        }
        SharpMap.Layers.VectorLayer layGrid = new SharpMap.Layers.VectorLayer("Grid");
        //Set the datasource to a shapefile in the App_data folder
        layGrid.DataSource = new SharpMap.Data.Providers.ShapeFile(HttpContext.Current.Server.MapPath(@"~\App_data\USA\latlong.shp"), true);
        layGrid.CoordinateTransformation = layCountries.CoordinateTransformation;
        layGrid.Style.Line = new Pen(Color.FromArgb(127, 255, 0, 0), 1);

        //Add the layers to the map object.
        map.Layers.Add(layCountries);
        map.Layers.Add(layGrid);

        map.BackColor = Color.LightBlue;

        HttpContext.Current.Trace.Write("Map initialized");
        return(map);
    }
Esempio n. 19
0
        public void TestPlainPolygonSymbolizer()
        {
            ShapeFile provider = new ShapeFile(
                "..\\..\\..\\WinFormSamples\\GeoData\\World\\countries.shp", true);
            PolygonalVectorLayer l = new PolygonalVectorLayer("Countries", provider);
            l.Symbolizer = new ModifiedBasicPolygonSymbolizer
                {
                    Fill = new HatchBrush(
                            HatchStyle.WideDownwardDiagonal, 
                            Color.Red /*,
                            System.Drawing.Color.LightPink*/),
                    UseClipping = false,
                    //Outline = System.Drawing.Pens.AliceBlue
                };

            Map m = new Map(new Size(1440, 1080)) { BackColor = Color.Cornsilk };
            m.Layers.Add(l);

            m.ZoomToExtents();

            Stopwatch sw = new Stopwatch();
            Image img = m.GetMap();
            
            sw.Start();
            img = m.GetMap();
            img.Save("PolygonSymbolizer-1.bmp", ImageFormat.Bmp);
            sw.Stop();
            Console.WriteLine(string.Format("Rendering new method:{0}ms", sw.ElapsedMilliseconds));

            l.Symbolizer = new BasicPolygonSymbolizer()
            {
                Fill = new HatchBrush(
                        HatchStyle.WideDownwardDiagonal,
                        Color.Red/*,
                        System.Drawing.Color.LightPink*/),
                UseClipping = false,
                //Outline = System.Drawing.Pens.AliceBlue
            };

            sw.Reset(); sw.Start();
            img = m.GetMap();
            img.Save("PolygonSymbolizer-2.bmp", ImageFormat.Bmp);
            sw.Stop();
            Console.WriteLine(string.Format("Rendering new method:{0}ms", sw.ElapsedMilliseconds));
        
        }
        /// <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, Geometry 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);

                Geometry 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
                                                   Geometry 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];
            }
        }
Esempio n. 21
0
        internal static Map InitializeMap(float angle, string[] filenames)
        {
            var providers = new SharpMap.Data.Providers.ShapeFile[filenames.Length];

            for (int i = 0; i < filenames.Length; i++)
            {
                providers[i] = new ShapeFile(filenames[i]);
            }

            var map = LayerTools.GetMapForProviders(providers);

            Matrix mat = new Matrix();

            mat.RotateAt(angle, map.WorldToImage(map.Center));
            map.MapTransform = mat;

            return(map);
        }
Esempio n. 22
0
        /// <summary>
        /// Method to create a SHX index from a given ShapeFile
        /// </summary>
        /// <param name="shpPath">The path to the shapefile</param>
        public static void Create(string shpPath)
        {
            if (string.IsNullOrEmpty(shpPath))
            {
                throw new ArgumentNullException(shpPath);
            }

            if (!File.Exists(shpPath))
            {
                throw new FileNotFoundException("The specified path does not lead to a file", shpPath);
            }

            var shxPath = Path.ChangeExtension(shpPath, ".shx");

            if (File.Exists(shxPath))
            {
                File.Delete(shxPath);
            }

            using (var it = new ShapeFileEnumerator(shpPath))
            {
                var fs = new FileStream(shxPath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None);
                fs.Seek(100, SeekOrigin.Begin);

                using (var bw = new BinaryWriter(fs))
                {
                    var count = 0;
                    while (it.MoveNext())
                    {
                        count++;
                        bw.Write(ShapeFile.SwapByteOrder(it.Current.Offset / 2));
                        bw.Write(ShapeFile.SwapByteOrder(it.Current.Length / 2));
                    }

                    var length = (int)bw.BaseStream.Position;
                    Debug.Assert(100 + count * 8 == length);
                    bw.BaseStream.Seek(24, SeekOrigin.Begin);
                    bw.Write(ShapeFile.SwapByteOrder(length / 2));
                    bw.BaseStream.Seek(length, SeekOrigin.Begin);
                }
            }
        }
Esempio n. 23
0
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlgOpen = new OpenFileDialog();

            dlgOpen.Filter = "ESRI Shapefiles (*.shp)|*.shp";
            if (dlgOpen.ShowDialog() == DialogResult.OK)
            {
                //lbAssetFields.Items.Clear();
                lbFieldNames.Items.Clear();
                String strFilePath    = dlgOpen.FileName;
                int    iParseFileName = dlgOpen.FileName.LastIndexOf('\\');
                String strFileName    = dlgOpen.FileName.Substring(iParseFileName + 1);
                m_strShapeFilePath   = strFilePath;
                strFilePath          = strFilePath.Substring(0, iParseFileName + 1);
                tbShapeFilePath.Text = m_strShapeFilePath;

                // Set the DBF database connection string
                m_connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strFilePath + ";Extended Properties=dBASE IV;User ID=Admin;Password=;";

                // Open the shapefile at the given path
                ShapeFile shapefile = null;
                try
                {
                    shapefile = new SharpMap.Data.Providers.ShapeFile(m_strShapeFilePath);
                    shapefile.Open();
                }
                catch (Exception exc)
                {
                    Global.WriteOutput("Error: Couldn't open shapefile." + exc.Message);
                    return;
                }
                FeatureDataRow fdr = shapefile.GetFeature(0);
                lbFieldNames.Items.Add("GEOMETRY");
                m_htShapefileFields.Clear();
                for (int i = 0; i < fdr.Table.Columns.Count; i++)
                {
                    lbFieldNames.Items.Add(fdr.Table.Columns[i].ColumnName.ToUpper());
                    m_htShapefileFields.Add(fdr.Table.Columns[i].ColumnName.ToUpper(), fdr.Table.Columns[i].DataType.ToString());
                }
                shapefile.Close();
            }
        }
Esempio n. 24
0
        internal static Map InitializeMap(float angle, string[] filenames)
        {
            if (filenames == null)
                return null;

            var providers = new SharpMap.Data.Providers.ShapeFile[filenames.Length];
            for (int i = 0; i < filenames.Length; i++)
            {
                providers[i] = new ShapeFile(filenames[i], true);
                providers[i].Open();
            }

            var map = LayerTools.GetMapForProviders(providers);

            Matrix mat = new Matrix();
            mat.RotateAt(angle, map.WorldToImage(map.Center));
            map.MapTransform = mat;

            return map;
        }
        public void Load(string fileName, System.Text.Encoding encoding)
        {
            try
            {
                m_shapeFileData = new SharpMap.Data.Providers.ShapeFile(fileName);
                m_shapeFileData.Encoding = encoding;

                m_shapeLayer.CoordinateTransformation = Transform2Mercator(m_shapeFileData.CoordinateSystem);
                m_googleMapCoordinateTransformation = Transform2Mercator(m_shapeFileData.CoordinateSystem);

                //m_shapeLayer.DataSource = m_shapeFileData;
                //if (myMap.Layers.IndexOf(m_shapeLayer) == -1)
                //{
                    //myMap.Layers.Add(m_shapeFileLayer);
                //}
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
        }
Esempio n. 26
0
        public ShapeFileIndex(Stream stream)
        {
            stream.Seek(24, SeekOrigin.Begin);
            var buf = new byte[4];

            stream.Read(buf, 0, 4);
            var bufferSize = 2 * ShapeFile.SwapByteOrder(BitConverter.ToInt32(buf, 0)) - 100;

            _shxBuffer = new byte[bufferSize];
            stream.Seek(100, SeekOrigin.Begin);
            stream.Read(_shxBuffer, 0, bufferSize);

            for (var i = 0; i < bufferSize; i += 4)
            {
                var value = 2 * ShapeFile.SwapByteOrder(BitConverter.ToInt32(_shxBuffer, i));
                var tmp   = BitConverter.GetBytes(value);
                Buffer.BlockCopy(tmp, 0, _shxBuffer, i, 4);
            }

            FeatureCount = (bufferSize) / 8;
        }
Esempio n. 27
0
        public void TestBasicLineSymbolizer()
        {
            ShapeFile p = new ShapeFile(@"d:\\daten\GeoFabrik\\roads.shp", false);
            VectorLayer l = new VectorLayer("roads", p);
            //l.Style.Outline = new System.Drawing.Pen(System.Drawing.Color.Firebrick, 5);
            l.Style.Line = new Pen(Color.Gold, 1);
            l.Style.EnableOutline = false;
            Map m = new Map(new Size(1440, 1080)) { BackColor = Color.Cornsilk };
            m.Layers.Add(l);

            m.ZoomToExtents();

            Stopwatch sw = new Stopwatch();
            sw.Start();
            m.GetMap();

            sw.Stop();
            Console.WriteLine(string.Format("Rendering old method: {0}ms", sw.ElapsedMilliseconds));
            sw.Reset();
            sw.Start();
            Image bmp = m.GetMap();
            sw.Stop();
            Console.WriteLine(string.Format("Rendering old method: {0}ms", sw.ElapsedMilliseconds));
            bmp.Save("NDSRoads1.bmp");


            CachedLineSymbolizer cls = new CachedLineSymbolizer();
            //cls.LineSymbolizeHandlers.Add(new SharpMap.Rendering.Symbolizer.PlainLineSymbolizeHandler { Line = new System.Drawing.Pen(System.Drawing.Color.Firebrick, 5) });
            cls.LineSymbolizeHandlers.Add(new PlainLineSymbolizeHandler { Line = new Pen(Color.Gold, 1) });

            l.Style.LineSymbolizer = cls;
            sw.Reset(); sw.Start();
            bmp = m.GetMap();
            sw.Stop();
            Console.WriteLine(string.Format("Rendering new method: {0}ms", sw.ElapsedMilliseconds));
            bmp.Save("NDSRoads2.bmp");

        }
Esempio n. 28
0
        /// <summary> Event handler for MouseDown event.  </summary>
        /// <param name="sender"> The sender of the MouseDown event. </param>
        /// <param name="e"> The event parameters. </param>
        #region doc:map_MouseDown handler
        private void map_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (!(e.ChangedButton == MouseButton.Left && e.ButtonState == MouseButtonState.Pressed))
            {
                return;
            }

            var canvasPoint = e.GetPosition(this);

            System.Windows.Point wgsPoint = CanvasToGeo(canvasPoint);
            var ds = new FeatureDataSet();

            geometries.Clear();
            using (var shpFile = new SharpMap.Data.Providers.ShapeFile(shapeFilePath))
            {
                shpFile.Open();
                shpFile.ExecuteIntersectionQuery(new BoundingBox(wgsPoint.X, wgsPoint.Y, wgsPoint.X, wgsPoint.Y), ds);

                //if selected any object
                if (ds.Tables[0].Rows.Count <= 0)
                {
                    return;
                }

                using (var geomProvider = new GeometryProvider(ds.Tables[0]))
                {
                    geomProvider.Open();
                    foreach (var geoItem in geomProvider.Geometries)
                    {
                        var geometry = WkbToWpf.Parse(geoItem.AsBinary(), GeoToCanvas);
                        if (geometry.FillContains(canvasPoint))
                        {
                            geometries.Add(geometry);
                        }
                    }
                }
            }
        }
Esempio n. 29
0
        public void TestShapeFile(SqlServerSpatialObjectType spatialType)
        {
            using (var p = new SharpMap.Data.Providers.ShapeFile(GetTestFile(), 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]));
                    }
                }
            }
        }
Esempio n. 30
0
 static ShapeFile decodeShapeFile(XmlElement e, Project proj, int pass)
 {
     ShapeFile shapeFile = null;
     if (e != null)
     {
         if (pass == 0)
         {
             // first pass: create the new source record
             //source = new Source();
             //source.setName(e.GetAttribute("name"));
             //source.setType(e.GetAttribute("type") == "raster" ? Source.SourceType.TYPE_RASTER : Source.SourceType.TYPE_FEATURE);
             //source.setURI(e.GetElementsByTagName("uri")[0].InnerText);
             if (e.GetAttribute("provider") == "ShapeFile")
             {
                 shapeFile = new ShapeFile(e.GetElementsByTagName("uri")[0].InnerText);
             }
         }
         else
         {
             // second pass: reference other sources
             //source = proj.getSource(e.GetAttribute("name"));
             //source.setParentSource(proj.getSource(e.GetAttribute("parent")));
         }
     }
     return shapeFile;
 }
Esempio n. 31
0
    public Map InitializeMap(Size size)
    {
        HttpContext.Current.Trace.Write("Initializing map...");

        //Initialize a new map of size 'imagesize'
        Map map = new Map(size);

        //Set up the countries layer
        VectorLayer layCountries = new VectorLayer("Countries");
        //Set the datasource to a shapefile in the App_data folder
        ShapeFile datasource = new ShapeFile(HttpContext.Current.Server.MapPath(@"~\App_data\USA\states.shp"), true);
        layCountries.DataSource = datasource;
        datacoordsys = datasource.CoordinateSystem;

        //Set fill-style to green
        layCountries.Style.Fill = new SolidBrush(Color.Green);
        //Set the polygons to have a black outline
        layCountries.Style.Outline = Pens.Black;
        layCountries.Style.EnableOutline = true;
        layCountries.CoordinateTransformation = GetTransform(ddlProjection.SelectedValue);
        if (layCountries.CoordinateTransformation != null)
        {
            litInputCoordsys.Text = layCountries.CoordinateTransformation.TargetCS.WKT;
            litCoordsys.Text = layCountries.CoordinateTransformation.SourceCS.WKT;
            litTransform.Text = layCountries.CoordinateTransformation.MathTransform.WKT;
        }
        else
        {
            
            litInputCoordsys.Text = datasource.CoordinateSystem.WKT;
            litCoordsys.Text = "None";
            litTransform.Text = "None";
        }
        VectorLayer layGrid = new VectorLayer("Grid");
        //Set the datasource to a shapefile in the App_data folder
        layGrid.DataSource = new ShapeFile(HttpContext.Current.Server.MapPath(@"~\App_data\USA\latlong.shp"), true);
        layGrid.CoordinateTransformation = layCountries.CoordinateTransformation;
        layGrid.Style.Line = new Pen(Color.FromArgb(127, 255, 0, 0), 1);

        //Add the layers to the map object.
        map.Layers.Add(layCountries);
        map.Layers.Add(layGrid);

        map.BackColor = Color.LightBlue;

        HttpContext.Current.Trace.Write("Map initialized");
        return map;
    }
Esempio n. 32
0
        public void SetupFixture()
        {
            SqlConnectionStringBuilder connStrBuilder = new SqlConnectionStringBuilder(UnitTests.Properties.Settings.Default.SqlServer2008);

            if (string.IsNullOrEmpty(connStrBuilder.DataSource) || string.IsNullOrEmpty(connStrBuilder.InitialCatalog))
            {
                Assert.Ignore("Requires SQL Server connectionstring");
            }

            GeoAPI.GeometryServiceProvider.Instance = new NetTopologySuite.NtsGeometryServices();
            //SqlServerTypes.Utilities.LoadNativeAssemblies(AppDomain.CurrentDomain.BaseDirectory);

            // Set up sample tables (Geometry + Geography)
            using (SqlConnection conn = new SqlConnection(UnitTests.Properties.Settings.Default.SqlServer2008))
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "CREATE TABLE roads_ugl_geom(ID int identity(1,1) PRIMARY KEY, NAME nvarchar(100), GEOM geometry)";
                    cmd.ExecuteNonQuery();
                }

                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "CREATE TABLE roads_ugl_geog(ID int identity(1,1) PRIMARY KEY, NAME nvarchar(100), GEOG geography)";
                    cmd.ExecuteNonQuery();
                }

                // Load data
                using (SharpMap.Data.Providers.ShapeFile shapeFile = new SharpMap.Data.Providers.ShapeFile(GetTestFile()))
                {
                    shapeFile.Open();
                    _geometrySrid = shapeFile.SRID;

                    IEnumerable <uint> indexes = shapeFile.GetObjectIDsInView(shapeFile.GetExtents());

                    // Note that spatial indexes may only kick in at certain number of records
                    // so for thorough testing comment out next line and load all features (approx 3500)
                    indexes = indexes.Take(100);

                    var cmdGeom = new SqlCommand("INSERT INTO roads_ugl_geom(NAME, GEOM) VALUES (@Name, geometry::STGeomFromText(@Geom, @Srid))", conn);
                    var cmdGeog = new SqlCommand("INSERT INTO roads_ugl_geog(NAME, GEOG) VALUES (@Name, geography::STGeomFromText(@Geog, @Srid))", conn);

                    foreach (uint idx in indexes)
                    {
                        SharpMap.Data.FeatureDataRow feature = shapeFile.GetFeature(idx);

                        string wkt;

                        if (feature.Geometry == null || feature.Geometry.IsEmpty)
                        {
                            wkt = "LINESTRING EMPTY";
                        }
                        else
                        {
                            wkt = feature.Geometry.AsText();
                        }

                        if (cmdGeom.Parameters.Count == 0)
                        {
                            cmdGeom.Parameters.AddWithValue("@Geom", wkt);
                            cmdGeom.Parameters.AddWithValue("@Name", feature["NAME"]);
                            cmdGeom.Parameters.AddWithValue("@Srid", _geometrySrid);
                        }
                        else
                        {
                            cmdGeom.Parameters[0].Value = wkt;
                            cmdGeom.Parameters[1].Value = feature["NAME"];
                        }
                        cmdGeom.ExecuteNonQuery();

                        if (cmdGeog.Parameters.Count == 0)
                        {
                            cmdGeog.Parameters.AddWithValue("@Geog", wkt);
                            cmdGeog.Parameters.AddWithValue("@Name", feature["NAME"]);
                            cmdGeog.Parameters.AddWithValue("@Srid", GeographySrid);
                        }
                        else
                        {
                            cmdGeog.Parameters[0].Value = wkt;
                            cmdGeog.Parameters[1].Value = feature["NAME"];
                        }
                        cmdGeog.ExecuteNonQuery();
                    }

                    cmdGeom.Dispose();
                    cmdGeog.Dispose();
                }

                // ensure we have some features with NULL and EMPTY geometries
                using (var cmd = conn.CreateCommand())
                {
                    // To find invalid geometries:
                    // SELECT {OidColumn}, {GeometryColumn}.STIsValid() AS STIsValid, {GeometryColumn}.IsValidDetailed() AS IsValidDetailed FROM {QualifiedTableName}

                    // NULL
                    cmd.CommandText = "INSERT INTO roads_ugl_geom(NAME, GEOM) VALUES ('Test null wkt', NULL)";
                    cmd.ExecuteNonQuery();

                    cmd.CommandText = "INSERT INTO roads_ugl_geog(NAME, GEOG) VALUES ('Test null wkt', NULL)";
                    cmd.ExecuteNonQuery();

                    // EMPTY
                    cmd.CommandText = "INSERT INTO roads_ugl_geom(NAME, GEOM) VALUES ('Test empty wkt', 'LINESTRING EMPTY')";
                    cmd.ExecuteNonQuery();

                    cmd.CommandText = "INSERT INTO roads_ugl_geog(NAME, GEOG) VALUES ('Test empty wkt', 'LINESTRING EMPTY')";
                    cmd.ExecuteNonQuery();

                    // INVALID (ID 144 from shape file; see also ID 2055)
                    cmd.CommandText = $"INSERT INTO roads_ugl_geom(NAME, GEOM) VALUES ('Test invalid wkt', geometry::STGeomFromText('LINESTRING (-84.652756071629071 42.676743004284312, -84.652924071615374 42.676624004283632, -84.652756071629071 42.676743004284312, -84.652512071649028 42.676922004285323, -84.641022072594438 42.685478004332808, -84.638779072781034 42.687271004342172, -84.636932072941363 42.689831004350026, -84.634491073153043 42.693100004360424, -84.62387107404335 42.701092004405112, -84.603256075794022 42.715752004493233, -84.603142075803831 42.715832004493734, -84.599823076091937 42.718651004508146, -84.588676077031693 42.722431004556235, -84.586021077270672 42.725533004568049)', {_geometrySrid}))";
                    cmd.ExecuteNonQuery();

                    cmd.CommandText = $"INSERT INTO roads_ugl_geog(NAME, GEOG) VALUES ('Test invalid wkt', geography::STGeomFromText('LINESTRING (-84.652756071629071 42.676743004284312, -84.652924071615374 42.676624004283632, -84.652756071629071 42.676743004284312, -84.652512071649028 42.676922004285323, -84.641022072594438 42.685478004332808, -84.638779072781034 42.687271004342172, -84.636932072941363 42.689831004350026, -84.634491073153043 42.693100004360424, -84.62387107404335 42.701092004405112, -84.603256075794022 42.715752004493233, -84.603142075803831 42.715832004493734, -84.599823076091937 42.718651004508146, -84.588676077031693 42.722431004556235, -84.586021077270672 42.725533004568049)', {GeographySrid}))";
                    cmd.ExecuteNonQuery();
                }

                // Create GEOM spatial index
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText    = $"CREATE SPATIAL INDEX [{GeometrySpatialIndex}] ON [dbo].[roads_ugl_geom](GEOM) USING GEOMETRY_GRID WITH (BOUNDING_BOX =(-98, 40, -82, 50), GRIDS =(LEVEL_1 = MEDIUM,LEVEL_2 = MEDIUM,LEVEL_3 = MEDIUM,LEVEL_4 = MEDIUM))";
                    cmd.CommandTimeout = 300;
                    cmd.ExecuteNonQuery();
                }

                // Create GEOG spatial index
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText    = $"CREATE SPATIAL INDEX [{GeographySpatialIndex}] ON [dbo].[roads_ugl_geog](GEOG)";
                    cmd.CommandTimeout = 300;
                    cmd.ExecuteNonQuery();
                }

                // initialise counts and test IDs
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = $"SELECT COUNT(ID) FROM roads_ugl_geom WHERE Geom.STIsEmpty() = 0 AND Geom.STIsValid() = 1";
                    _numValidGeoms  = (int)cmd.ExecuteScalar();

                    cmd.CommandText  = $"SELECT COUNT(ID) FROM roads_ugl_geom WHERE GEOM IS NOT NULL AND Geom.STIsEmpty() = 0 AND Geom.STIsValid() = 0";
                    _numInvalidGeoms = (int)cmd.ExecuteScalar();

                    _numValidatedGeoms = _numValidGeoms + _numInvalidGeoms;

                    cmd.CommandText = $"SELECT COUNT(ID) FROM roads_ugl_geom";
                    _numFeatures    = (int)cmd.ExecuteScalar();

                    _idNullGeom    = (uint)(_numFeatures - 2);
                    _idEmptyGeom   = (uint)(_numFeatures - 1);
                    _idInvalidGeom = (uint)(_numFeatures);
                }
            }
        }
Esempio n. 33
0
        public static SharpMap.Map InitializeMap()
        {
            //Initialize a new map of size 'imagesize'
              SharpMap.Map map = new SharpMap.Map();

              //Set up the countries layer
              var monroeCounty = new VectorLayer("Monroe");
              //Set the datasource to a shapefile in the App_data folder
              //layCountries.DataSource = new SharpMap.Data.Providers.ShapeFile("GeoData/World/countries.shp", true);
              ShapeFile roadFile = new ShapeFile("j:/gis/roadsb12.shp", true);
              //using (roadFile)
              //{
              //    roadFile.Open();
              //    for (uint i = 0; i < roadFile.GetFeatureCount(); i++)
              //    {
              //        var feature = roadFile.GetFeature(i);
              //        string name = feature["name"] as string;
              //    }
              //}
              monroeCounty.DataSource = roadFile;
              //Set fill-style to green
              monroeCounty.Style.Fill = new SolidBrush(Color.Green);
              //Set the polygons to have a black outline
              monroeCounty.Style.Outline = System.Drawing.Pens.Black;
              monroeCounty.Style.EnableOutline = true;
              monroeCounty.SRID = 4326;
              monroeCounty.Theme = new CustomTheme(dr => new VectorStyle { Line = new Pen(ColorFromName(dr["Name"] as string)) });

              ////Set up a river layer
              //SharpMap.Layers.VectorLayer layRivers = new SharpMap.Layers.VectorLayer("Rivers");
              ////Set the datasource to a shapefile in the App_data folder
              //layRivers.DataSource = new SharpMap.Data.Providers.ShapeFile("GeoData/World/rivers.shp", true);
              ////Define a blue 1px wide pen
              //layRivers.Style.Line = new Pen(Color.Blue, 1);
              //layRivers.SRID = 4326;

              ////Set up a cities layer
              //SharpMap.Layers.VectorLayer layCities = new SharpMap.Layers.VectorLayer("Cities");
              ////Set the datasource to a shapefile in the App_data folder
              //layCities.DataSource = new SharpMap.Data.Providers.ShapeFile("GeoData/World/cities.shp", true);
              //layCities.Style.SymbolScale = 0.8f;
              //layCities.MaxVisible = 40;
              //layCities.SRID = 4326;

              ////Set up a country label layer
              //SharpMap.Layers.LabelLayer layLabel = new SharpMap.Layers.LabelLayer("Country labels");
              //layLabel.DataSource = layCountries.DataSource;
              //layLabel.Enabled = true;
              //layLabel.LabelColumn = "Name";
              //layLabel.Style = new SharpMap.Styles.LabelStyle();
              //layLabel.Style.ForeColor = Color.White;
              //layLabel.Style.Font = new Font(FontFamily.GenericSerif, 12);
              //layLabel.Style.BackColor = new System.Drawing.SolidBrush(Color.FromArgb(128, 255, 0, 0));
              //layLabel.MaxVisible = 90;
              //layLabel.MinVisible = 30;
              //layLabel.Style.HorizontalAlignment = SharpMap.Styles.LabelStyle.HorizontalAlignmentEnum.Center;
              //layLabel.SRID = 4326;
              //layLabel.MultipartGeometryBehaviour = SharpMap.Layers.LabelLayer.MultipartGeometryBehaviourEnum.Largest;

              ////Set up a city label layer
              //SharpMap.Layers.LabelLayer layCityLabel = new SharpMap.Layers.LabelLayer("City labels");
              //layCityLabel.DataSource = layCities.DataSource;
              //layCityLabel.Enabled = true;
              //layCityLabel.LabelColumn = "Name";
              //layCityLabel.Style = new SharpMap.Styles.LabelStyle();
              //layCityLabel.Style.ForeColor = Color.Black;
              //layCityLabel.Style.Font = new Font(FontFamily.GenericSerif, 11);
              //layCityLabel.MaxVisible = layLabel.MinVisible;
              //layCityLabel.Style.HorizontalAlignment = SharpMap.Styles.LabelStyle.HorizontalAlignmentEnum.Left;
              //layCityLabel.Style.VerticalAlignment = SharpMap.Styles.LabelStyle.VerticalAlignmentEnum.Bottom;
              //layCityLabel.Style.Offset = new PointF(3, 3);
              //layCityLabel.Style.Halo = new Pen(Color.Yellow, 2);
              //layCityLabel.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
              //layCityLabel.SmoothingMode = SmoothingMode.AntiAlias;
              //layCityLabel.SRID = 4326;
              //layCityLabel.LabelFilter = SharpMap.Rendering.LabelCollisionDetection.ThoroughCollisionDetection;
              //layCityLabel.Style.CollisionDetection = true;

              //Add the layers to the map object.
              //The order we add them in are the order they are drawn, so we add the rivers last to put them on top
              map.Layers.Add(monroeCounty);
              //map.Layers.Add(layRivers);
              //map.Layers.Add(layCities);
              //map.Layers.Add(layLabel);
              //map.Layers.Add(layCityLabel);

              //limit the zoom to 360 degrees width
              // map.MaximumZoom = 360;
              map.BackColor = Color.LightBlue;

              map.Center = monroeCounty.Envelope.GetCentroid();
              map.ZoomToBox(monroeCounty.Envelope);

              return map;
        }
Esempio n. 34
0
        public void TestCachedLineSymbolizerInTheme()
        {
            ShapeFile p = new ShapeFile(@"d:\\daten\GeoFabrik\\Aurich\\roads.shp", false);

            VectorLayer l = new VectorLayer("roads", p);
            ClsTheme theme = new ClsTheme(l.Style);
            l.Theme = theme;

            Map m = new Map(new Size(720, 540)) { BackColor = Color.Cornsilk };
            m.Layers.Add(l);

            m.ZoomToExtents();

            Stopwatch sw = new Stopwatch();

            sw.Start();
            Image bmp = m.GetMap();
            sw.Stop();
            Console.WriteLine(string.Format("Rendering new method: {0}ms", sw.ElapsedMilliseconds));
            bmp.Save("AurichRoads1Theme.bmp");
        }
Esempio n. 35
0
        public void TestWarpedLineSymbolizer()
        {
            ShapeFile p = new ShapeFile(@"d:\\daten\GeoFabrik\\Aurich\\roads.shp", false);

            VectorLayer l = new VectorLayer("roads", p);

            CachedLineSymbolizer cls = new CachedLineSymbolizer();
            cls.LineSymbolizeHandlers.Add(new PlainLineSymbolizeHandler { Line = new Pen(Color.Gold, 2) });

            WarpedLineSymbolizeHander wls = new WarpedLineSymbolizeHander
                          {
                              Pattern =
                                  WarpedLineSymbolizer.
                                  GetGreaterSeries(3, 3),
                              Line = new Pen(Color.Firebrick, 1)
                              ,
                              Interval = 20
                          };
            cls.LineSymbolizeHandlers.Add(wls);
            l.Style.LineSymbolizer = cls;

            Map m = new Map(new Size(720, 540)) { BackColor = Color.Cornsilk };
            m.Layers.Add(l);

            m.ZoomToExtents();

            Stopwatch sw = new Stopwatch();

            sw.Start();
            Image bmp = m.GetMap();
            sw.Stop();
            Console.WriteLine(string.Format("Rendering new method: {0}ms", sw.ElapsedMilliseconds));
            bmp.Save("AurichRoads1.bmp");

            cls.LineSymbolizeHandlers[1] = new WarpedLineSymbolizeHander
                                               {
                                                   Pattern =
                                                       WarpedLineSymbolizer.
                                                       GetTriangle(4, 0),
                                                   Line = new Pen(Color.Firebrick, 1),
                                                   Fill = new SolidBrush(Color.Firebrick)
                                                   ,
                                                   Interval = 10
                                               };
            sw.Reset(); sw.Start();
            bmp = m.GetMap();
            sw.Stop();
            Console.WriteLine(string.Format("Rendering new method: {0}ms", sw.ElapsedMilliseconds));
            bmp.Save("AurichRoads2-0.bmp");

            cls.LineSymbolizeHandlers[1] = new WarpedLineSymbolizeHander
            {
                Pattern =
                    WarpedLineSymbolizer.
                    GetTriangle(4, 1),
                Line = new Pen(Color.Firebrick, 1),
                Fill = new SolidBrush(Color.Firebrick)
                ,
                Interval = 10
            };
            sw.Reset(); sw.Start();
            bmp = m.GetMap();
            sw.Stop();
            Console.WriteLine(string.Format("Rendering new method: {0}ms", sw.ElapsedMilliseconds));
            bmp.Save("AurichRoads2-1.bmp");
            cls.LineSymbolizeHandlers[1] = new WarpedLineSymbolizeHander
            {
                Pattern =
                    WarpedLineSymbolizer.
                    GetTriangle(4, 2),
                Line = new Pen(Color.Firebrick, 1),
                Fill = new SolidBrush(Color.Firebrick)
                ,
                Interval = 10
            };
            sw.Reset(); sw.Start();
            bmp = m.GetMap();
            sw.Stop();
            Console.WriteLine(string.Format("Rendering new method: {0}ms", sw.ElapsedMilliseconds));
            bmp.Save("AurichRoads2-2.bmp");

            cls.LineSymbolizeHandlers[1] = new WarpedLineSymbolizeHander
            {
                Pattern =
                    WarpedLineSymbolizer.
                    GetTriangle(4, 3),
                Line = new Pen(Color.Firebrick, 1),
                Fill = new SolidBrush(Color.Firebrick)
                ,
                Interval = 10
            };
            sw.Reset(); sw.Start();
            bmp = m.GetMap();
            sw.Stop();
            Console.WriteLine(string.Format("Rendering new method: {0}ms", sw.ElapsedMilliseconds));
            bmp.Save("AurichRoads2-3.bmp");


            //cls.LineSymbolizeHandlers[0] = cls.LineSymbolizeHandlers[1];
            cls.LineSymbolizeHandlers[1] = new WarpedLineSymbolizeHander
                                               {
                                                   Pattern =
                                                       WarpedLineSymbolizer.GetZigZag(4, 4),
                                                   Line = new Pen(Color.Firebrick, 1),
                                                   //Fill = new System.Drawing.SolidBrush(System.Drawing.Color.Firebrick)
                                               };
            sw.Reset(); sw.Start();
            bmp = m.GetMap();
            sw.Stop();
            Console.WriteLine(string.Format("Rendering new method: {0}ms", sw.ElapsedMilliseconds));
            bmp.Save("AurichRoads3.bmp");
        }
Esempio n. 36
0
        public ILayer Create(string layerName, string connectionInfo)
        {
            ShapeFile shapeFileData = new ShapeFile(connectionInfo);
            VectorLayer shapeFileLayer = new VectorLayer(layerName, shapeFileData);
            shapeFileLayer.Style.Fill = new System.Drawing.SolidBrush(System.Drawing.Color.Wheat);
            shapeFileLayer.Style.Outline = new System.Drawing.Pen(new System.Drawing.SolidBrush(System.Drawing.Color.Black), 1);
            shapeFileLayer.Style.Enabled = true;
            shapeFileLayer.Style.EnableOutline = true;

            return shapeFileLayer;
        }
Esempio n. 37
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();
            Envelope ext = sf.GetExtents();
            FeatureDataSet ds = new FeatureDataSet();
            sf.ExecuteIntersectionQuery(ext, ds);
            //ds.Tables[0].Columns.Remove("Oid");
            return ds.Tables[0];
        }
Esempio n. 38
0
        public static Map Default()
        {
            HttpContext context = HttpContext.Current;
            Map map = new Map(new Size(1, 1));

            IDictionary<string, LayerData> dict = Nyc;
            foreach (string layer in dict.Keys)
            {
                string format = String.Format("~/App_Data/{0}", layer);
                string path = context.Server.MapPath(format);
                if (!File.Exists(path))
                    throw new FileNotFoundException("file not found", path);

                string name = Path.GetFileNameWithoutExtension(layer);
                LayerData data = dict[layer];
                ShapeFile source = new ShapeFile(path, true, new WebCacheUtility());
                VectorLayer item = new VectorLayer(name, source)
                {
                    SRID = 4326,
                    Style = (VectorStyle)data.Style,
                    SmoothingMode = SmoothingMode.AntiAlias
                };
                map.Layers.Add(item);
            }
            return map;
        }
Esempio n. 39
0
        internal static Map Default()
        {       
            string currdir = Directory.GetCurrentDirectory();
            Trace.WriteLine(String.Format("Current directory: {0}", currdir));

            Map map = new Map(new Size(1, 1));
            IDictionary<string, LayerData> dict = Nyc;
            foreach (string layer in dict.Keys)
            {
                string format = String.Format(@"WMS\Server\data\{0}", layer);                
                string path = Path.Combine(currdir, format);
                if (!File.Exists(path))
                    throw new FileNotFoundException("file not found", path);

                string name = Path.GetFileNameWithoutExtension(layer);
                LayerData data = dict[layer];
                ShapeFile source = new ShapeFile(path, true);
                VectorLayer item = new VectorLayer(name, source)
                {
                    SRID = 4326,
                    Style = (VectorStyle)data.Style,
                    SmoothingMode = Smoothing.AntiAlias
                };
                map.Layers.Add(item);
            }
            return map;
        }
Esempio n. 40
0
        public void UseShapefileFeaturesAdFeatureCoverageSource()
        {
            string path =
                Path.Combine(sharpMapGisShapeFilePath,"rivers.shp");
            ShapeFile shapeFile = new ShapeFile(path);
            
            // select only some features from shapefile
            IEnvelope coverageFeatureEnvelope = shapeFile.GetExtents();
            coverageFeatureEnvelope.ExpandBy(0.5, 0.5);

            FeatureCoverage coverage = new FeatureCoverage();
            coverage.Components.Add(new Variable<double>("value"));
            coverage.Arguments.Add(new Variable<FeatureDataRow>("feature"));
            coverage.Features = shapeFile.GetFeatures(coverageFeatureEnvelope);

            double[] values = new double[coverage.FeatureVariable.Values.Count];
            for (int i = 0; i < values.Length; i++)
            {
                values[i] = i;
            }

            coverage.SetValues(values);
        }
Esempio n. 41
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();
        }