Example #1
0
        public void Multipg()
        {
            Random rnd = new Random();
            Polygon[] pg = new Polygon[50];
            GeoAPI.Geometries.IPolygon[] pgcheck = new GeoAPI.Geometries.IPolygon[50];
            GisSharpBlog.NetTopologySuite.Geometries.GeometryFactory gf = new GisSharpBlog.NetTopologySuite.Geometries.GeometryFactory();
            for (int i = 0; i < 50; i++)
            {
                Coordinate center = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90);
                Coordinate[] coord = new Coordinate[36];
                GeoAPI.Geometries.ICoordinate[] coordscheck = new GeoAPI.Geometries.ICoordinate[36];
                for (int ii = 0; ii < 36; ii++)
                {
                    coord[ii] = new Coordinate(center.X + Math.Cos((ii * 10) * Math.PI / 10), center.Y + (ii * 10) * Math.PI / 10);
                    double x = coord[ii].X;
                    double y = coord[ii].Y;
                    GisSharpBlog.NetTopologySuite.Geometries.Coordinate c = new GisSharpBlog.NetTopologySuite.Geometries.Coordinate(x, y);
                    coordscheck[ii] = c;
                }
                coord[35] = new Coordinate(coord[0].X, coord[0].Y);
                coordscheck[35] = new GisSharpBlog.NetTopologySuite.Geometries.Coordinate(coordscheck[0].X, coordscheck[0].Y);
                GeoAPI.Geometries.ILinearRing ring = gf.CreateLinearRing(coordscheck);
                pgcheck[i] = gf.CreatePolygon(ring, null);
                pg[i] = new Polygon(coord);

            }
            MultiPolygon mpg = new MultiPolygon(pg);
            GeoAPI.Geometries.IMultiPolygon mpgcheck = gf.CreateMultiPolygon(pgcheck);
            for (int ii = 0; ii < mpg.Coordinates.Count; ii++)
            {
                Assert.AreEqual(mpg.Coordinates[ii].X, mpgcheck.Coordinates[ii].X);
                Assert.AreEqual(mpg.Coordinates[ii].Y, mpgcheck.Coordinates[ii].Y);
            }
        }
Example #2
0
        private void MpgCS(object sender, EventArgs e)
        {
            Random rnd = new Random();
            Polygon[] pg = new Polygon[50];
            for (int i = 0; i < 50; i++)
            {
                Coordinate center = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90);
                Coordinate[] coord = new Coordinate[36];
                for (int ii = 0; ii < 36; ii++)
                {
                    coord[ii] = new Coordinate(center.X + Math.Cos((ii * 10) * Math.PI / 10), center.Y + (ii * 10) * Math.PI / 10);
                }
                coord[35] = new Coordinate(coord[0].X, coord[0].Y);
                pg[i] = new Polygon(coord);
            }
            MultiPolygon mpg = new MultiPolygon(pg);

            FeatureSet fs = new FeatureSet(mpg.FeatureType);
            fs.Features.Add(mpg);
            fs.SaveAs("C:\\Temp\\mpg.shp", true);
        }
