Beispiel #1
0
        public FeatureSet PopulateFromTable()
        {
            DataTable pTable = this.GetTable(sqlStatements.selectAddressUnitsSQL);

            foreach (DataRow mRow in pTable.Rows)
            {
                var mXY = ExtFunctions.GetXYFromRow(mRow);
                if (mXY != null)
                {
                    var mPoint   = new DotSpatial.Topology.Point(mXY[0], mXY[1]);
                    var mFeature = this.AddFeature(mPoint);
                    mFeature.DataRow.BeginEdit();

                    mFeature.DataRow["ADDRESSUNITID"]   = mFeature.Fid;
                    mFeature.DataRow["ROADID"]          = mRow["road_id"].ToString();
                    mFeature.DataRow["ADDRESSUNITNR"]   = mRow["addressUnitNumber"].ToString();
                    mFeature.DataRow["ROADNAME_EN"]     = "";
                    mFeature.DataRow["ROADNAME_AR"]     = "";
                    mFeature.DataRow["ROADNAME_POP_EN"] = "";
                    mFeature.DataRow["ROADNAME_POP_AR"] = "";
                    mFeature.DataRow["DISTRICTID"]      = mRow["district_id"].ToString();
                    mFeature.DataRow["MUNICIPALITY_EN"] = Utilities.LABEL_ABUDHABI_EN;
                    mFeature.DataRow["MUNICIPALITY_AR"] = Utilities.LABEL_ABUDHABI_AR;
                    mFeature.DataRow["QR_CODE"]         = this.GetQRCode(mRow, pTable);
                    mFeature.DataRow.EndEdit();
                }
            }
            return(this);
        }
        public FeatureSet PopulateFromTable()
        {
            DataTable pTable = this.GetTable(sqlStatements.selectAddressGuideSignsSQL);

            foreach (DataRow mRow in pTable.Rows)
            {
                var mXY = ExtFunctions.GetXYFromRow(mRow);
                if (mXY != null)
                {
                    var mPoint   = new DotSpatial.Topology.Point(mXY[0], mXY[1]);
                    var mFeature = this.AddFeature(mPoint);

                    mFeature.DataRow.BeginEdit();

                    mFeature.DataRow["ADDRESSGUIDESIGNID"] = mRow["id"];
                    mFeature.DataRow["QR_CODE"]            = this.GetQRCode(mRow, pTable);
                    mFeature.DataRow["SIGNTYPE"]           = mRow["signType"];
                    mFeature.DataRow["SERIALNUMBER"]       = mRow["serialNumberOfSign"];
                    mFeature.DataRow["AUNRANGE"]           = mRow["addressUnitRange"];
                    mFeature.DataRow["ROADID"]             = mRow["road_id"];
                    mFeature.DataRow["DISTRICTID"]         = mRow["district_id"];
                    mFeature.DataRow.EndEdit();
                }
            }

            return(this);
        }
        public static List <String> GetDistrictByPoint(this IMapLayer pLyr, double x, double y)
        {
            var mNameEN = "";
            var mNameAR = "";

            if (pLyr.LegendText == "Districts")
            {
                var mPoint = new DotSpatial.Topology.Point(x, y);

                var tLyr = (IFeatureLayer)pLyr;

                foreach (DotSpatial.Data.Feature mF in tLyr.DataSet.Features)
                {
                    if (mF.Contains(mPoint))
                    {
                        mNameEN = mF.DataRow["NAMELATIN"].ToString();
                        mNameAR = mF.DataRow["NAMEARABIC"].ToString();
                        break;
                    }
                }
            }
            return(new List <String>()
            {
                mNameEN, mNameAR
            });
        }
        public RuleSymbolizerPreview()
        {
            InitializeComponent();
            mapPreview.Projection = DotSpatial.Projections.KnownCoordinateSystems.Geographic.World.WGS1984;
            featureSetPoint.Projection = DotSpatial.Projections.KnownCoordinateSystems.Geographic.World.WGS1984;
            featureSetLine.Projection = DotSpatial.Projections.KnownCoordinateSystems.Geographic.World.WGS1984;
            featureSetPolygon.Projection = DotSpatial.Projections.KnownCoordinateSystems.Geographic.World.WGS1984;
            DotSpatial.Topology.LineString ls = new DotSpatial.Topology.LineString(new Coordinate[] { new Coordinate(-45D, 0D), new Coordinate(45D, 0D) });
            featureSetLine.AddFeature(ls);
            DotSpatial.Topology.Polygon polygon = new DotSpatial.Topology.Polygon(new LinearRing(new Coordinate[] {
                new Coordinate(90, -25), new Coordinate(135, -25), new Coordinate(135,25),new Coordinate(90, 25),new Coordinate(90, -25)
            }));
            featureSetPolygon.AddFeature(polygon);

            DotSpatial.Topology.Point point = new DotSpatial.Topology.Point(new Coordinate(-90D, 0D));
            featureSetPoint.AddFeature(point);

            layerPoint = new MapPointLayer(featureSetPoint);
            layerLine = new MapLineLayer(featureSetLine);
            layerPolygon = new MapPolygonLayer(featureSetPolygon);
               // layerPoint.Symbolizer = new DotSpatial.Symbology.PointSymbolizer(System.Drawing.Color.DarkBlue, DotSpatial.Symbology.PointShape.Triangle, 20);

            mapPreview.Layers.Add(layerLine);
            mapPreview.Layers.Add(layerPolygon);
            mapPreview.Layers.Add(layerPoint);
            this.SizeChanged += RuleSymbolizerPreview_SizeChanged;
            mapPreview.ViewExtents = new Extent(-180, -180, 180, 180);
            mapPreview.ViewExtents.SetCenter(new Coordinate(0, 0));
        }
        /// <summary>
        /// Converts a WGS-84 Lat/Long coordinate to the tile XY of the tile containing
        /// that point at the given levelOfDetail
        /// </summary>
        /// <param name="coord">WGS-84 Lat/Long</param>
        /// <param name="levelOfDetail">Level of detail, from 1 (lowest detail)
        /// to 23 (highest detail).  </param>
        /// <returns>Tile XY Point</returns>
        public static MWPoint LatLongToTileXY(Coordinate coord, int levelOfDetail)
        {
            MWPoint pixelXY = LatLongToPixelXY(coord.Y, coord.X, levelOfDetail);
            MWPoint tileXY  = PixelXYToTileXY(pixelXY);

            return(tileXY);
        }
        public void GetShapefile(string filepath)
        {
            FeatureSet fs = new FeatureSet(FeatureType.Point);

            fs.DataTable.Columns.Add(new DataColumn("ID", typeof(string)));
            fs.DataTable.Columns.Add(new DataColumn("Name", typeof(string)));
            fs.DataTable.Columns.Add(new DataColumn("Lat", typeof(double)));
            fs.DataTable.Columns.Add(new DataColumn("Lon", typeof(double)));
            fs.DataTable.Columns.Add(new DataColumn("Contam", typeof(string)));
            fs.DataTable.Columns.Add(new DataColumn("Trend", typeof(double)));
            fs.DataTable.Columns.Add(new DataColumn("Trending", typeof(string)));
            fs.DataTable.Columns.Add(new DataColumn("Rsquared", typeof(double)));
            fs.DataTable.Columns.Add(new DataColumn("MCL", typeof(double)));
            fs.DataTable.Columns.Add(new DataColumn("Units", typeof(string)));
            fs.DataTable.Columns.Add(new DataColumn("NumSamp", typeof(int)));
            fs.DataTable.Columns.Add(new DataColumn("LastDate", typeof(string)));
            fs.DataTable.Columns.Add(new DataColumn("Result", typeof(double)));
            fs.DataTable.Columns.Add(new DataColumn("Link", typeof(string)));



            for (int a = 0; a < WellList.Count; a++)
            {
                int        c        = WellList[a].GetTopTrendIndex(3);
                Coordinate vertices = new Coordinate();
                vertices.X = WellList[a].LonDouble[c];
                vertices.Y = WellList[a].LatDouble[c];
                DotSpatial.Topology.Point Geom = new DotSpatial.Topology.Point(vertices);
                fs.AddFeature(Geom);
                fs.DataTable.Rows[a].BeginEdit();
                fs.DataTable.Rows[a]["ID"]       = WellList[a].ID;
                fs.DataTable.Rows[a]["Name"]     = WellList[a].Names[c];
                fs.DataTable.Rows[a]["Lat"]      = WellList[a].LatDouble[c];
                fs.DataTable.Rows[a]["Lon"]      = WellList[a].LonDouble[c];
                fs.DataTable.Rows[a]["Contam"]   = WellList[a].Contaminate;
                fs.DataTable.Rows[a]["Trending"] = WellList[a].Trending[c];
                fs.DataTable.Rows[a]["Trend"]    = WellList[a].Trends[c];
                fs.DataTable.Rows[a]["Rsquared"] = WellList[a].R2[c];
                fs.DataTable.Rows[a]["MCL"]      = WellList[a].MCL;
                fs.DataTable.Rows[a]["Units"]    = WellList[a].Latest[c].UNITS;
                fs.DataTable.Rows[a]["NumSamp"]  = WellList[a].SampsByName[c].Count;
                fs.DataTable.Rows[a]["LastDate"] = WellList[a].RecentSampleDate[c];
                fs.DataTable.Rows[a]["Result"]   = WellList[a].Results[c];
                fs.DataTable.Rows[a]["Link"]     = WellList[a].ChartURL[c];
                fs.DataTable.Rows[a].EndEdit();
            }

            fs.Projection =
                KnownCoordinateSystems.Geographic.NorthAmerica.NorthAmericanDatum1983;

            fs.SaveAs(savepath, true);

            //IFeatureSet buff = new FeatureSet();
            //buff = fs.Buffer(.003, true);
            //string filepathB = filepath.Replace(".shp", "buffer.shp");
            //buff.Projection =
            //KnownCoordinateSystems.Geographic.NorthAmerica.NorthAmericanDatum1983;
            //buff.SaveAs(filepathB, true);
        }
        // Sample code that demonstrates how to buffer a randomly generated point.
        public static void BufferingAPoint()
        {
            Coordinate coords = new Coordinate();
            Random     rnd    = new Random();

            coords = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90);
            DotSpatial.Topology.Point p = new DotSpatial.Topology.Point(coords);
            //This will get the area of the buffer.
            double area = p.Buffer(500).Area;
        }
