예제 #1
0
        private Dictionary <string, List <Point> > GetTilesFromShapeFile()
        {
            var tilesToDownload = new Dictionary <string, List <Point> >();
            var indexMapFile    = Shapefile.OpenFile(this.options.ShapeFile);

            indexMapFile.Reproject(ProjectionInfo.FromEpsgCode(4326));

            // Get the map index from the Feature data
            for (int i = 0; i < indexMapFile.DataTable.Rows.Count; i++)
            {
                // Get the feature
                DotSpatial.Data.IFeature feature = indexMapFile.Features.ElementAt(i);

                var polygon = feature.BasicGeometry as Polygon;
                var name    = (string)feature.DataRow[1];

                if (!string.IsNullOrWhiteSpace(this.options.FeaturePropertyValue))
                {
                    if (this.options.FeaturePropertyValue != name)
                    {
                        continue;
                    }
                }
                tilesToDownload[name] = polygon.GetTiles(name, this.options.MinZoom, this.options.MaxZoom);
                // Now it's very quick to iterate through and work with the feature.
            }
            return(tilesToDownload);
        }
        private double GetRandomVectorValue(string file, int requests)
        {
            var featureIds = new int[requests];

            using (var shapefile = Shapefile.OpenFile(file))
            {
                var numberOfFeatures = shapefile.Features.Count;
                Parallel.For(0, requests, index => { featureIds[index] = _rnd.Next(numberOfFeatures); });
            }

            // Close the file and reopen after messurement has started

            var watch = System.Diagnostics.Stopwatch.StartNew();

            using (var shapefile = Shapefile.OpenFile(file))
            {
                var shp = shapefile;
                Parallel.ForEach(featureIds, id =>
                {
                    var feature  = shp.GetFeature(id);
                    var geometry = feature.Geometry;
//                    Console.WriteLine(geometry);
                });
            }

            return(watch.Elapsed.Milliseconds);
        }
예제 #3
0
        private static RouteFeature[] ReadFeatures(string path)
        {
            var sf = Shapefile.OpenFile(path);

            sf.Reproject(KnownCoordinateSystems.Geographic.World.WGS1984);

            var features = new List <RouteFeature>();

            var columns = GetColumns(sf);

            foreach (var feature in sf.Features)
            {
                var f = new RouteFeature();
                f.Data.Coordinates = feature.Coordinates.Select(t => new PointPosition
                {
                    Latitude  = t.Y,
                    Longitude = t.X
                }).ToArray();

                f.Data.Properties = GetAttributes(feature, columns);
                features.Add(f);
            }

            return(features.ToArray());
        }
예제 #4
0
        public void SelectIndexByAttribute()
        {
            var shapeFile = Shapefile.OpenFile(Path.Combine(_shapefiles, "lakes.shp"));
            var features  = shapeFile.SelectIndexByAttribute("[NAME]='Great Salt Lake'");

            Assert.AreEqual(1, features.Count);
        }
예제 #5
0
        void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            #region 矢量数据读取

            string countyShapePath = Path.Combine(m_GlobeControl.DataDirectory, @"China\ChinaSHP\中国县界.shp");
            if (File.Exists(countyShapePath))
            {
                m_countyPosition = new Hashtable();
                Shapefile      _sf       = Shapefile.OpenFile(countyShapePath);
                ProjectionInfo piWGS1984 = KnownCoordinateSystems.Geographic.World.WGS1984;
                if (_sf.Projection != piWGS1984 && _sf.CanReproject)
                {
                    _sf.Reproject(piWGS1984);//如果投影不是WGS1984投影,则进行投影变换
                }
                foreach (IFeature ft in _sf.Features)
                {
                    Shape           shape     = ft.ToShape();
                    List <double[]> verticess = new List <double[]>();
                    if (shape.Range.Parts == null)
                    {
                        verticess.Add(shape.Vertices);
                    }
                    else
                    {
                        foreach (PartRange pr in shape.Range.Parts)
                        {
                            verticess.Add(pr.Vertices);
                        }
                    }
                    string shapeName = ft.DataRow["NAME"].ToString();
                    double centerLon = 0, centerLat = 0;
                    long   count = 0;
                    foreach (double[] vts in verticess)
                    {
                        count += vts.Length / 2;
                        for (int i = 0; i < vts.Length; i += 2)
                        {
                            centerLon += vts[i];
                            centerLat += vts[i + 1];
                        }
                    }
                    centerLon /= count;
                    centerLat /= count;
                    shapeName  = shapeName == "" ? Guid.NewGuid().ToString() : shapeName;
                    try
                    {
                        m_countyPosition.Add(shapeName, string.Format("{0}#{1}", centerLat, centerLon));
                    }
                    catch (ArgumentException)
                    {
                        m_countyPosition.Add(shapeName + Guid.NewGuid().ToString(), string.Format("{0}#{1}", centerLat, centerLon));
                    }
                }
            }

            #endregion
        }
예제 #6
0
 /// <summary>
 /// This will use this object to open a shapefile, but launches an open file dialog for the user to select the file to open.
 /// </summary>
 /// <param name="self">this.</param>
 /// <returns>A new Shapefile created from the file chosen by the open file dialog.</returns>
 public static Shapefile OpenFile(this Shapefile self)
 {
     using var ofd = new OpenFileDialog { Filter = @"Shapefiles (*.shp) |*.shp|All Files|*.*" };
     if (ofd.ShowDialog() != DialogResult.OK)
     {
         return(null);
     }
     return(Shapefile.OpenFile(ofd.FileName));
 }