Example #3
0
        public void shpWrite(string path)
        {
            fs.DataTable.Columns.Add(new DataColumn("ID", typeof(int)));
            DataColumn col = new DataColumn("Project", typeof(string));
            col.MaxLength = 50;
            fs.DataTable.Columns.Add(col);
            fs.DataTable.Columns.Add(new DataColumn("Area", typeof(double)));
            IFeatureSet fsource = FeatureSet.Open(@"Sample\Sample.shp");
            fs.Projection = fsource.Projection;
            fsource.Close();
            int ID = 0;
            foreach (Geometries geometry in project.Geometries) {
                ID++;
                Polygon[] pgs = new Polygon[geometry.Polygons.Count];
                int i = 0;
                //foreach (Geometries geometry in project.Geometries) {

                foreach (GeoPolygon polygon in geometry.Polygons) {
                    List<Coordinate> vertices = new List<Coordinate>();

                    //polygon.Points.Reverse();

                    if (polygon.Circle>1&&!polygon.GetDirection()) {
                        polygon.Points.Reverse();
                    } else if (polygon.Circle==1&&polygon.GetDirection()) {
                        polygon.Points.Reverse();
                    }

                    foreach (GeoPoint point in polygon.Points) {
                        Coordinate vertice = new Coordinate();
                        vertice.X = point.X;
                        vertice.Y = point.Y;
                        vertices.Add(vertice);
                    }

                    Polygon geom = new Polygon(vertices);

                    pgs[i] = geom;

                    i++;
                }
                //}

                MultiPolygon geoms = new MultiPolygon(pgs);
                geoms.ToText();
                IFeature feature = fs.AddFeature(geoms);
                feature.DataRow.BeginEdit();
                feature.DataRow["ID"] = ID;
                feature.DataRow["Project"] = project.Name;
                //feature.DataRow["Area"] = feature.Area();
                feature.DataRow.EndEdit();
            }
            //fs.Projection = ProjectionInfo.(@"F:\数据\2013SHP\DLTB.shp");
            //fs.ProjectionString = " +x_0=40500000 +y_0=0 +lat_0=0 +lon_0=120 +proj=tmerc +a=6378140 +b=6356755.28815753 +no_defs";

            fs.SaveAs(path, true);

            fs.Dispose();
            GeoRead gr = new GeoRead(path);
            gr.shpAreaReCalculate();
            //fs = FeatureSet.Open(path);
        }
        /// <summary>
        /// Exports the selected database to fieldAttributes filegeodatabase
        /// </summary>
        /// <param name="pOnlyApproved"></param>
        /// <returns></returns>
        public static FeatureSet GetDistrictsFeatureSetFromAdmAdrMdb(ref ToolStripProgressBar pPgBar, string pMdbFile, int pOnlyApproved = 0)
        {
            // Setup SQL string to select all or only some streets
            string mSql;

            if (pOnlyApproved == 1)
            {
                mSql = "SELECT OBJECTID, ABBREVIATION, NAMEENGLISH, NAMEARABIC, NAMEPOPULARENGLISH, NAMEPOPULARARABIC, APPROVED FROM ADRDISTRICT WHERE APPROVED = 'Y'";
            }
            else
            {
                mSql = "SELECT OBJECTID, ABBREVIATION, NAMEENGLISH, NAMEARABIC, NAMEPOPULARENGLISH, NAMEPOPULARARABIC, APPROVED FROM ADRDISTRICT";
            }

            // Setup fieldAttributes dictionary to hold road names
            var mDistrictNames = new Dictionary <int, DataRow>();

            // Connect to database and load names
            var mOdbcConn    = new OdbcConnection("Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=" + pMdbFile + ";Uid=Admin;Pwd=;");
            var mDataAdapter = new OdbcDataAdapter(mSql, mOdbcConn);
            var mDataTable   = new DataTable();

            mDataAdapter.Fill(mDataTable);
            int ctr1   = 0;
            int total1 = mDataTable.Rows.Count;

            pPgBar.Value = ctr1;
            foreach (DataRow mRow in mDataTable.Rows)
            {
                if (mDistrictNames.Keys.Contains(mRow["OBJECTID"].ToInt()))
                {
                    Utilities.LogDebug("Key " + mRow["OBJECTID"].ToInt() + " already exists in districts");
                }
                mDistrictNames.Add(mRow["OBJECTID"].ToInt(), mRow);
                ctr1++;
                if (ctr1 % 100 == 0)
                {
                    double mFraction1 = (((double)ctr1 / (double)total1) * 100);
                    pPgBar.ProgressBar.Value = (int)(Math.Round(mFraction1));
                    Application.DoEvents();
                }
            }

            Debug.WriteLine("Done loading district names");
            Debug.WriteLine(ctr1);
            mOdbcConn.Close();
            mDataAdapter = null;
            mOdbcConn    = null;

            // Connect to database using OGR to load geometries
            var mDriver = Ogr.GetDriverByName("PGeo");

            if (mDriver == null)
            {
                return(null);
            }

            Debug.WriteLine("Loaded driver");
            var mSource = mDriver.Open(pMdbFile, 0);

            if (mSource == null)
            {
                return(null);
            }

            Debug.WriteLine("Loaded datasource");
            var mLayer = mSource.GetLayerByName("ADRDISTRICT");

            //Debug.WriteLine("Set attribute filter");
            if (mLayer == null)
            {
                return(null);
            }
            Debug.WriteLine("Loaded layer");

            // Create simplified roads
            var mDistrict = new District();

            int mTotal2 = mLayer.GetFeatureCount(1);

            Debug.WriteLine("Number of features" + mTotal2);

            pPgBar.Value = 0;
            OSGeo.OGR.Feature mFeature;

            int mFeatureIndex = 0;

            while (null != (mFeature = mLayer.GetNextFeature()))
            {
                if (mFeature == null)
                {
                    Debug.WriteLine("Feature #{0} is null", mFeatureIndex);
                }
                else
                {
                    OSGeo.OGR.Geometry mGeometry = mFeature.GetGeometryRef();
                    if (mGeometry != null)
                    {
                        mGeometry.FlattenTo2D();
                        byte[] mWkb = new Byte[mGeometry.WkbSize()];
                        string mWkt = "";
                        mGeometry.ExportToWkb(mWkb);
                        mGeometry.ExportToWkt(out mWkt);

                        IMultiPolygon mPolygon;

                        int mDistrictObjectId = mFeature.GetFieldAsInteger("OBJECTID");

                        if (mDistrictObjectId > 0)
                        {
                            var       mWkbReader = new WkbReader();
                            IGeometry mGeom      = mWkbReader.Read(mWkb);
                            if (mGeom.GetType() == typeof(DotSpatial.Topology.MultiPolygon))
                            {
                                var mPolygons = new List <Polygon>();
                                mPolygons.Add(mGeom as Polygon);

                                var mPolygonsN = new List <Polygon>();
                                foreach (var mPart in mPolygons)
                                {
                                    if (mPart != null)
                                    {
                                        mPolygonsN.Add(mPart);
                                    }
                                }
                                mPolygon = new DotSpatial.Topology.MultiPolygon(mPolygonsN.ToArray <Polygon>());
                            }
                            else
                            {
                                mPolygon = mGeom as IMultiPolygon;
                            }

                            if (mDistrictNames.ContainsKey(mDistrictObjectId))
                            {
                                var mDistrictName = mDistrictNames[mDistrictObjectId];


                                var mDistrictAbbreviation = mDistrictName["ABBREVIATION"].ToString();
                                var mNameArabic           = mDistrictName["NAMEARABIC"].ToString();
                                var mNameLatin            = mDistrictName["NAMEENGLISH"].ToString();
                                var mNamePopularArabic    = mDistrictName["NAMEPOPULARARABIC"].ToString();
                                var mNamePopularLatin     = mDistrictName["NAMEPOPULARENGLISH"].ToString();
                                var mApproved             = mDistrictName["APPROVED"].ToString();
                                mDistrict.AddNewRow(mGeom, mDistrictObjectId, mDistrictAbbreviation, mNameArabic, mNameLatin, mNamePopularArabic, mNamePopularLatin, mApproved);
                            }
                            else
                            {
                                Debug.WriteLine("No matching abbreviation");
                            }
                        }
                        else
                        {
                            Debug.WriteLine("No abbreviation");
                        }
                    }
                    else
                    {
                        Debug.WriteLine("No geometry");
                    }
                }

                if (mFeatureIndex % (mTotal2 / 20) == 0)
                {
                    double mFraction = (double)mFeatureIndex / (double)mTotal2;
                    int    mProgress = (int)Math.Round(mFraction * 100);
                    pPgBar.ProgressBar.Value = mProgress;
                    Application.DoEvents();
                }
                mFeatureIndex++;
            }

            mDistrict.UpdateExtent();
            Debug.WriteLine("Done creating districts...");
            return(mDistrict);
        }