Beispiel #8
0
        public static void CreatingANewPoint()
        {
            //creates a new coordinate
            Coordinate c = new Coordinate(2.4, 2.4);

            //passes the coordinate to a new point
            DotSpatial.Topology.Point p = new DotSpatial.Topology.Point(c);
            //displayes the new point's x and y coordiantes
            Console.WriteLine("Point p is: x= " + p.X + " & y= " + p.Y);
        }
        /// <summary>
        /// Converts a point from latitude/longitude WGS-84 coordinates (in degrees)
        /// into pixel XY coordinates at a specified level of detail.
        /// </summary>
        /// <param name="latitude">Latitude of the point, in degrees.</param>
        /// <param name="longitude">Longitude of the point, in degrees.</param>
        /// <param name="levelOfDetail">Level of detail, from 1 (lowest detail)
        /// to 23 (highest detail).  </param>
        public static MWPoint LatLongToPixelXY(double latitude, double longitude, int levelOfDetail)
        {
            latitude  = Clip(latitude, MinLatitude, MaxLatitude);
            longitude = Clip(longitude, MinLongitude, MaxLongitude);

            var x           = (longitude + 180) / 360;
            var sinLatitude = Math.Sin(latitude * Math.PI / 180);
            var y           = 0.5 - Math.Log((1 + sinLatitude) / (1 - sinLatitude)) / (4 * Math.PI);

            var mapSize = MapSize(levelOfDetail);

            var pixelXY = new MWPoint
            {
                X = (int)Clip(x * mapSize + 0.5, 0, mapSize - 1),
                Y = (int)Clip(y * mapSize + 0.5, 0, mapSize - 1)
            };

            return(pixelXY);
        }
Beispiel #10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="envelope"></param>
        /// <param name="bounds"></param>
        /// <returns></returns>
        public Tile[,] GetTiles(Envelope envelope, Rectangle bounds)
        {
            Coordinate mapTopLeft     = envelope.TopLeft();
            Coordinate mapBottomRight = envelope.BottomRight();

            //Clip the coordinates so they are in the range of the web mercator projection
            mapTopLeft.Y = TileCalculator.Clip(mapTopLeft.Y, TileCalculator.MinLatitude, TileCalculator.MaxLatitude);
            mapTopLeft.X = TileCalculator.Clip(mapTopLeft.X, TileCalculator.MinLongitude, TileCalculator.MaxLongitude);

            mapBottomRight.Y = TileCalculator.Clip(mapBottomRight.Y, TileCalculator.MinLatitude, TileCalculator.MaxLatitude);
            mapBottomRight.X = TileCalculator.Clip(mapBottomRight.X, TileCalculator.MinLongitude, TileCalculator.MaxLongitude);

            int zoom = TileCalculator.DetermineZoomLevel(envelope, bounds);

            Point topLeftTileXY  = TileCalculator.LatLongToTileXY(mapTopLeft, zoom);
            Point btmRightTileXY = TileCalculator.LatLongToTileXY(mapBottomRight, zoom);

            var tileMatrix = new Tile[(int)(btmRightTileXY.X - topLeftTileXY.X) + 1, (int)(btmRightTileXY.Y - topLeftTileXY.Y) + 1];

            Parallel.For((int)topLeftTileXY.Y, (int)btmRightTileXY.Y + 1,
                         y => Parallel.For((int)topLeftTileXY.X, (int)btmRightTileXY.X + 1,
                                           x =>
            {
                var currTopLeftPixXY = TileCalculator.TileXYToTopLeftPixelXY(x, y);
                var currTopLeftCoord = TileCalculator.PixelXYToLatLong((int)currTopLeftPixXY.X,
                                                                       (int)currTopLeftPixXY.Y, zoom);

                var currBtmRightPixXY = TileCalculator.TileXYToBottomRightPixelXY(x,
                                                                                  y);
                var currBtmRightCoord = TileCalculator.PixelXYToLatLong((int)currBtmRightPixXY.X,
                                                                        (int)currBtmRightPixXY.Y, zoom);

                var currEnv = new Envelope(currTopLeftCoord, currBtmRightCoord);

                var tile = GetTile(x, y, currEnv, zoom);
                tileMatrix[x - (int)topLeftTileXY.X, y - (int)topLeftTileXY.Y] = tile;
            }
                                           ));

            return(tileMatrix);
        }
        /// <summary>
        /// Overloaded method for rendering point data on map
        /// </summary>
        /// <param name="MyRemainingFacets"></param>
        private void PutReturnOnMap(IEnumerable <FacetedSearch3.CUAHSIFacetedSearch.SiteData> MyRemainingFacets)
        {
            ClearPointLayersFromMap();
            FeatureSet fs = new FeatureSet(FeatureType.Point);

            fs.Projection = KnownCoordinateSystems.Geographic.World.WGS1984;

            foreach (FacetedSearch3.CUAHSIFacetedSearch.SiteData o in MyRemainingFacets)
            {
                DotSpatial.Topology.Point p = new DotSpatial.Topology.Point();
                p.X = o.longitude;
                p.Y = o.latitude;
                fs.AddFeature(p);
            }

            fs.Filename = FacetedShapeFileName;
            fs.Save();

            App.Map.AddLayer(FacetedShapeFileName);
            // map1.Layers.Add(MyLocations);
        }
        private void GpsDataPointToFeatureRow(int tagID, FeatureSet fs, FtTransmitterGpsDataEntry gpsPoint)
        {
            DotSpatial.Topology.Point point = null;
            if (!gpsPoint.Rechtswert.HasValue || !gpsPoint.Hochwert.HasValue)
            {
                point = new DotSpatial.Topology.Point(double.NaN, double.NaN);
            }
            else
            {
                point = new DotSpatial.Topology.Point(gpsPoint.Rechtswert.Value, gpsPoint.Hochwert.Value);
            }
            var feature = fs.AddFeature(point);

            feature.DataRow.BeginEdit();
            feature.DataRow["TagID"]     = tagID;
            feature.DataRow["Timestamp"] = gpsPoint.StartTimestamp;
            if (gpsPoint.TimestampOfFix.HasValue)
            {
                feature.DataRow["TimestampOfFix"] = gpsPoint.TimestampOfFix;
            }
            feature.DataRow["UsedTimeToGetFix"] = gpsPoint.UsedTimeToGetFix;
            if (gpsPoint.HeightAboveEllipsoid.HasValue)
            {
                feature.DataRow["HeightAboveEllipsoid"] = gpsPoint.HeightAboveEllipsoid.Value;
            }
            if (gpsPoint.HeadingDegree.HasValue)
            {
                feature.DataRow["HeadingDegree"] = gpsPoint.HeadingDegree.Value;
            }
            if (gpsPoint.SpeedOverGround.HasValue)
            {
                feature.DataRow["SpeedOverGround"] = gpsPoint.SpeedOverGround.Value;
            }
            feature.DataRow["Status"]              = gpsPoint.Status;
            feature.DataRow["BatteryVoltage"]      = gpsPoint.BatteryVoltage;
            feature.DataRow["BatteryVoltageAtFix"] = gpsPoint.BatteryVoltageFix;
            feature.DataRow["Temperature"]         = gpsPoint.Temperature;

            feature.DataRow.EndEdit();
        }