예제 #7
0
        private static Collection <NatureArea> GenerateNatureAreasFromShapeFile(string shapeFilePath, int epsgCode, string knr, int startFeature, int featureCount)
        {
            var natureAreas = new Collection <NatureArea>();

            shapeFilePath = FileLocator.FindFileInTree(shapeFilePath);
            Shapefile shapeFile  = Shapefile.OpenFile(shapeFilePath);
            var       endFeature = startFeature + featureCount < shapeFile.Features.Count
                ? startFeature + featureCount
                : shapeFile.Features.Count;

            for (var number = startFeature; number < endFeature; number++)
            {
                var feature = shapeFile.Features[number];
                var area    = new NatureArea {
                    UniqueId = new Identification()
                };

                var numberString = number.ToString();
                var guid         = "00000000-0000-0000-" + knr + "-";

                for (int i = 0; i < 12 - numberString.Length; ++i)
                {
                    guid += "0";
                }

                area.UniqueId.LocalId = new Guid(guid + numberString);

                area.UniqueId.NameSpace = "NBIC";
                area.UniqueId.VersionId = "1.0";

                area.Version = "1";
                area.Nivå    = Types.NatureLevel.Natursystem;

                area.Area = SqlGeometry.STGeomFromText(new SqlChars(feature.BasicGeometry.ToString()), epsgCode);

                var       natureAreaType = new NatureAreaType();
                const int rowOffset      = 0; // 1 for melhus
                natureAreaType.Code  = (string)feature.DataRow[rowOffset + 4];
                natureAreaType.Share = 1;
                if (feature.DataRow[rowOffset + 3] != DBNull.Value)
                {
                    var descriptionVariable      = new DescriptionVariable();
                    var descriptionVariableParts = ((string)feature.DataRow[rowOffset + 3]).Split('_');
                    descriptionVariable.Code  = descriptionVariableParts[0];
                    descriptionVariable.Value = descriptionVariableParts[1];
                    natureAreaType.AdditionalVariables.Add(descriptionVariable);
                }
                area.Parameters.Add(natureAreaType);

                area.Surveyed = DateTime.Parse(feature.DataRow[rowOffset + 5].ToString());
                area.Surveyer = new Contact {
                    Company = (string)feature.DataRow[rowOffset + 8]
                };
                natureAreas.Add(area);
            }
            return(natureAreas);
        }
예제 #8
0
        /// <summary>
        /// 初始化矢量文件
        /// </summary>
        private void readPlaceNameAnnotation()
        {
            //初始化列表
            placeNameAnnotation = new List <Annotation>();

            //打开矢量文件
            Shapefile _sf = Shapefile.OpenFile(m_ShapeFilePath);
            //投影转换
            ProjectionInfo piWGS1984 = KnownCoordinateSystems.Geographic.World.WGS1984;

            if (_sf.Projection != piWGS1984 && _sf.CanReproject)
            {
                _sf.Reproject(piWGS1984);//如果投影不是WGS1984投影,则进行投影变换
            }
            #region 读取矢量文件中的子矢量内容

            foreach (IFeature ft in _sf.Features)
            {
                Shape           shape     = ft.ToShape();
                List <double[]> verticess = new List <double[]>();
                if (shape.Range.Parts == null)
                {
                    verticess.Add(shape.Vertices);
                }
                else
                {
                    foreach (PartRange pr in shape.Range.Parts)
                    {
                        verticess.Add(pr.Vertices);
                    }
                }

                if (m_isShowLabel)
                {
                    string shapeName = ft.DataRow[m_labelColumnName].ToString();
                    double centerLon = 0, centerLat = 0;
                    long   count = 0;
                    foreach (double[] vts in verticess)
                    {
                        count += vts.Length / 2;
                        for (int i = 0; i < vts.Length; i += 2)
                        {
                            centerLon += vts[i];
                            centerLat += vts[i + 1];
                        }
                    }
                    centerLon /= count;
                    centerLat /= count;
                    Annotation annotation = new Annotation(shapeName, centerLat, centerLon,
                                                           m_textColorAtImageMode, m_textColorAtMapMode, MaximumDisplayDistance, MinimumDisplayDistance);
                    annotation.IsOn = true;
                    placeNameAnnotation.Add(annotation);
                }
            }
            #endregion
        }
예제 #9
0
        public void TestPreparedGeometryFilter()
        {
            var sf = Shapefile.OpenFile("");

            var randomId    = new System.Random().Next(0, sf.NumRows() - 1);
            var buffer      = sf.GetShape(randomId, false).ToGeoAPI().Buffer(20d);
            var bufferShape = buffer.ToDotSpatialShape();

            var res = sf.Select(bufferShape);
        }
예제 #10
0
 public MapDrawer(string shapeFile)
 {
     this.shapeFile = null;
     UIConsole.Debug($"MapDrawer -- Loading ShapeFile {shapeFile}");
     try {
         this.shapeFile = Shapefile.OpenFile(shapeFile);
         UIConsole.Debug("MapDrawer -- ShapeFile Loaded at MapDrawer");
     } catch (Exception e) {
         UIConsole.Error($"MapDrawer -- Cannot load ShapeFile at {shapeFile}: {e}");
     }
 }