Example #5
0
        public void AddGrid(IList<IFeature> selected, Dictionary<int, Stat> data, Dictionary<int, RGB> dataRGB)
        {
            this.data = data;
            if (pro != null)
            {
                pro.Value = 0;
                pro.Maximum = 1000;
                pro.Visible = true;
            }

            _GridLayer.DataSet.Features.Clear();

            Int32 id = 0;

            for (int i = 0; i < _area.NumColumns; i++)
            {
                for (int j = 0; j < _area.NumRows; j++)
                {

                    int val = 1000 * id / (_area.NumColumns * _area.NumRows);

                    if (pro != null)
                    {
                        pro.Value = val;
                        //  pro.Increment(val);
                    }
                    Coordinate[] array = new Coordinate[5];


                    array[0] = ProjectPointAzimut(new Coordinate(_area.MinX + (i * _area.CellSizeX), _area.MinY + (j * _area.CellSizeY)));
                    Coordinate start = array[0];
                    array[1] = ProjectPointAzimut(new Coordinate(_area.MinX + ((i + 1) * _area.CellSizeX), _area.MinY + (j * _area.CellSizeY)));
                    array[2] = ProjectPointAzimut(new Coordinate(_area.MinX + ((i + 1) * _area.CellSizeX), _area.MinY + ((j + 1) * _area.CellSizeY)));
                    array[3] = ProjectPointAzimut(new Coordinate(_area.MinX + (i * _area.CellSizeX), _area.MinY + ((j + 1) * _area.CellSizeY)));
                    array[4] = start;

                    LinearRing shell = new LinearRing(array);
                    IGeometry poly = new Polygon(shell);
                    bool contain = true;
                    if (selected != null && selected.Count > 0)
                    {
                        IFeature newF = null;
                        foreach (IFeature fea in selected)
                        {
                            try
                            {
                                if (!fea.Contains(poly))
                                {

                                    if (fea.Intersects((IGeometry)poly))
                                    {
                                        IGeometry newF1 = null;
                                        MultiPolygon poly1 = null;
                                        poly1 = new MultiPolygon(fea);
                                        newF1 = poly.Difference((IGeometry)poly1);
                                        poly = newF1;
                                    }
                                }
                                else
                                    contain = false;
                            }
                            catch
                            {

                            }
                        }

                        if (contain)
                        {
                            newF = _GridLayer.DataSet.AddFeature(poly);
                            newF.DataRow["polygonID"] = id;
                            newF.DataRow["row"] = j + 1;
                            newF.DataRow["col"] = i + 1;
                        }

                        id++;
                    }
                    else
                    {
                        IFeature newF = _GridLayer.DataSet.AddFeature(poly);
                        newF.DataRow["polygonID"] = id;
                        newF.DataRow["row"] = j + 1;
                        newF.DataRow["col"] = i + 1;
                        int idcel = _area.NumColumns * ((j + 1) - 1) + (i + 1);
                        newF.DataRow["Value"] = data[idcel].Mean;
                        newF.DataRow["Number"] = data[idcel].num;
                        newF.DataRow["R"] = dataRGB[idcel].R.Mean;
                        newF.DataRow["G"] = dataRGB[idcel].G.Mean;
                        newF.DataRow["B"] = dataRGB[idcel].B.Mean;


                        id++;

                    }

                }
            }
            rectangleFs = (FeatureSet)_GridLayer.DataSet;
            _mainMap.ResetBuffer();
            if (pro != null) pro.Visible = false;

        }
        /// <summary>
        /// Get delineated watershed polygon from EPA WebServices
        /// </summary>
        /// <param name="uri">Query string</param>
        /// <returns>Returns an IFeatureSet including the delineated polygon</returns>
        private object[] GetDelineation(string uri)
        {
            //Declare a WebClient instance to get the Watershed Delineation response string
            WebClient delineate = new WebClient();

            try
            {
                string response = delineate.DownloadString(uri);

                int start = response.IndexOf("(");
                int end = response.LastIndexOf(")");

                response = response.Substring(start + 1, end - 1 - start);

                //Declare Json Elements
                JObject mainObj = new JObject();
                JToken outputObj = new JObject();
                JToken shapeObj = new JObject();
                JToken statusObj = new JObject();

                mainObj = JObject.Parse(response);

                outputObj = mainObj["output"];

                //check for error message in outputObj
                if (outputObj.Type == Newtonsoft.Json.Linq.JTokenType.Null)
                {
                    statusObj = mainObj["status"];
                    string statusMessage = statusObj["status_message"].ToString();
                    throw new ArgumentException(statusMessage);
                }

                shapeObj = outputObj["shape"];

                string stype = shapeObj["type"].ToString();
                string area = outputObj["total_areasqkm"].ToString();

                JArray coordArray = shapeObj["coordinates"] as JArray;

                //For coordinate information
                string lat;
                string lon;

                //Setup projection information
                _defaultProjection = KnownCoordinateSystems.Projected.World.WebMercator;

                //Initialize feature parameters
                Feature polyf = new Feature();
                Feature multipolyf = new Feature();
                IFeatureSet polyfs = new FeatureSet(FeatureType.Polygon);

                //For the case GeoJSON returns a MultiPolygon
                if (stype.Trim().ToLower() == "multipolygon")
                {
                    foreach (JArray Polycoord in coordArray) //The third level branket
                    {
                        Polygon[] polys = new Polygon[Polycoord.Count];

                        if (Polycoord != null)
                        {
                            for (int i = 0; i < Polycoord.Count; i++)//The second level branket
                            {
                                JArray multiRingcoord = (JArray)Polycoord[i];

                                IList<Coordinate> multicoords = new List<Coordinate>();

                                if (multiRingcoord != null)
                                {
                                    foreach (JArray latlongcoord in multiRingcoord) //The first level branket
                                    {
                                        Coordinate coord = new Coordinate();

                                        lon = latlongcoord[0].ToString();
                                        lat = latlongcoord[1].ToString();

                                        coord.X = Convert.ToDouble(lon);
                                        coord.Y = Convert.ToDouble(lat);

                                        double[] xy = new double[2];
                                        xy[0] = coord.X;
                                        xy[1] = coord.Y;

                                        double[] z = new double[1];

                                        coord.X = xy[0];
                                        coord.Y = xy[1];

                                        multicoords.Add(coord);
                                    }

                                    polys[i] = new Polygon(multicoords);
                                }
                            }

                            //Save polygon[] into a multipolygon
                            if (polys.Length > 1)
                            {
                                IMultiPolygon multipolys = new MultiPolygon(polys);

                                multipolyf = new Feature(multipolys);
                            }
                            else
                            {
                                // special case: A multipolygon with one part
                                multipolyf = new Feature(polys[0]);
                            }

                            //Save features into a featureset
                            if (polyfs.Features.Count == 0)
                            {
                                polyfs = new FeatureSet(multipolyf.FeatureType);
                                polyfs.Projection = WGS84;
                                polyfs.AddFeature(multipolyf);
                            }

                            else
                            {
                                polyfs.Projection = WGS84;
                                polyfs.AddFeature(multipolyf);
                            }
                        }
                    }
                }

                //For the case GeoJSON returns a Polygon
                if (stype.Trim().ToLower() == "polygon")
                {
                    foreach (JArray Ringcoord in coordArray)  //The second level branket
                    {
                        IList<Coordinate> coords = new List<Coordinate>();

                        if (Ringcoord != null)
                        {
                            foreach (JArray latlongcoord in Ringcoord) //The first level branket
                            {
                                Coordinate coord = new Coordinate();

                                lon = latlongcoord[0].ToString();
                                lat = latlongcoord[1].ToString();

                                coord.X = Convert.ToDouble(lon);
                                coord.Y = Convert.ToDouble(lat);

                                double[] xy = new double[2];
                                xy[0] = coord.X;
                                xy[1] = coord.Y;

                                double[] z = new double[1];

                                coord.X = xy[0];
                                coord.Y = xy[1];

                                coords.Add(coord);
                            }

                            polyfs.Projection = WGS84; // _defaultProjection;
                            polyf = new Feature(FeatureType.Polygon, coords);
                        }

                        polyfs = new FeatureSet(polyf.FeatureType);

                        if (polyfs.Features.Count == 0)
                        {
                            polyfs = new FeatureSet(polyf.FeatureType);
                            polyfs.Projection = WGS84;
                            polyfs.AddFeature(polyf);
                        }

                        else
                        {
                            polyfs.Projection = WGS84;
                            polyfs.AddFeature(polyf);
                        }
                    }
                }

                object[] watersheds = new object[2];

                watersheds[0] = polyfs;
                watersheds[1] = area;

                return watersheds;
            }
            catch (NullReferenceException ex)
            {
                var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
                {
                    Content = new StringContent(ex.Message),
                    ReasonPhrase = "Watershed not found. Please try a different point."
                };

                throw new HttpResponseException(resp);
            }

            catch (Exception ex)
            {
                var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
                {
                    Content = new StringContent(ex.Message),
                    ReasonPhrase = "Error searching for watershed."
                };

                throw new HttpResponseException(resp);
            }
        }