Beispiel #13
0
        public FeatureSet PopulateFromTable()
        {
            DataTable pTable = this.GetTable(sqlStatements.selectStreetNameSignsSQL);

            foreach (DataRow mRow in pTable.Rows)
            {
                var mXY = ExtFunctions.GetXYFromRow(mRow);
                if (mXY != null)
                {
                    var mPoint   = new DotSpatial.Topology.Point(mXY[0], mXY[1]);
                    var mFeature = this.AddFeature(mPoint);

                    var mF = mFeature.DataRow;

                    mF.BeginEdit();

                    mF["STREETNAMESIGNID"] = mRow["id"];
                    mF["QR_CODE"]          = this.GetQRCode(mRow, pTable);
                    mF["SERIALNUMBER"]     = mRow["serialNumberOfSign"];
                    mF["SIGNTYPE"]         = mRow["signType"];
                    mF["AUNRANGE_P1"]      = mRow["addressUnitRange_p1"];
                    mF["ROADID_P1"]        = mRow["road_id_p1"];
                    mF["DISTRICTID_P1"]    = mRow["district_id_p1"];
                    mF["CLEARANCE_P1"]     = mRow["signpanelgroundclearance_p1"];
                    mF["SIZE_P1"]          = mRow["signPanelDimensions_p1"];
                    mF["AUNRANGE_P2"]      = mRow["addressUnitRange_p2"];
                    mF["ROADID_P2"]        = mRow["road_id_p2"];
                    mF["DISTRICTID_P2"]    = mRow["district_id_p2"];
                    mF["CLEARANCE_P2"]     = mRow["signpanelgroundclearance_p2"];
                    mF["SIZE_P2"]          = mRow["signPanelDimensions_p2"];
                    mF["DISTRICT_EN"]      = "";
                    mF["DISTRICT_AR"]      = "";
                    mF.EndEdit();
                }
            }
            return(this);
        }