예제 #11
0
        public MapLayer(string folder)
        {
            List <string> files = Directory.GetFiles(folder, "*_pA.shp").ToList();

            files.AddRange(Directory.GetFiles(folder, "*_pAH.shp").ToList());
            List <int> ids = new List <int>();

            foreach (var file in files)
            {
                var f = Shapefile.OpenFile(file);
                shapefiles.Add(f);
            }
        }
예제 #12
0
        public void mReadSectionShpFile(string sfilePath)
        {
            var       ShpData      = Shapefile.OpenFile(sfilePath);
            DataTable ShpfileTable = ShpData.DataTable;

            foreach (DataRow shp in ShpfileTable.Rows)
            {
                ImageNodeModel thisImageNode = new ImageNodeModel((int)shp[0], (Int16)shp[1], (Int16)shp[2], (Int16)shp[3], (string)shp[4],
                                                                  (double)shp[5], (double)shp[6], (double)shp[7], (double)shp[8], (double)shp[9], (double)shp[10]);
                _imageNodeModelcollection.Add(thisImageNode);
            }
            SectionModel.N_images = ShpfileTable.Rows.Count;
        }
 public Option <IFeatureCollection, Exception> Get()
 {
     try
     {
         var shapefile = Shapefile.OpenFile(this.pathToShapefile);
         var features  = shapefile.Features.Select(this.CreateRecord);
         var res       = new FeatureCollection(features, shapefile.DataTable);
         return(Some <IFeatureCollection, Exception>(res));
     }
     catch (Exception ex)
     {
         return(None <IFeatureCollection, Exception>(ex));
     }
 }
        public void CopyAttributesToClipped()
        {
            var target = new ClipPolygonWithPolygon();

            // load input 1 Shapefile as IFeatureSet
            IFeatureSet europeShape = Shapefile.OpenFile(Common.AbsolutePath(@"Data\ClipPolygonWithPolygonTests\EUR_countries.shp"));

            // load input 2 Shapefile as IFeatureSet
            IFeatureSet belgiumShape = Shapefile.OpenFile(Common.AbsolutePath(@"Data\ClipPolygonWithPolygonTests\Belgium.shp"));

            // set output file as IFeatureSet shapefile
            IFeatureSet outputShape = new FeatureSet()
            {
                Filename = FileTools.GetTempFileName(".shp")
            };

            target.Execute(europeShape, belgiumShape, outputShape, new MockProgressHandler());

            // the output file needs to be closed and re-opened, because the DataTable in memory does not match the DataTable on disk
            outputShape.Close();
            var outputFile = FeatureSet.Open(outputShape.Filename);

            try
            {
                // output shapefile attribute columns should match the input 1 attribute columns
                Assert.That(outputFile.DataTable.Columns[0].Caption.Equals("ID"));
                Assert.That(outputFile.DataTable.Columns[1].Caption.Equals("Name"));

                string[,] dataValues =
                {
                    { "BE", "Belgium"    },
                    { "DE", "Germany"    },
                    { "LU", "Luxembourg" }
                };

                var mpCount = 0;
                foreach (var feature in outputFile.Features)
                {
                    Assert.That(feature.DataRow.ItemArray.Length == 2 && feature.DataRow.ItemArray[0].Equals(dataValues[mpCount, 0]) && feature.DataRow.ItemArray[1].Equals(dataValues[mpCount, 1]));
                    mpCount++;
                }

                Assert.That(mpCount == 3);
            }
            finally
            {
                FileTools.DeleteShapeFile(outputShape.Filename);
            }
        }
예제 #15
0
        public static Grid FromShapeFile(string shapeFilePath, RutenettType rutenettType, int epsgCode)
        {
            var grid = new Grid(rutenettType);

            Shapefile shapeFile = Shapefile.OpenFile(shapeFilePath);

            foreach (var feature in shapeFile.Features)
            {
                var cell = new GridCell();
                cell.CellId = feature.DataRow[0].ToString();
                var text = new SqlChars(feature.BasicGeometry.ToString());
                cell.Geometry = SqlGeometry.STGeomFromText(text, epsgCode);
                grid.Cells.Add(cell);
            }

            return(grid);
        }
예제 #16
0
        public void ClipRasterWithPolygonTest()
        {
            var shapeFilePath  = Path.Combine("Data", "elbe_watershed1.shp");
            var rasterFilePath = Path.Combine("Data", "kriging.bgd");
            var resultFilePath = Path.Combine("Data", "clipResult.bgd");

            var lClipPolygon = Shapefile.OpenFile(shapeFilePath);
            var lGridToClip  = Raster.OpenFile(rasterFilePath, false);

            var lGridAfterClip = new Raster {
                Filename = resultFilePath
            };

            ClipRaster.ClipRasterWithPolygon(lClipPolygon.Features[0], lGridToClip, lGridAfterClip.Filename);
            var ras2 = Raster.Open(lGridAfterClip.Filename);

            Assert.AreEqual(lGridToClip.NoDataValue, ras2.NoDataValue);
        }
예제 #17
0
        private Polygon GetLuster()
        {
            Shapefile indexMapFile = Shapefile.OpenFile("kommune2018.shp");

            indexMapFile.Reproject(ProjectionInfo.FromEpsgCode(4326));
            Polygon polygon = null;

            // Get the map index from the Feature data
            for (int i = 0; i < indexMapFile.DataTable.Rows.Count; i++)
            {
                // Get the feature
                IFeature feature = indexMapFile.Features.ElementAt(i);
                if ((string)feature.DataRow[1] == "Luster")
                {
                    polygon = feature.BasicGeometry as Polygon;
                }
            }
            return(polygon);
        }
예제 #18
0
        private static GridCell[] GetGrid(string path)
        {
            var sf = Shapefile.OpenFile(path);

            sf.Reproject(KnownCoordinateSystems.Geographic.World.WGS1984);

            var columns = GetColumns(sf);

            return((from feature in sf.Features
                    let attributes = GetAttributes(feature, columns)
                                     select new GridCell
            {
                Border = feature.Coordinates.Select(t => new PointPosition {
                    Latitude = t.Y, Longitude = t.X
                })
                         .ToArray(),
                Index = attributes["TEXTID"].ToString()
            }).ToArray());
        }
예제 #19
0
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            string    filename = ReadFile();
            var       shp      = Shapefile.OpenFile(filename);
            IMapLayer layer    = null;

            layer = map.Layers.Add(shp) as IMapLayer;
            if (layer is MapPointLayer)
            {
                file_layer.Add(filename, layer as MapPointLayer);
                comboBox1.Items.Add(filename);
                flag = true;
            }
            else
            {
                map.Layers.Remove(layer);
                MessageBox.Show("要素集格式错误,需要点类型图层!", "TIN提示信息", MessageBoxButtons.OKCancel);
            }
        }
예제 #20
0
        public void GeometryToWktTest_2()
        {
            Log.Debug("Enter");

            var testShapeFileFullPath = TestHelper.GetTestFile(@"Shapefiles\lakes.shp");

            Assert.True(File.Exists(testShapeFileFullPath), $"Shapefile: {testShapeFileFullPath} does not exist.");

            string name = "Lake Texoma";

            Shapefile shapefile = Shapefile.OpenFile(testShapeFileFullPath);
            var       feature   = shapefile.SelectByAttribute($"NAME = '{name}'").First();

            Assert.IsNotNull(feature);

            var actual = feature.BasicGeometry.ToString();

            // Console.WriteLine(actual);

            Assert.AreEqual(expectedWkt, actual);
        }
        public void View(string path, ContextObject context)
        {
            this._context = context;
            context.Title = $"{Path.GetFileName(path)}";
            try
            {
                mapCtrl = new Map()
                {
                    Name = "mapCtrl",
                    //设置缩放
                    FunctionMode = FunctionMode.Info,
                    Dock         = DockStyle.Fill
                };
                WindowsFormsHost host = new WindowsFormsHost()
                {
                    Child = mapCtrl,
                };

                //添加shp图层
                shp = Shapefile.OpenFile(path);
                mapCtrl.Layers.Add(shp);
                mapCtrl.ZoomToMaxExtent();
                mapCtrl.Refresh();

                mapCtrl.MouseMove += MapCtrl_MouseMove;

                context.ViewerContent = host;
            }
            catch (Exception ex)
            {
                context.ViewerContent = new System.Windows.Controls.Label
                {
                    Content = $"Can not open shapefile because of: {ex.Message}"
                };
            }
            finally
            {
                context.IsBusy = false;
            }
        }
예제 #22
0
        /// <summary>
        /// read shape file to DataInfo List
        /// </summary>
        /// <param name="fileName">file name</param>
        /// <param name="start">start index of record</param>
        /// <param name="count">how many records to read</param>
        /// <returns>DataInfo List</returns>
        public List <DataInfo> ReadFromFile(string fileName, int start = 0, int count = 0)
        {
            List <DataInfo> lsData = new List <DataInfo>();

            Shapefile fs    = Shapefile.OpenFile(fileName);
            int       index = 0;

            foreach (DataRow row in fs.DataTable.Rows)
            {
                DataInfo data = new DataInfo();
                data.Spatial = fs.GetShape(index, false).ToGeometry().ToString();
                foreach (DataColumn col in fs.GetColumns())
                {
                    data.NonSpatial[col.ColumnName] = row[col.ColumnName].ToString();
                }

                lsData.Add(data);
                index++;
            }

            return(lsData);
        }
예제 #23
0
        /// <summary>
        /// Convert features defined in a shape file to Areas.
        /// </summary>
        /// <param name="shapeFilePath">Path to the shape file</param>
        /// <param name="areaType">area type</param>
        /// <param name="sourceEpsgCode"></param>
        private static AreaCollection FromShapeFile(string shapeFilePath, AreaType areaType, int sourceEpsgCode)
        {
            var       areas     = new AreaCollection();
            Shapefile shapeFile = Shapefile.OpenFile(shapeFilePath);

            shapeFile.Reproject(ProjectionInfo.FromEpsgCode(sourceEpsgCode));

            foreach (var feature in shapeFile.Features)
            {
                var area   = new Area();
                var id     = feature.DataRow[0].ToString();
                var number = int.Parse(id.Replace("VV", ""));
                area.Number   = number;
                area.Name     = feature.DataRow[1].ToString();
                area.Type     = areaType;
                area.Geometry = SqlGeometry.STGeomFromText(new SqlChars(feature.BasicGeometry.ToString()),
                                                           Config.Settings.Map.SpatialReferenceSystemIdentifier);
                area.Category = feature.DataRow[3].ToString();
                areas.Add(area);
            }

            return(areas);
        }