Beispiel #14
0
        private void ExcelDatasetToLayer()
        {
            try
            {
                if (_excelDataset != null)
                {
                    var excelTable = _excelDataset.Tables[0];

                    if (excelTable.Columns.Contains("lat") & excelTable.Columns.Contains("long"))
                    {
                        FeatureSet fs = new FeatureSet(FeatureType.Point);
                        fs.Projection = KnownCoordinateSystems.Geographic.World.WGS1984;

                        // Set columns of attribute table
                        fs.DataTable = excelTable.Clone();

                        foreach (DataRow excelRow in excelTable.Rows)
                        {
                            string lat = (excelRow["lat"].ToString());
                            string lon = (excelRow["long"].ToString());

                            if (!string.IsNullOrEmpty(lat) && !string.IsNullOrEmpty(lon))
                            {
                                // Add the point to the FeatureSet
                                Coordinate coord = new Coordinate(Double.Parse(lon), Double.Parse(lat));
                                DotSpatial.Topology.Point point = new DotSpatial.Topology.Point(coord);
                                IFeature feature = fs.AddFeature(point);

                                // Bring over all of the data as attribute data.
                                for (int i = 0; i <= excelTable.Columns.Count - 1; i++)
                                {
                                    feature.DataRow[i] = excelRow[i];
                                }
                            }
                        }

                        foreach (var item in fieldsList.Where(c => c.isChecked == false))
                        {
                            fs.DataTable.Columns.Remove(item.Field);
                        }

                        var shapePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TempFiles", Path.GetFileNameWithoutExtension(_filePath) + ".shp");

                        if (!Directory.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TempFiles")))
                            Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TempFiles"));

                        fs.SaveAs(shapePath, true);

                        PluginExtension.MyAppManager.Map.Layers.Add(shapePath);
                    }
                    else
                    {
                        MessageBox.Show("The excel file must have lat and long columns.");
                    }
                }
                else
                {
                    MessageBox.Show("Please provide file.");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #15
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="point"></param>
 /// <param name="envelope"></param>
 /// <param name="zoom"></param>
 /// <returns></returns>
 public Tile GetTile(Point point, Envelope envelope, int zoom)
 {
     return(GetTile((int)point.X, (int)point.Y, envelope, zoom));
 }
Beispiel #16
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="point"></param>
 /// <param name="envelope"></param>
 /// <param name="zoom"></param>
 /// <returns></returns>
 public Tile GetTile(Point point, Envelope envelope, int zoom)
 {
     return GetTile((int)point.X, (int)point.Y, envelope, zoom);
 }
Beispiel #17
0
        public void HandleRow(string textline)
        {
            Hashtable rs = _aisParser.Parse(textline);

            if (rs != null)
            {
                if (rs.ContainsKey("MessageType"))
                {
                    switch ((uint)rs["MessageType"])
                    {
                    case 1:
                    case 2:
                    case 3:
                        double[] pointCoords = { (double)rs["Longitude"], (double)rs["Latitude"] };
                        double[] z           = { 0 };

                        if (!_projectionInfo.Equals(KnownCoordinateSystems.Geographic.World.WGS1984))
                        {
                            Reproject.ReprojectPoints(pointCoords, z, KnownCoordinateSystems.Geographic.World.WGS1984, _projectionInfo, 0, 1);
                        }

                        Coordinate coord = new Coordinate(pointCoords[0], pointCoords[1]);
                        IFeature   feature;

                        List <int> results = VesselsFeatureSet.Find(string.Format("[MMSI]={0}", rs["MMSI"]));
                        if (results != null && results.Any())
                        {
                            feature = VesselsFeatureSet.GetFeature(results[0]);
                            feature.Coordinates[0] = coord;
                        }
                        else
                        {
                            DotSpatial.Topology.Point point = new DotSpatial.Topology.Point(coord);
                            feature = VesselsFeatureSet.AddFeature(point);
                        }

                        //
                        // Fix values outside range
                        if (double.IsInfinity((double)rs["CourseOverGround"]) || double.IsNaN((double)rs["CourseOverGround"]))
                        {
                            rs["CourseOverGround"] = 0F;
                        }
                        if (double.IsInfinity((double)rs["SpeedOverGround"]) || double.IsNaN((double)rs["SpeedOverGround"]))
                        {
                            rs["SpeedOverGround"] = 0F;
                        }

                        foreach (DictionaryEntry item in rs)
                        {
                            feature.DataRow[item.Key.ToString()] = item.Value;
                        }

                        break;

                    case 5:
                        break;

                    default:
                        break;
                    }
                }
            }
        }
        /// <summary>
        /// Given an ArcGIS Online URL, create a DotSpatial in-memory feature set
        /// </summary>
        /// <param name="url">The ArcGIS Online URL</param>
        /// <returns>a feature set that can be added to the map</returns>
        public static IFeatureSet GetFeatures(string url)
        {
            //(1) form the url query
            string[] fieldNames = new string[] { "Latitude",
                                                 "Longitude", "SiteName", "SiteCode", "VarCode", "VarName", "ServCode",
                                                 "watermluri", "StartDate", "EndDate" };
            string queryUri = GenerateQueryUri(url, fieldNames);

            using (WebClient wc = new WebClient())
            {
                try
                {
                    string response = wc.DownloadString(queryUri);
                    int    len      = response.Length;

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

                    mainObj  = JObject.Parse(response);
                    shapeObj = mainObj["features"] as JArray;

                    //initialize feature set
                    FeatureSet fs = new FeatureSet(FeatureType.Point);
                    //attr table
                    fs.DataTable.Columns.Add(new DataColumn("Latitude", typeof(double)));
                    fs.DataTable.Columns.Add(new DataColumn("Longitude", typeof(double)));
                    fs.DataTable.Columns.Add(new DataColumn("SiteName", typeof(string)));
                    fs.DataTable.Columns.Add(new DataColumn("SiteCode", typeof(string)));
                    fs.DataTable.Columns.Add(new DataColumn("VarCode", typeof(string)));
                    fs.DataTable.Columns.Add(new DataColumn("VarName", typeof(string)));
                    fs.DataTable.Columns.Add(new DataColumn("ServCode", typeof(string)));
                    fs.DataTable.Columns.Add(new DataColumn("WaterMLURI", typeof(string)));
                    fs.DataTable.Columns.Add(new DataColumn("StartDate", typeof(string)));
                    fs.DataTable.Columns.Add(new DataColumn("EndDate", typeof(string)));

                    foreach (JObject feature in shapeObj)
                    {
                        JObject atrList = feature["attributes"] as JObject;

                        double latitude   = Convert.ToDouble(atrList["Latitude"]);
                        double longitude  = Convert.ToDouble(atrList["Longitude"]);
                        string siteCode   = Convert.ToString(atrList["SiteCode"]);
                        string varCode    = Convert.ToString(atrList["VarCode"]);
                        string varName    = Convert.ToString(atrList["VarName"]);
                        string startDate  = Convert.ToString(atrList["StartDate"]);
                        string endDate    = Convert.ToString(atrList["EndDate"]);
                        string siteName   = Convert.ToString(atrList["SiteName"]);
                        string servCode   = Convert.ToString(atrList["ServCode"]);
                        string waterMLURI = Convert.ToString(atrList["WaterMLURI"]);

                        DotSpatial.Topology.Point pt = new DotSpatial.Topology.Point(longitude, latitude);

                        IFeature f = fs.AddFeature(pt);

                        DataRow r = f.DataRow;

                        r["Latitude"]   = latitude;
                        r["Longitude"]  = longitude;
                        r["SiteCode"]   = siteCode;
                        r["VarCode"]    = varCode;
                        r["VarName"]    = varName;
                        r["ServCode"]   = servCode;
                        r["WaterMLURI"] = waterMLURI;
                        r["SiteName"]   = siteName;
                        r["StartDate"]  = startDate;
                        r["EndDate"]    = endDate;
                    }

                    //fs.Projection = KnownCoordinateSystems.Geographic.World.WGS1984);

                    return(fs);

                    //outputObj = mainObj["output"] as JsonObject;
                    //shapeObj = outputObj["shape"] as JsonObject;
                }
                catch (WebException ex)
                {
                    MessageBox.Show(ex.Message);
                }
                return(null);
            }
        }
        /// <summary>
        /// Creates shapefile from search results, shows shapefile on map display
        /// </summary>
        /// <param name="SeriesCatalogResults"></param>
        private void PutReturnOnMap(IEnumerable <FacetedSearch3.CUAHSIFacetedSearch.SeriesCatalogRecord> SeriesCatalogResults)
        {
            FeatureSet fs = new FeatureSet(FeatureType.Point);

            try
            {
                ClearPointLayersFromMap();

                // string shapeFileName = String.Format(@"{0}\{1}.shp", Settings.Instance.TempDirectory, "FacetedSearchResult");

                fs.DataTable.Columns.Add(new DataColumn("ServiceCode", typeof(string)));
                fs.DataTable.Columns.Add(new DataColumn("ServiceURL", typeof(string)));
                fs.DataTable.Columns.Add(new DataColumn("SiteCode", typeof(string)));
                fs.DataTable.Columns.Add(new DataColumn("SiteName", typeof(string))); //to improve display of labels and pop-up. shows a copy of SiteCode
                fs.DataTable.Columns.Add(new DataColumn("VarCode", typeof(string)));
                fs.DataTable.Columns.Add(new DataColumn("VarName", typeof(string)));  //to improve display of labels and pop-up. shows a copy of VarCode
                fs.DataTable.Columns.Add(new DataColumn("StartDate", typeof(DateTime)));
                fs.DataTable.Columns.Add(new DataColumn("EndDate", typeof(DateTime)));
                fs.DataTable.Columns.Add(new DataColumn("ValueCount", typeof(int)));

                foreach (FacetedSearch3.CUAHSIFacetedSearch.SeriesCatalogRecord o in SeriesCatalogResults)
                {
                    DotSpatial.Topology.Point p = new DotSpatial.Topology.Point(o.Longitude, o.Latitude);
                    IFeature f = fs.AddFeature(p);
                    f.DataRow.BeginEdit();
                    f.DataRow["ServiceCode"] = o.ServCode;
                    f.DataRow["ServiceURL"]  = o.ServURL;
                    f.DataRow["SiteCode"]    = o.SiteCode;
                    f.DataRow["SiteName"]    = o.SiteName;
                    f.DataRow["VarCode"]     = o.VarCode;
                    f.DataRow["VarName"]     = o.VariableName;
                    f.DataRow["StartDate"]   = o.StartDate;
                    f.DataRow["EndDate"]     = o.EndDate;
                    f.DataRow["ValueCount"]  = o.ValueCount;
                    f.DataRow.EndEdit();
                }

                //set the projection
                fs.Projection =
                    new ProjectionInfo();
                fs.ProjectionString = "+proj=longlat +ellps=WGS84 +no_defs";

                // the faceted search shapefile is saved to the current project directory
                // preferably this should be in the current project's directory
                // if the current project directory doesn't exist then use a temp folder
                string facetedSearchShapefileFullPath;
                if (App.SerializationManager.CurrentProjectDirectory == null)
                {
                    string hdTempPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "HydroDesktop");
                    facetedSearchShapefileFullPath = System.IO.Path.Combine(hdTempPath, FacetedShapeFileName);
                }
                else
                {
                    facetedSearchShapefileFullPath = System.IO.Path.Combine(App.SerializationManager.CurrentProjectDirectory, FacetedShapeFileName);
                }
                fs.Filename = facetedSearchShapefileFullPath;
                fs.Save();

                // implement threshold for adding to map directly or via shapefile on disk?
                if (SeriesCatalogResults.Count <FacetedSearch3.CUAHSIFacetedSearch.SeriesCatalogRecord>() > 25000)
                {
                }
                else
                {
                }

                // need to use the full path (relative path didn't work when deploying
                // the plugin as a package)
                App.Map.AddLayer(facetedSearchShapefileFullPath);
            }
            finally
            {
                fs.Dispose();
            }

            //add featureSet to the map
            // IMapLayer newLayer = MapArgs.Map.Layers.Add(shapeFileName);

            //add labels
            // MapArgs.Map.AddLabels((IFeatureLayer)newLayer,
            // String.Format("[{0}]", "FacetedSearchResults"), String.Empty,
            //     new LabelSymbolizer());
        }
Beispiel #20
0
        private bool DrawMonitorMap()
        {
            try
            {
                IFeatureSet fsPoints = new FeatureSet();
                fsPoints.DataTable.Columns.Add("Name");
                fsPoints.DataTable.Columns.Add("Description");
                fsPoints.DataTable.Columns.Add("Longitude");
                fsPoints.DataTable.Columns.Add("Latitude");
                string[] tmps = new string[_lstMonitorPoints[0].dicMetricValues.Count];
                _lstMonitorPoints[0].dicMetricValues.Keys.CopyTo(tmps, 0);
                for (int i = 0; i < tmps.Length; i++)
                {
                    fsPoints.DataTable.Columns.Add(tmps[i]);
                }
                MonitorValue      mv            = null;
                Feature           feature       = null;
                List <Coordinate> lstCoordinate = new List <Coordinate>();
                List <double>     fsInter       = new List <double>();
                mainMap.Layers.Clear();
                mainMap.ProjectionModeReproject = ActionMode.Never;
                mainMap.ProjectionModeDefine    = ActionMode.Never;
                mainMap.Layers.Clear();
                if (File.Exists(this._gridShapeFile))
                {
                    mainMap.Layers.Add(this._gridShapeFile);
                }
                if (this._lstMonitorPoints != null && this.LstMonitorPoints.Count > 0)
                {
                    PolygonScheme   myScheme = new PolygonScheme();
                    PolygonCategory pcin     = new PolygonCategory();
                    pcin.Symbolizer.SetFillColor(Color.Red);
                    myScheme.Categories.Add(pcin);
                    DotSpatial.Topology.Point point;
                    for (int i = 0; i < LstMonitorPoints.Count; i++)
                    {
                        mv      = LstMonitorPoints[i];
                        point   = new DotSpatial.Topology.Point(mv.Longitude, mv.Latitude);
                        feature = new Feature(point);

                        fsPoints.AddFeature(feature);

                        fsPoints.DataTable.Rows[i]["Name"]      = mv.MonitorName;
                        fsPoints.DataTable.Rows[i]["Latitude"]  = mv.Latitude;
                        fsPoints.DataTable.Rows[i]["Longitude"] = mv.Longitude;
                        for (int col = 0; col < tmps.Length; col++)
                        {
                            fsPoints.DataTable.Rows[i][tmps[col]] = mv.dicMetricValues[tmps[col]];
                        }
                    }
                    mainMap.Layers.Add(fsPoints);
                    mainMap.Layers[0].LegendText = "Air quality grid";
                    mainMap.Layers[1].LegendText = "Monitors";
                }
                PolygonLayer      player      = mainMap.Layers[0] as PolygonLayer;
                float             f           = 0.9f;
                Color             c           = Color.Transparent;
                PolygonSymbolizer Transparent = new PolygonSymbolizer(c);
                Transparent.OutlineSymbolizer = new LineSymbolizer(Color.DarkBlue, 1); player.Symbolizer = Transparent;
                LayerObject = null;
                return(true);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                return(false);
            }
        }
        private static Point GetPoint(SqlGeometry sqlPoint)
        {
            var point = new Point(GetCoordinate(sqlPoint));

            return(point);
        }
Beispiel #22
0
 /// <summary>
 /// Converts pixel XY coordinates into tile XY coordinates of the tile containing
 /// the specified pixel.
 /// </summary>
 /// <param name="point">Pixel X,Y point.</param>
 public static MWPoint PixelXYToTileXY(MWPoint point)
 {
     return PixelXYToTileXY((int)point.X, (int)point.Y);
 }
        private void testQRCodesOfSelectedLayerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                IFeatureLayer mLayer;
                string        mDistrictsShapefile = Application.StartupPath + "/GisData/districts.shp";

                // Empty the list of processed QR-codes
                QRLib.ResetQRCodes();

                var mQrTestResults = new List <QrTestResult>();

                if (null == (mLayer = ExtFunctions.GetSelectedPointLayer(theMap)))
                {
                    Log("The selected layer is not a point feature");
                    return;
                }
                else
                {
                    dlgSaveFile.FileName = DateTime.Now.ToString("yyyyMMdd") + "-qrtest.log.xlsx";
                    dlgSaveFile.Title    = "Please select a log file location (optional)";
                    dlgSaveFile.Filter   = "Excel log files|*.log.xslx";
                    if (dlgSaveFile.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                    {
                        QRLib.setLogFile(dlgSaveFile.FileName);
                    }
                    bool HasQRCode = false;
                    foreach (var mColumn in mLayer.DataSet.GetColumns())
                    {
                        if (mColumn.ColumnName == "QR_CODE")
                        {
                            HasQRCode = true;
                            break;
                        }
                    }
                    if (!HasQRCode)
                    {
                        Log("No QR code in selected layer");
                    }
                    else
                    {
                        foreach (var mFeature in mLayer.DataSet.Features)
                        {
                            var mQRCode = mFeature.DataRow["QR_CODE"].ToString();
                            if (mFeature.FeatureType == FeatureType.Point)
                            {
                                DotSpatial.Topology.Point mPoint = (DotSpatial.Topology.Point)mFeature.BasicGeometry;
                                var mResult = mQRCode.TestQRCode(mDistrictsShapefile, false, mPoint.X, mPoint.Y, true);
                                if (mResult.HasIssue)
                                {
                                    Log(mResult);
                                }
                                mQrTestResults.Add(mResult);
                            }
                            else
                            {
                                var mResult = mQRCode.TestQRCode(
                                    districtsShapefile: mDistrictsShapefile,
                                    checkForDuplicates: true);
                                Log(mResult);
                                mQrTestResults.Add(mResult);
                            }
                            Application.DoEvents();
                        }
                    }

                    using (var mCsvWriter = new CsvHelper.CsvWriter(new ExcelSerializer(dlgSaveFile.FileName)))
                    {
                        mCsvWriter.WriteRecords(mQrTestResults);
                        Log("Processed " + mQrTestResults.Count + " records...");
                        Log("Wrote output to " + dlgSaveFile.FileName + "...");
                        Log("Operation completed");
                    }
                }
            }
            catch (Exception ex)
            {
                Log("Operation aborted: " + ex.Message);
            }
        }
Beispiel #24
0
 /// <summary>
 /// Converts pixel XY coordinates into tile XY coordinates of the tile containing
 /// the specified pixel.
 /// </summary>
 /// <param name="point">Pixel X,Y point.</param>
 public static MWPoint PixelXYToTileXY(MWPoint point)
 {
     return(PixelXYToTileXY((int)point.X, (int)point.Y));
 }
        private void map1_MouseDown(object sender, MouseEventArgs e)
        {
            switch (shapeType)
            {
            case "Point":
                if (e.Button == MouseButtons.Left)
                {
                    if ((pointmouseClick))
                    {
                        //This method is used to convert the screen cordinate to map coordinate
                        //e.location is the mouse click point on the map control
                        Coordinate coord = map1.PixelToProj(e.Location);

                        //Create a new point
                        //Input parameter is clicked point coordinate
                        DotSpatial.Topology.Point point = new DotSpatial.Topology.Point(coord);

                        //Add the point into the Point Feature
                        //assigning the point feature to IFeature because via it only we can set the attributes.
                        IFeature currentFeature = pointF.AddFeature(point);

                        //increase the point id
                        pointID = pointID + 1;

                        //set the ID attribute
                        currentFeature.DataRow["PointID"] = pointID;

                        //refresh the map
                        map1.ResetBuffer();
                    }
                }
                else
                {
                    //mouse right click
                    map1.Cursor     = Cursors.Default;
                    pointmouseClick = false;
                }

                break;

            case "line":
                if (e.Button == MouseButtons.Left)
                {
                    //left click - fill array of coordinates
                    //coordinate of clicked point
                    Coordinate coord = map1.PixelToProj(e.Location);
                    if (linemouseClick)
                    {
                        //first time left click - create empty line feature
                        if (firstClick)
                        {
                            //Create a new List called lineArray.
                            //This list will store the Coordinates
                            //We are going to store the mouse click coordinates into this array.
                            List <Coordinate> lineArray = new List <Coordinate>();

                            //Create an instance for LineString class.
                            //We need to pass collection of list coordinates
                            LineString lineGeometry = new LineString(lineArray);

                            //Add the linegeometry to line feature
                            IFeature lineFeature = lineF.AddFeature(lineGeometry);

                            //add first coordinate to the line feature
                            lineFeature.Coordinates.Add(coord);
                            //set the line feature attribute
                            lineID = lineID + 1;
                            lineFeature.DataRow["LineID"] = lineID;
                            firstClick = false;
                        }
                        else
                        {
                            //second or more clicks - add points to the existing feature
                            IFeature existingFeature = lineF.Features[lineF.Features.Count - 1];
                            existingFeature.Coordinates.Add(coord);

                            //refresh the map if line has 2 or more points
                            if (existingFeature.Coordinates.Count >= 2)
                            {
                                lineF.InitializeVertices();
                                map1.ResetBuffer();
                            }
                        }
                    }
                }
                else
                {
                    //right click - reset first mouse click
                    firstClick = true;
                    map1.ResetBuffer();
                }
                break;

            case "polygon":

                if (e.Button == MouseButtons.Left)
                {
                    //left click - fill array of coordinates
                    Coordinate coord = map1.PixelToProj(e.Location);

                    if (polygonmouseClick)
                    {
                        //first time left click - create empty line feature
                        if (firstClick)
                        {
                            //Create a new List called polygonArray.

                            //this list will store the Coordinates
                            //We are going to store the mouse click coordinates into this array.

                            List <Coordinate> polygonArray = new List <Coordinate>();

                            //Create an instance for LinearRing class.
                            //We pass the polygon List to the constructor of this class
                            LinearRing polygonGeometry = new LinearRing(polygonArray);

                            //Add the polygonGeometry instance to PolygonFeature
                            IFeature polygonFeature = polygonF.AddFeature(polygonGeometry);

                            //add first coordinate to the polygon feature
                            polygonFeature.Coordinates.Add(coord);

                            //set the polygon feature attribute
                            polygonID = polygonID + 1;
                            polygonFeature.DataRow["PolygonID"] = polygonID;
                            firstClick = false;
                        }
                        else
                        {
                            //second or more clicks - add points to the existing feature
                            IFeature existingFeature = (IFeature)polygonF.Features[polygonF.Features.Count - 1];

                            existingFeature.Coordinates.Add(coord);

                            //refresh the map if line has 2 or more points
                            if (existingFeature.Coordinates.Count >= 3)
                            {
                                //refresh the map
                                polygonF.InitializeVertices();
                                map1.ResetBuffer();
                            }
                        }
                    }
                }
                else
                {
                    //right click - reset first mouse click
                    firstClick = true;
                }
                break;
            }
        }
Beispiel #26
0
        /// <summary>
        /// Converts a point from latitude/longitude WGS-84 coordinates (in degrees)
        /// into pixel XY coordinates at a specified level of detail.
        /// </summary>
        /// <param name="latitude">Latitude of the point, in degrees.</param>
        /// <param name="longitude">Longitude of the point, in degrees.</param>
        /// <param name="levelOfDetail">Level of detail, from 1 (lowest detail)
        /// to 23 (highest detail).  </param>
        public static MWPoint LatLongToPixelXY(double latitude, double longitude, int levelOfDetail)
        {
            latitude = Clip(latitude, MinLatitude, MaxLatitude);
            longitude = Clip(longitude, MinLongitude, MaxLongitude);

            var x = (longitude + 180) / 360;
            var sinLatitude = Math.Sin(latitude * Math.PI / 180);
            var y = 0.5 - Math.Log((1 + sinLatitude) / (1 - sinLatitude)) / (4 * Math.PI);

            var mapSize = MapSize(levelOfDetail);

            var pixelXY = new MWPoint
            {
                X = (int)Clip(x * mapSize + 0.5, 0, mapSize - 1),
                Y = (int)Clip(y * mapSize + 0.5, 0, mapSize - 1)
            };

            return pixelXY;
        }
Beispiel #27
0
        private void map1_MouseDown(object sender, MouseEventArgs e)
        {
            Stopwatch timer = new Stopwatch();

            timer.Start();

            Coordinate mousept = map1.PixelToProj(e.Location);

            NetTopologySuite.Geometries.Point xp = new NetTopologySuite.Geometries.Point(mousept.X, mousept.Y);
            Console.WriteLine(xp.ToString());

            MapPolygonLayer polylayer = (MapPolygonLayer)map1.Layers[0];
            MapPolygonLayer gridlayer = (MapPolygonLayer)map1.Layers[1];

            //Iterate through NLDAS grid and determine if it intersects a polygon at selected region
            gridlayer.UnSelectAll();
            double interArea = 0.0;

            foreach (GeoAPI.Geometries.IGeometry s in overlap)
            {
                if (s.Intersects(xp))
                {
                    squareArea = s.Area;
                    foreach (GeoAPI.Geometries.IGeometry p in polys)
                    {
                        if (p.Intersects(s))
                        {
                            GeoAPI.Geometries.IGeometry intersection = p.Intersection(s);
                            interArea += intersection.Area;
                            break;
                        }
                    }
                    break;
                }
            }

            /**
             * /// slightly slower implementation, but provides visual selection.
             * int iShape = 0;
             * foreach (GeoAPI.Geometries.IGeometry s in squares)
             * {
             *  if (s.Intersects(xp))
             *  {
             *      squareArea = s.Area;
             *      gridlayer.Select(iShape);
             *      foreach (GeoAPI.Geometries.IGeometry p in polys)
             *      {
             *          if (p.Intersects(s))
             *          {
             *              GeoAPI.Geometries.IGeometry intersection = p.Intersection(s);
             *              interArea += intersection.Area;
             *              break;
             *          }
             *      }
             *      break;
             *  }
             *  iShape++;
             * }**/

            double percent = (interArea / squareArea) * 100;

            label2.Text = "Area of square: " + squareArea.ToString() + "\r\nArea of polygon in selected square: " + interArea.ToString() + "\r\nPortion of polygon covers " + percent.ToString() + "% of this square.";

            timer.Stop();
            TimeSpan ts          = timer.Elapsed;
            string   elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);

            Console.WriteLine("RunTime " + elapsedTime);

            switch (shapeType)
            {
            case "Point":
                if (e.Button == MouseButtons.Left)
                {
                    if ((pointmouseClick))
                    {
                        //This method is used to convert the screen cordinate to map coordinate
                        //e.location is the mouse click point on the map control
                        Coordinate coord = map1.PixelToProj(e.Location);

                        //Create a new point
                        //Input parameter is clicked point coordinate
                        DotSpatial.Topology.Point point = new DotSpatial.Topology.Point(coord);

                        //Add the point into the Point Feature
                        //assigning the point feature to IFeature because via it only we can set the attributes.
                        IFeature currentFeature = pointF.AddFeature(point);

                        //increase the point id
                        pointID = pointID + 1;

                        //set the ID attribute
                        //currentFeature.DataRow["PointID"] = pointID;

                        //refresh the map
                        map1.ResetBuffer();
                    }
                }

                else
                {
                    //mouse right click
                    map1.Cursor     = Cursors.Default;
                    pointmouseClick = false;
                }
                break;

            case "line":
                if (e.Button == MouseButtons.Left)
                {
                    //left click - fill array of coordinates
                    //coordinate of clicked point
                    Coordinate coord = map1.PixelToProj(e.Location);
                    if (linemouseClick)
                    {
                        //first time left click - create empty line feature
                        if (firstClick)
                        {
                            //Create a new List called lineArray.
                            //This list will store the Coordinates
                            //We are going to store the mouse click coordinates into this array.
                            List <Coordinate> lineArray = new List <Coordinate>();

                            //Create an instance for LineString class.
                            //We need to pass collection of list coordinates
                            LineString lineGeometry = new LineString(lineArray);

                            //Add the linegeometry to line feature
                            IFeature lineFeature = lineF.AddFeature(lineGeometry);

                            //add first coordinate to the line feature
                            lineFeature.Coordinates.Add(coord);
                            //set the line feature attribute
                            lineID = lineID + 1;
                            lineFeature.DataRow["LineID"] = lineID;
                            firstClick = false;
                        }
                        else
                        {
                            //second or more clicks - add points to the existing feature
                            IFeature existingFeature = lineF.Features[lineF.Features.Count - 1];
                            existingFeature.Coordinates.Add(coord);

                            //refresh the map if line has 2 or more points
                            if (existingFeature.Coordinates.Count >= 2)
                            {
                                lineF.InitializeVertices();
                                map1.ResetBuffer();
                            }
                        }
                    }
                }
                else
                {
                    //right click - reset first mouse click
                    firstClick = true;
                    map1.ResetBuffer();
                }
                break;

            case "polygon":

                if (e.Button == MouseButtons.Left)
                {
                    //left click - fill array of coordinates
                    Coordinate coord = map1.PixelToProj(e.Location);

                    if (polygonmouseClick)
                    {
                        //first time left click - create empty line feature
                        if (firstClick)
                        {
                            //Create a new List called polygonArray.

                            //this list will store the Coordinates
                            //We are going to store the mouse click coordinates into this array.

                            List <Coordinate> polygonArray = new List <Coordinate>();

                            //Create an instance for LinearRing class.
                            //We pass the polygon List to the constructor of this class
                            LinearRing polygonGeometry = new LinearRing(polygonArray);

                            //Add the polygonGeometry instance to PolygonFeature
                            IFeature polygonFeature = polygonF.AddFeature(polygonGeometry);

                            //add first coordinate to the polygon feature
                            polygonFeature.Coordinates.Add(coord);

                            //set the polygon feature attribute
                            polygonID = polygonID + 1;
                            polygonFeature.DataRow["PolygonID"] = polygonID;
                            firstClick = false;
                        }
                        else
                        {
                            //second or more clicks - add points to the existing feature
                            IFeature existingFeature = (IFeature)polygonF.Features[polygonF.Features.Count - 1];

                            existingFeature.Coordinates.Add(coord);

                            //refresh the map if line has 2 or more points
                            if (existingFeature.Coordinates.Count >= 3)
                            {
                                //refresh the map
                                polygonF.InitializeVertices();
                                map1.ResetBuffer();
                            }
                        }
                    }
                }
                else
                {
                    //right click - reset first mouse click
                    firstClick = true;
                }
                break;
            }
        }
Beispiel #28
0
 private void btnCoord_Click(object sender, EventArgs e)
 {
     //creates a new coordinate 
     Coordinate c = new Coordinate(2.4, 2.4);
     //passes the coordinate to a new point
     DotSpatial.Topology.Point p = new DotSpatial.Topology.Point(c);
     //displayes the new point's x and y coordiantes
     MessageBox.Show("Point p is: x= " + p.X + " & y= " + p.Y);
 }
        void CratePvPole(double xSpacing, IMapFeatureLayer BLineFeLyr)
        {
            project.NumPvPanel = 0;
            IMapRasterLayer demLyr;
            Raster          dem4Pv = new Raster();
            double          poleH  = 1; //Default pole height = 1 m.
            double          z0     = 0;

            try { poleH = Convert.ToDouble(txtPoleHeight.Text); }
            catch
            {
                MessageBox.Show("Pole height value error");
                txtPoleHeight.Text = "1";
                poleH = 1;
            }

            if (project.LyrDEM != -1 & chkDEM.Checked == true)
            {
                demLyr = pvMap.Layers[project.LyrDEM] as IMapRasterLayer;

                if (demLyr == null)
                {
                    MessageBox.Show("Error: DEM Data is not correct");
                    return;
                }

                int mRow = demLyr.Bounds.NumRows;
                int mCol = demLyr.Bounds.NumColumns;
                dem4Pv = (Raster)demLyr.DataSet;
                Coordinate ptReference = new Coordinate(project.UtmE, project.UtmN);
                RcIndex    rc          = dem4Pv.ProjToCell(ptReference);
                //RcIndex rc = demLyr.DataSet.ProjToCell(ptReference);
                if (rc.Column < 0 | rc.Row < 0)
                {
                    z0 = 0;
                }
                else
                {
                    z0 = dem4Pv.Value[rc.Row, rc.Column];
                    //z0 = demLyr.DataSet.Value[rc.Row, rc.Column];
                }
            }
            //------------------------------------------------------------------------------------------------
            // Create pole posion from baseline shapefile
            //------------------------------------------------------------------------------------------------

            int    nShp = BLineFeLyr.DataSet.NumRows(); // get Number of Feature
            double dx   = xSpacing;                     //m.

            FeatureSet fs;

            fs = new FeatureSet(FeatureType.Point);
            //---------------------------------------------------------
            fs.DataTable.Columns.Add(new DataColumn("x", typeof(double)));
            fs.DataTable.Columns.Add(new DataColumn("y", typeof(double)));
            fs.DataTable.Columns.Add(new DataColumn("w", typeof(double)));
            fs.DataTable.Columns.Add(new DataColumn("h", typeof(double)));
            fs.DataTable.Columns.Add(new DataColumn("Azimuth", typeof(double)));
            fs.DataTable.Columns.Add(new DataColumn("Ele_Angle", typeof(double)));
            fs.DataTable.Columns.Add(new DataColumn("ele", typeof(double)));
            //---------------------------------------------------------

            for (int i = 0; i < nShp; i++) //Line shape
            {
                IFeature BLineFe = BLineFeLyr.DataSet.GetFeature(i);
                if (chkSystemSpacing.Checked == true)
                {
                    dx = Convert.ToDouble(txtDx.Text);
                }
                else
                {
                    try
                    {
                        object val = BLineFe.DataRow["spacing"];
                        dx = (double)val;
                        if (dx <= 0)
                        {
                            MessageBox.Show("Error: Spacing data incorrect.");
                            return;
                        }
                    }
                    catch
                    {
                        MessageBox.Show("Error: Spacing data not found.");
                        project.Verify[5] = false;
                        return;
                    }
                }
                xSpacing = dx;
                double sumSegment  = 0;
                double sumL        = 0;
                double iniSegment  = 0;
                double LastSegment = 0;
                for (int n = 0; n < BLineFe.NumPoints - 1; n++) //Line segment
                {
                    double x1    = BLineFe.Coordinates[n].X;
                    double y1    = BLineFe.Coordinates[n].Y;
                    double x2    = BLineFe.Coordinates[n + 1].X;
                    double y2    = BLineFe.Coordinates[n + 1].Y;
                    double LastL = sumL;
                    double dL;

                    sumL      += Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2));
                    sumSegment = LastSegment;
                    if (sumSegment + xSpacing <= sumL | sumSegment == 0)
                    {
                        for (double Segment = sumSegment; Segment <= sumL; Segment += xSpacing)
                        {
                            dL = Segment - LastL;
                            Coordinate poleLocation = util.PointOnTheLine(x1, y1, x2, y2, dL);
                            if (poleLocation != null)
                            {
                                LastSegment += xSpacing;

                                double poleHeight = Convert.ToDouble(txtPoleHeight.Text);

                                //Coordinate poleLocation = new Coordinate(pt.X, pt.Y, poleHeight);
                                IPoint   poleFe = new DotSpatial.Topology.Point(poleLocation);
                                IFeature ifea   = fs.AddFeature(poleFe);
                                project.NumPvPanel++;

                                //------------------------------------------------------
                                ifea.DataRow.BeginEdit();
                                ifea.DataRow["x"]         = poleLocation.X;
                                ifea.DataRow["y"]         = poleLocation.Y;
                                ifea.DataRow["w"]         = 0;
                                ifea.DataRow["h"]         = 0;
                                ifea.DataRow["Azimuth"]   = 0;
                                ifea.DataRow["Ele_Angle"] = 0;

                                if (project.LyrDEM != -1 & chkDEM.Checked == true)
                                {
                                    RcIndex rc = dem4Pv.ProjToCell(poleLocation);
                                    double  z  = 0;
                                    if (rc.Column < 0 | rc.Row < 0)
                                    {
                                        z = 0;
                                    }
                                    else
                                    {
                                        z = dem4Pv.Value[rc.Row, rc.Column];
                                    }
                                    //demLyr.DataSet
                                    if (radioAboveAssumeDatum.Checked == true)
                                    {
                                        ifea.DataRow["ele"] = poleH;
                                    }
                                    else
                                    {
                                        ifea.DataRow["ele"] = z - z0 + poleH;
                                    }
                                }
                                else
                                {
                                    ifea.DataRow["ele"] = poleH;
                                }
                                ifea.DataRow.EndEdit();
                            }
                        }
                    }
                }
            } // next alignment shape

            fs.Projection = pvMap.Projection;

            //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            fs.Name     = "Panel Positon";
            fs.Filename = project.Path + "\\Temp\\" + fs.Name + ".shp";
            //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

            fs.SaveAs(fs.Filename, true);
            util.removeDupplicateLyr(fs.Name, pvMap);
            PointSymbolizer p = new PointSymbolizer(Color.Yellow, DotSpatial.Symbology.PointShape.Hexagon, 6);

            p.ScaleMode = ScaleMode.Simple;
            MapPointLayer kasem = new MapPointLayer(fs);

            kasem.Symbolizer = p;
            pvMap.Layers.Add(kasem);

            //loadLayerList();
            //pvMap.MapFrame.DrawingLayers.Clear();
            util.ClearGraphicMap(pvMap);
            project.LyrPoleName = fs.Name;


            /*
             * MapPointLayer rangeRingAxis;
             * rangeRingAxis = new MapPointLayer(fs);
             * pvMap.MapFrame.DrawingLayers.Add(rangeRingAxis);
             * pvMap.MapFrame.Invalidate();
             */
            //project.Verify[5] = true;
            //updateArea();
        }
        /// <summary>
        /// This uses extent checking (rather than full polygon intersection checking).  It will add
        /// any members that are either contained by or intersect with the specified region
        /// depending on the SelectionMode property.  The order of operation is the region
        /// acting on the feature, so Contains, for instance, would work with points.
        /// </summary>
        /// <param name="region"></param>
        /// <param name="affectedArea">The affected area of this addition</param>
        /// <returns>True if any item was actually added to the collection</returns>
        public bool AddRegion(IEnvelope region, out IEnvelope affectedArea)
        {
            bool added = false;
            SuspendChanges();
            affectedArea = new Envelope();
            Stopwatch sw = new Stopwatch();
            Stopwatch total = new Stopwatch();
            total.Start();
            foreach (IFeature f in FeatureList)
            {
                bool doAdd = false;
                if (_selectionMode == SelectionMode.IntersectsExtent)
                {
                    if (region.Intersects(f.Envelope))
                    {
                        Add(f);
                        affectedArea.ExpandToInclude(f.Envelope);
                        added = true;
                    }
                }
                else if (_selectionMode == SelectionMode.ContainsExtent)
                {
                    if (region.Contains(f.Envelope))
                    {
                        Add(f);
                        affectedArea.ExpandToInclude(f.Envelope);
                        added = true;
                    }
                }

                IGeometry reg;
                if (region.Width == 0 && region.Height == 0)
                {
                    reg = new Point(region.X, region.Y);
                }
                else if (region.Height == 0 || region.Width == 0)
                {
                    Coordinate[] coords = new Coordinate[2];
                    coords[0] = new Coordinate(region.X, region.Y);
                    coords[1] = new Coordinate(region.Bottom(), region.Right());
                    reg = new LineString(coords);
                }
                else
                {
                    reg = region.ToPolygon();
                }
                IGeometry geom = Geometry.FromBasicGeometry(f.BasicGeometry);
                switch (_selectionMode)
                {
                    case SelectionMode.Contains:
                        if (region.Contains(f.Envelope))
                        {
                            doAdd = true;
                        }
                        else if (region.Intersects(f.Envelope))
                        {
                            if (reg.Contains(geom)) doAdd = true;
                        }
                        break;
                    case SelectionMode.CoveredBy:
                        if (reg.CoveredBy(geom)) doAdd = true;
                        break;
                    case SelectionMode.Covers:
                        if (reg.Covers(geom)) doAdd = true;
                        break;
                    case SelectionMode.Disjoint:
                        if (reg.Disjoint(geom)) doAdd = true;
                        break;
                    case SelectionMode.Intersects:

                        if (region.Contains(f.Envelope))
                        {
                            doAdd = true;
                        }
                        else if (region.Intersects(f.Envelope))
                        {
                            if (reg.Intersects(geom)) doAdd = true;
                        }

                        break;
                    case SelectionMode.Overlaps:
                        if (reg.Overlaps(geom)) doAdd = true;
                        break;
                    case SelectionMode.Touches:
                        if (reg.Touches(geom)) doAdd = true;
                        break;
                    case SelectionMode.Within:
                        if (reg.Within(geom)) doAdd = true;
                        break;
                }

                if (doAdd)
                {
                    Add(f);
                    affectedArea.ExpandToInclude(f.Envelope);
                    added = true;
                }
            }
            sw.Start();
            ResumeChanges();
            sw.Stop();
            total.Stop();
            Debug.WriteLine("Geometry Intersection Time: " + sw.ElapsedMilliseconds);
            Debug.WriteLine("Total Intersection Time: " + total.ElapsedMilliseconds);
            return added;
        }
 public void AddPoint()
 {
     var point = new Point(spatialMap.ViewExtents.Center);
     IFeature feature = layerBeingEdited.DataSet.AddFeature(point);
     Points.Add(point);
 }