예제 #24
0
        public static void Main(string[] args)
        {
            var nycBoroughs = Shapefile.OpenFile(@"C:\NYC Shape\nybb_13a\nybb.shp");
            var wktstring   = "PROJCS[\"NAD_1983_StatePlane_New_York_Long_Island_FIPS_3104_Feet\",GEOGCS[\"GCS_North_American_1983\",DATUM[\"D_North_American_1983\",SPHEROID[\"GRS_1980\",6378137.0,298.257222101]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Lambert_Conformal_Conic\"],PARAMETER[\"False_Easting\",984250.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",-74.0],PARAMETER[\"Standard_Parallel_1\",40.66666666666666],PARAMETER[\"Standard_Parallel_2\",41.03333333333333],PARAMETER[\"Latitude_Of_Origin\",40.16666666666666],UNIT[\"Foot_US\",0.3048006096012192]]";

            var latlongwkt = "GEOGCS [\"Longitude / Latitude (NAD 83)\",DATUM [\"NAD 83\",SPHEROID [\"GRS 80\",6378137,298.257222101]],PRIMEM [\"Greenwich\",0.000000],UNIT [\"Decimal Degree\",0.01745329251994330]]";
            var csvFile    = @"C:\NYC Shape\studylatlong.csv";
            var targetFile = @"C:\NYC Shape\nycstudieslatlong.csv";

            var studyData = new List <StudyInfo>();

            using (StreamReader sr = new StreamReader(csvFile))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    var tokens = line.Split(',');
                    var study  = StudyInfo.CreateFromStrings(tokens);
                    if (study.Latitude < 40 || study.Latitude > 42 ||
                        study.Longitude < -75 || study.Longitude > -70)
                    {
                    }
                    else
                    {
                        studyData.Add(StudyInfo.CreateFromStrings(tokens));
                    }
                }
                Console.WriteLine("# of Studies: " + studyData.Count());
            }

            ICoordinateSystem nycCS =
                CoordinateSystemWktReader.Parse(wktstring) as ICoordinateSystem;

            ICoordinateSystem baseCS =
                CoordinateSystemWktReader.Parse(latlongwkt) as ICoordinateSystem;

            var ctFactory = new CoordinateTransformationFactory();
            // Transform lat/long points into NYC UTM.
            var transformer = ctFactory.CreateFromCoordinateSystems(baseCS, nycCS);

            var nycStudies = new List <StudyInfo>();

            foreach (var study in studyData)
            {
                double[] fromPoint     = { study.Longitude, study.Latitude };
                double[] toPoint       = transformer.MathTransform.Transform(fromPoint);
                var      studyLocation = new Coordinate(toPoint[0], toPoint[1]);
                if (IsPointInShape(studyLocation, nycBoroughs.Features))
                {
                    nycStudies.Add(study);
                }
            }

            Console.WriteLine("# of NYC Studies: " + nycStudies.Count());

            using (StreamWriter sw = new StreamWriter(targetFile))
            {
                foreach (var study in nycStudies)
                {
                    sw.Write("" + study.StudyID);
                    sw.Write(",");
                }
                sw.WriteLine();
            }

            Console.WriteLine("Output written.");
            Console.ReadLine();
        }
예제 #25
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            //retrive inputs
            string filePath = "";

            if (!DA.GetData(0, ref filePath))
            {
                return;
            }

            bool readFile = false;

            if (!DA.GetData(1, ref readFile))
            {
                return;
            }


            if (readFile)
            {
                GH_Structure <GH_Point>  featureGeometry = new GH_Structure <GH_Point>();//tree with all features
                GH_Structure <GH_String> attributes      = new GH_Structure <GH_String>();
                var openSHP = Shapefile.OpenFile(@filePath);

                List <string> featureFields = new List <string>();
                foreach (DataColumn column in openSHP.GetColumns())
                {
                    featureFields.Add(column.ColumnName);
                }


                int featureIndex = 0;
                foreach (var currentFeature in openSHP.Features)
                {
                    //current geature attributes
                    GH_Path currentPath       = new GH_Path(featureIndex);
                    var     currentAttributes = currentFeature.DataRow;
                    foreach (var attr in currentAttributes.ItemArray)
                    {
                        string thisAttribute = Convert.ToString(attr);
                        if (thisAttribute == " " || thisAttribute == "" || thisAttribute == null)
                        {
                            thisAttribute = "nan";
                        }
                        GH_String thisGhAttribute = new GH_String(thisAttribute);
                        attributes.Append(thisGhAttribute, currentPath);
                    }
                    //end current feature attributes

                    var coordinates = currentFeature.Coordinates;


                    for (int pathIndex = 0; pathIndex <= currentFeature.NumGeometries - 1; pathIndex++)                           //for each path in the feature
                    {
                        List <GH_Point> thisPathPoints = new List <GH_Point>();                                                   //coordinate list for this path
                        foreach (DotSpatial.Topology.Coordinate coord in currentFeature.GetBasicGeometryN(pathIndex).Coordinates) //for each node in path
                        {
                            //int X = coord.X;
                            //int Y = coord.Y
                            //make point and add to this path
                            Point3d  thisPoint   = new Point3d((double)coord.X, (double)coord.Y, 0);
                            GH_Point thisGhPoint = new GH_Point(thisPoint);
                            thisPathPoints.Add(thisGhPoint);
                        }//end for each  nodes
                        GH_Path thisPath = new GH_Path(featureIndex, pathIndex);
                        featureGeometry.AppendRange(thisPathPoints, thisPath);//Add this path to the feature tree
                    } //end for goes in feature
                    featureIndex++;
                }     //end while features\
                DA.SetDataList(0, featureFields);
                DA.SetDataTree(1, attributes);
                DA.SetDataTree(2, featureGeometry);
            }//end if read
        }
예제 #26
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object can be used to retrieve data from input parameters and
        /// to store data in output parameters.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Setup inputs
            string path = "";

            if (!DA.GetData("File Path", ref path))
            {
                return;
            }
            Vector3d vec = new Vector3d(0, 0, 0);

            DA.GetData("Vector", ref vec);

            // Setup output
            DataTree <Point3d> ptTree   = new DataTree <Point3d>();
            DataTree <string>  keysTree = new DataTree <string>();
            DataTree <string>  valsTree = new DataTree <string>();

            // Open shapefile from path
            Shapefile shp    = Shapefile.OpenFile(path);
            string    prjStr = shp.ProjectionString;
            string    prj    = shp.Projection.ToString();

            //Read features in the shapefile
            int pathCount = 0;

            foreach (Feature f in shp.Features)
            {
                // Get values for each feature
                GH_Path       p       = new GH_Path(pathCount);
                DataRow       dataRow = f.DataRow;
                List <string> vals    = new List <string>();
                foreach (object item in dataRow.ItemArray)
                {
                    vals.Add(item.ToString());
                }
                valsTree.AddRange(vals, p);



                // Get keys for each feature
                DataTable            table   = dataRow.Table;
                DataColumnCollection columns = table.Columns;
                DataColumn[]         dca     = new DataColumn[columns.Count];
                columns.CopyTo(dca, 0);
                List <string> keys = new List <string>();
                foreach (DataColumn col in dca)
                {
                    keys.Add(col.ColumnName.ToString());
                }
                keysTree.AddRange(keys, p);


                // Get pts for each feature and transform by user input vector
                List <Point3d> pts = new List <Point3d>();

                IList <DotSpatial.Topology.Coordinate> coords = f.Coordinates;
                foreach (DotSpatial.Topology.Coordinate coord in coords)
                {
                    Point3d pt = new Point3d(coord.X + vec.X, coord.Y + vec.Y, 0 + vec.Z);
                    pts.Add(pt);
                }
                ptTree.AddRange(pts, p);

                // Increment path
                pathCount++;
            }

            //Output the data
            DA.SetDataTree(0, keysTree);
            DA.SetDataTree(1, valsTree);
            DA.SetDataTree(2, ptTree);
            DA.SetData(3, prjStr);
            DA.SetData(4, prj);
        }
예제 #27
0
 /// <summary>
 /// This open method is only called if this plugin has been given priority for one
 /// of the file extensions supported in the DialogReadFilter property supplied by
 /// this control. Failing to provide a DialogReadFilter will result in this plugin
 /// being added to the list of DataProviders being supplied under the Add Other Data
 /// option in the file menu.
 /// </summary>
 /// <param name="fileName">A string specifying the complete path and extension of the file to open.</param>
 /// <returns>The opend feature set.</returns>
 public virtual IFeatureSet Open(string fileName)
 {
     return(Shapefile.OpenFile(fileName));
 }
예제 #28
0
        public static QrTestResult TestQRCode(this string qrCode, string districtsShapefile, bool checkOnline = true, double xCoord = double.NaN, double yCoord = double.NaN, bool checkForDuplicates = false)
        {
            var qrTestResult = new QrTestResult();

            if (QRCodes == null && checkForDuplicates == true)
            {
                QRCodes = new List <string>();
            }

            if (String.IsNullOrEmpty(qrCode))
            {
                qrTestResult.AddMessage("No QR-code to test: " + qrCode);
                return(qrTestResult);
            }

            if (Districts == null)
            {
                qrTestResult.AddMessage("Loading districts from Shapefile (once per session): " + districtsShapefile);
                Districts = Shapefile.OpenFile(districtsShapefile);
            }

            string mBaseURL, mMunicipalityAbbreviation, mAreaAbbreviation = "", mRoadID, mSignType, mAUSNumber;

            qrTestResult.AddMessage("Decoded QR code content: " + qrCode);

            qrTestResult.QrCode = qrCode;

            var mRegex = Regex.Match(qrCode, @"http://([a-z\.]*)/([A-Za-z]*)/([A-Za-z]*)/([0-9]*)/([a-zA-Z0-9]*)/([0-9]*)$");

            if (mRegex.Groups.Count != 7)
            {
                qrTestResult.AddMessage("Error: QR code has wrong structure for ANS sign: " + (mRegex.Groups.Count - 1) + " parts, should be 6");
                qrTestResult.StructureOk = false;
                qrTestResult.HasIssue    = true;
                qrTestResult.SignType    = QrTestResult.TypeOfSign.Unknown;
            }
            else
            {
                qrTestResult.AddMessage("Info: QR code has correct structure for ANS sign");
                qrTestResult.StructureOk = true;
                qrTestResult.SignType    = QrTestResult.TypeOfSign.AddressUnitNumber;
                mBaseURL = mRegex.Groups[1].ToString();
                mMunicipalityAbbreviation = mRegex.Groups[2].ToString();
                mAreaAbbreviation         = mRegex.Groups[3].ToString();
                mRoadID    = mRegex.Groups[4].ToString();
                mSignType  = mRegex.Groups[5].ToString();
                mAUSNumber = mRegex.Groups[6].ToString();
            }

            // Check for existence of QR-code in processed batch
            if (checkForDuplicates == true && QRCodes.Contains(qrCode.Trim().ToLower()))
            {
                qrTestResult.AddMessage("QR-code already exists (duplicate): " + qrCode);
                qrTestResult.IsDuplicate = true;
                qrTestResult.HasIssue    = true;
            }
            else
            {
                QRCodes.Add(qrCode.Trim().ToLower());
                qrTestResult.IsDuplicate = false;
            }

            // Check for correct start of QR code
            if (!qrCode.StartsWith("http://myabudhabi.net/adm"))
            {
                qrTestResult.AddMessage("Error: base URL or municipality");
                qrTestResult.UriOk    = false;
                qrTestResult.HasIssue = true;
            }
            else
            {
                qrTestResult.AddMessage("Info: URL part is ok");
                qrTestResult.UriOk = true;
            }

            // Check if codes contains spaces
            if (qrCode.Contains(" "))
            {
                qrTestResult.AddMessage("Error: QR Code contains spaces");
                qrTestResult.SpacesOk = false;
                qrTestResult.HasIssue = true;
            }
            else
            {
                qrTestResult.AddMessage("Info: Contains no spaces");
                qrTestResult.SpacesOk = true;
            }

            // Check if code exists on myabudhabi.net
            MyAbuDhabiNetResponse mResponse = null;

            if (checkOnline)
            {
                if (HasInternetConnection())
                {
                    mResponse = qrCode.DownloadLandingPage().Data as MyAbuDhabiNetResponse;
                    if (mResponse == null || mResponse.status != "success")
                    {
                        qrTestResult.AddMessage("Notice: The QR-code does not exist on myabudhabi.net");
                        qrTestResult.IsOnline = QrTestResult.OnlineStatus.Unavailable;
                        qrTestResult.HasIssue = true;
                    }
                    else
                    {
                        qrTestResult.AddMessage(String.Format("Info: Exists on myabudhabi.net (Longitude: {0}/Latitude: {1}){2}",
                                                              mResponse.x,
                                                              mResponse.y,
                                                              Environment.NewLine));
                        qrTestResult.IsOnline = QrTestResult.OnlineStatus.Available;
                    }
                }
                else
                {
                    qrTestResult.AddMessage("Either the computer is not connected to the Internet or there is a problem with the connection");
                    qrTestResult.IsOnline = QrTestResult.OnlineStatus.Unknown;
                }
            }
            else
            {
                qrTestResult.IsOnline = QrTestResult.OnlineStatus.Unknown;
            }

            // Check if inside district
            Point mPointGeom = null;

            if (xCoord != double.NaN || yCoord != double.NaN)
            {
                mPointGeom = new Point(xCoord, yCoord);
                qrTestResult.HasCoordinates = true;
            }
            else if (mResponse != null)
            {
                double mX, mY;

                if (!double.TryParse(mResponse.x, out mX) || !double.TryParse(mResponse.y, out mY))
                {
                    qrTestResult.AddMessage("Notice: Coordinate values could not be parsed to a number or records on myabudhabi.net does not contain coordinates");
                    qrTestResult.HasCoordinates = false;
                    qrTestResult.HasIssue       = true;
                }
                else
                {
                    var            mPoints  = new double[] { mX, mY };
                    ProjectionInfo pSRSFrom = KnownCoordinateSystems.Geographic.World.WGS1984;
                    ProjectionInfo pSRSTo   = KnownCoordinateSystems.Projected.World.WebMercator;
                    Reproject.ReprojectPoints(mPoints, new double[] { 0 }, pSRSFrom, pSRSTo, 0, 1);
                    mPointGeom = new Point(mPoints[0], mPoints[1]);
                    qrTestResult.HasCoordinates = true;
                }
            }

            if (mPointGeom != null)
            {
                foreach (Feature mFeature in Districts.Features)
                {
                    if (mFeature.Contains(mPointGeom))
                    {
                        if (mFeature.DataRow["DISTRICTABB"].ToString().ToLower().Trim() == mAreaAbbreviation.ToLower())
                        {
                            qrTestResult.AddMessage(String.Format("Info: District abbreviation is correct according to coordinates: {0} ({1}){2}",
                                                                  mFeature.DataRow["NAMELATIN"].ToString(),
                                                                  mFeature.DataRow["DISTRICTABB"].ToString().ToLower(),
                                                                  Environment.NewLine));
                            qrTestResult.DistrictOk = true;
                        }
                        else
                        {
                            qrTestResult.AddMessage(String.Format("Error: District abbreviation is wrong according to coordinates; it is: {1} but should be {0}{2}",
                                                                  mFeature.DataRow["DISTRICTABB"].ToString().ToLower(),
                                                                  mAreaAbbreviation,
                                                                  Environment.NewLine));
                            qrTestResult.DistrictOk = false;
                            qrTestResult.HasIssue   = true;
                        }
                        break;
                    }
                }
            }

            return(qrTestResult);
        }
예제 #29
0
        public HttpResponseMessage UploadMapShape()
        {
            HttpResponseMessage result = null;
            int bcount = 0;

            try
            {
                var httpRequest = HttpContext.Current.Request;

                PROJECT_IMPACT importInfo = null;

                if (httpRequest.Form.Count > 0)
                {
                    var imageInfo = httpRequest.Form["ImageInfo"];
                    if (imageInfo != null)
                    {
                        importInfo = (new System.Web.Script.Serialization.JavaScriptSerializer()).Deserialize <PROJECT_IMPACT>(imageInfo);
                    }
                }



                List <Geometry> geometries = new List <Geometry>(0);
                if (httpRequest.Files.Count > 0)
                {
                    string sessionID = Guid.NewGuid().ToString();



                    var docfiles = new List <string>();
                    foreach (string file in httpRequest.Files)
                    {
                        var postedFile = httpRequest.Files[file];

                        string targetFolder = $@"{HttpContext.Current.Server.MapPath("~")}UploadShape\{sessionID}";
                        if (!System.IO.Directory.Exists(targetFolder))
                        {
                            System.IO.Directory.CreateDirectory(targetFolder);
                        }

                        /*save file from client*/
                        var zipFilePath = $@"{targetFolder}\{postedFile.FileName}";
                        postedFile.SaveAs(zipFilePath);
                        docfiles.Add(zipFilePath);

                        /*extract zip file*/
                        var extractFilePath = $"{targetFolder}";
                        System.IO.Compression.ZipFile.ExtractToDirectory(zipFilePath, extractFilePath, System.Text.Encoding.UTF8);

                        /*process unzip file*/

                        var zipDirs = System.IO.Directory.GetDirectories(targetFolder);
                        zipDirs.ToList().ForEach(zipDir =>
                        {
                            var dirs = System.IO.Directory.GetDirectories(zipDir);
                            dirs.ToList().ForEach(dir =>
                            {
                                var loop = true;
                                /*search shape file*/
                                while (loop)
                                {
                                    loop      = false;
                                    var files = System.IO.Directory.GetFiles(dir, "*.shp", System.IO.SearchOption.AllDirectories);
                                    /*if dbf file not found then search shp*/
                                    if (files.Count() == 0)
                                    {
                                        files = System.IO.Directory.GetFiles(dir, "*.dbf", System.IO.SearchOption.AllDirectories);
                                    }

                                    files.ToList().ForEach(f =>
                                    {
                                        var fileInfo = new System.IO.FileInfo(f);

                                        try
                                        {
                                            Shapefile indexMapFile = Shapefile.OpenFile(f);
                                            indexMapFile.Reproject(KnownCoordinateSystems.Geographic.Asia.Indian1975);



                                            TDM.Models.Util.LatLngUTMConverter latLngUTMConverter = new TDM.Models.Util.LatLngUTMConverter("WGS 84");
                                            //var rr = latLngUTMConverter.convertLatLngToUtm(15.000095111201411, 100.64638250268084);

                                            string utmShape = "";
                                            foreach (IFeature feature in indexMapFile.Features)
                                            {
                                                if (feature != null && feature.Geometry != null)
                                                {
                                                    utmShape = feature.Geometry.Coordinates
                                                               .Select(coordinate => latLngUTMConverter.convertLatLngToUtm(coordinate.Y, coordinate.X))
                                                               .Select(utm => $"{utm.Easting} {utm.Northing}")
                                                               .Aggregate((current, next) => current + ", " + next);

                                                    geometries.Add(new Geometry()
                                                    {
                                                        //Shape = feature.Geometry.ToString(),
                                                        Shape    = $"{feature.Geometry.OgcGeometryType.ToString().ToUpper()} (({utmShape}))",
                                                        AREA     = Convert.ToDecimal(feature.DataRow["AREA"]),
                                                        ORIGIN_X = feature.DataRow["ORIGIN_X"].ToString(),
                                                        ORIGIN_Y = feature.DataRow["ORIGIN_Y"].ToString()
                                                    });
                                                }
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            string k = "";
                                        }
                                    });
                                }
                            });
                        });
                    }


                    /*save data*/

                    importInfo.ID   = 0;
                    importInfo.Area = geometries.Sum(g => g.AREA);
                    PROJECT_IMPACT saveProject = tdmEntities.PROJECT_IMPACT.Add(importInfo);
                    tdmEntities.SaveChanges();

                    foreach (var geometry in geometries)
                    {
                        if (!geometry.Shape.Contains("MULTIPO"))
                        {
                            tdmEntities.PROJECT_IMPACT_GEOMETRY.Add(new PROJECT_IMPACT_GEOMETRY()
                            {
                                ProjectImpactID = importInfo.ID,
                                OriginX         = geometry.ORIGIN_X,
                                OriginY         = geometry.ORIGIN_Y,
                                Area            = geometry.AREA,
                                Shape           = (geometry.Shape.Contains("MULTIPO")) ? DbGeometry.MultiPolygonFromText(geometry.Shape, 4326) : DbGeometry.PolygonFromText(geometry.Shape, 4326),
                                UpdateDate      = DateTime.Now,
                                CreateDate      = DateTime.Now
                            });
                        }
                    }

                    tdmEntities.SaveChanges();

                    result = Request.CreateResponse(HttpStatusCode.Created, "Success");
                }
                else
                {
                    result = Request.CreateResponse(HttpStatusCode.BadRequest);
                }
            }
            catch (Exception exc)
            {
                result = Request.CreateResponse(HttpStatusCode.InternalServerError, exc.Message);
            }

            return(result);
        }
예제 #30
0
        public void NumericColumnAsDoubleTest()
        {
            var shapeFile = Shapefile.OpenFile(Path.Combine(_shapefiles, @"OGR-numeric\ogr-numeric.shp"));

            Assert.AreEqual("System.Double", shapeFile.DataTable.Columns[2].DataType.FullName);
        }