Пример #1
0
        /// <summary>
        /// Returns the style based on a feature
        /// </summary>
        /// <param name="attribute">Set of attribute values to calculate the <see cref="IStyle"/> from</param>
        /// <returns>The style</returns>
        public IStyle GetStyle(FeatureDataRow attribute)
        {
            // Do we have a theme to evaluate first?
            if (BaseTheme != null)
            {
                var style = BaseTheme.GetStyle(attribute);
                if (!style.Enabled) return style;
                if (!(style is LabelStyle)) return style;

                var labelStyle = (LabelStyle) style;
                return UpdateStyle(labelStyle, CalculateSize(_map, labelStyle.Font.SizeInPoints));
            }

            // Test if zoom level has changed.
            if (_currentZoom != _map.Zoom)
            {
                // Get the new size
                var newSize = CalculateSize(_map, _currentSize);
                
                // Update the style
                _currentStyle = UpdateStyle(_currentStyle, newSize);
                _currentZoom = _map.Zoom;
            }

            // return the style
            return _currentStyle;
        }
Пример #2
0
        //特征着色
        private SharpMap.Styles.VectorStyle FeatureColoured(SharpMap.Data.FeatureDataRow row)
        {
            SharpMap.Styles.VectorStyle style = new SharpMap.Styles.VectorStyle();

            string NAME = row["NAME"].ToString().ToLower();

            if (NAME == featureName)
            {
                style.Fill    = new System.Drawing.SolidBrush(Color.Green);
                style.Outline = new System.Drawing.Pen(Color.Transparent, 2);

                style.Line.Color    = Color.Yellow;
                style.EnableOutline = true;

                return(style);
            }
            else
            {
                //style.Fill = new SolidBrush(Color.Transparent);
                //style.Outline = new Pen(Color.ForestGreen, 0.4f);
                //style.Line.Width = 1;
                //style.Line.Color = Color.Green;
                style.Fill    = new System.Drawing.SolidBrush(Color.Transparent);
                style.Outline = new System.Drawing.Pen(Color.ForestGreen, 0.4f);

                style.Line.Color    = Color.Green;
                style.EnableOutline = true;
                return(style);
            }
        }
Пример #3
0
    /// <summary>
    /// Method for creating pie chart symbols
    /// </summary>
    /// <remarks>
    /// <para>In this example we just create some random pie charts,
    /// but it probably should be based on attributes read from the row.</para>
    ///	<para>Credits goes to gonzalo_ar for posting this in the forum</para></remarks>
    /// <param name="row"></param>
    /// <returns></returns>
    private static Bitmap GetPieChart(SharpMap.Data.FeatureDataRow row)
    {
        // Replace polygon with a center point (this is where we place the symbol
        row.Geometry = row.Geometry.GetBoundingBox().GetCentroid();

        // Just for the example I use random values
        int       size   = rand.Next(20, 35);
        int       angle1 = rand.Next(60, 180);
        int       angle2 = rand.Next(angle1 + 60, 300);
        Rectangle rect   = new Rectangle(0, 0, size, size);

        System.Drawing.Bitmap b = new Bitmap(size, size);
        Graphics g = Graphics.FromImage(b);

        // Draw Pie
        g.FillPie(Brushes.LightGreen, rect, 0, angle1);
        g.FillPie(Brushes.Pink, rect, angle1, angle2 - angle1);
        g.FillPie(Brushes.PeachPuff, rect, angle2, 360 - angle2);

        // Draw Borders
        g.DrawPie(Pens.Green, rect, 0, angle1);
        g.DrawPie(Pens.Red, rect, angle1, angle2 - angle1);
        g.DrawPie(Pens.Orange, rect, angle2, 360 - angle2);
        g.Dispose();
        return(b);
    }
Пример #4
0
 /// <summary>
 /// This method is used for determining the style
 /// It is used as a delegate for the CustomTheme class.
 /// </summary>
 /// <param name="row"></param>
 /// <returns></returns>
 private SharpMap.Styles.VectorStyle GetCountryStyle(SharpMap.Data.FeatureDataRow row)
 {
     SharpMap.Styles.VectorStyle s = new SharpMap.Styles.VectorStyle();
     s.Fill   = new SolidBrush(Color.Green);
     s.Symbol = GetPieChart(row);
     return(s);
 }
Пример #5
0
    /// <summary>
    /// Method for creating pie chart symbols
    /// </summary>
    /// <remarks>
    /// <para>In this example we just create some random pie charts, 
    /// but it probably should be based on attributes read from the row.</para>
    ///	<para>Credits goes to gonzalo_ar for posting this in the forum</para></remarks>
    /// <param name="row"></param>
    /// <returns></returns>
    private static Bitmap GetPieChart(FeatureDataRow row)
    {
        // Replace polygon with a center point (this is where we place the symbol
        row.Geometry = row.Geometry.Centroid;

        // Just for the example I use random values
        int size = rand.Next(20, 35);
        int angle1 = rand.Next(60, 180);
        int angle2 = rand.Next(angle1 + 60, 300);
        Rectangle rect = new Rectangle(0, 0, size, size);
        Bitmap b = new Bitmap(size, size);
        using (var g = Graphics.FromImage(b))
        {
            // Draw Pie
            g.FillPie(Brushes.LightGreen, rect, 0, angle1);
            g.FillPie(Brushes.Pink, rect, angle1, angle2 - angle1);
            g.FillPie(Brushes.PeachPuff, rect, angle2, 360 - angle2);

            // Draw Borders
            g.DrawPie(Pens.Green, rect, 0, angle1);
            g.DrawPie(Pens.Red, rect, angle1, angle2 - angle1);
            g.DrawPie(Pens.Orange, rect, angle2, 360 - angle2);
        }
        return b;
    }
Пример #6
0
 /// <summary>
 /// This method is used for determining the color of country based on attributes.
 /// It is used as a delegate for the CustomTheme class.
 /// </summary>
 /// <param name="row"></param>
 /// <returns></returns>
 private VectorStyle GetCountryStyle(FeatureDataRow row)
 {
     VectorStyle style = new VectorStyle();
     switch (row["NAME"].ToString().ToLower())
     {
         case "denmark": //If country name is Danmark, fill it with green
             style.Fill = Brushes.Green;
             return style;
         case "united states": //If country name is USA, fill it with Blue and add a red outline
             style.Fill = Brushes.Blue;
             style.Outline = Pens.Red;
             return style;
         case "china": //If country name is China, fill it with red
             style.Fill = Brushes.Red;
             return style;
         default:
             break;
     }
     //If country name starts with S make it yellow
     if (row["NAME"].ToString().StartsWith("S"))
     {
         style.Fill = Brushes.Yellow;
         return style;
     }
         // If geometry is a (multi)polygon and the area of the polygon is less than 30, make it cyan
     else if (row.Geometry.GetType() == typeof (MultiPolygon) && (row.Geometry as MultiPolygon).Area < 30 ||
              row.Geometry.GetType() == typeof (Polygon) && (row.Geometry as Polygon).Area < 30)
     {
         style.Fill = Brushes.Cyan;
         return style;
     }
     else //None of the above -> Use the default style
         return null;
 }
Пример #7
0
 /// <summary>
 /// This method is used for determining the style
 /// It is used as a delegate for the CustomTheme class.
 /// </summary>
 /// <param name="row"></param>
 /// <returns></returns>
 private VectorStyle GetCountryStyle(FeatureDataRow row)
 {
     VectorStyle s = new VectorStyle();
     s.Fill = new SolidBrush(Color.Green);
     s.Symbol = GetPieChart(row);
     return s;
 }
Пример #8
0
 private static IStyle StyleBasedOnAlignment(FeatureDataRow dr)
 {
     var style = new LabelStyle
     {
         HorizontalAlignment = (LabelStyle.HorizontalAlignmentEnum)(int) dr[2],
         VerticalAlignment = (LabelStyle.VerticalAlignmentEnum)(int) dr[3],
         Rotation = -20,
         BackColor = Brushes.Pink,
         Halo = new Pen(Brushes.LightBlue, 2)
     };
     return style;
 }
Пример #9
0
        /// <summary>
        /// Returns the style based on a feature
        /// </summary>
        /// <param name="attribute">Attribute to calculate color from</param>
        /// <returns>Color</returns>
        public SharpMap.Styles.IStyle GetStyle(FeatureDataRow attribute)
        {
            VectorStyle vs = new VectorStyle();

            if (!_brushes.ContainsKey(attribute.Geometry))
                _brushes[attribute.Geometry] = new SolidBrush(Color.FromArgb(rand.Next(255), rand.Next(255), rand.Next(255)));

            vs.Fill = _brushes[attribute.Geometry];
            vs.Outline = new Pen(Color.Black);
            vs.EnableOutline = true;
            return vs;
        }
Пример #10
0
        /// <summary>
        /// Returns all features with the view box
        /// </summary>
        /// <param name="bbox">view box</param>
        /// <param name="ds">FeatureDataSet to fill data into</param>
        public void ExecuteIntersectionQuery(SharpMap.Geometries.BoundingBox bbox, SharpMap.Data.FeatureDataSet ds)
        {
            List <Geometries.Geometry> features = new List <SharpMap.Geometries.Geometry>();

            using (SqlConnection conn = new SqlConnection(_ConnectionString))
            {
                string strSQL = "SELECT *, " + this.GeometryColumn + " AS sharpmap_tempgeometry ";
                strSQL += "FROM " + this.Table + " WHERE ";
                strSQL += GetBoxClause(bbox);

                if (_defintionQuery != null && _defintionQuery != "")
                {
                    strSQL += " AND " + this.DefinitionQuery;
                }

                using (SqlDataAdapter adapter = new SqlDataAdapter(strSQL, conn))
                {
                    conn.Open();
                    System.Data.DataSet ds2 = new System.Data.DataSet();
                    adapter.Fill(ds2);
                    conn.Close();
                    if (ds2.Tables.Count > 0)
                    {
                        FeatureDataTable fdt = new FeatureDataTable(ds2.Tables[0]);
                        foreach (System.Data.DataColumn col in ds2.Tables[0].Columns)
                        {
                            if (col.ColumnName != this.GeometryColumn && col.ColumnName != "sharpmap_tempgeometry" && !col.ColumnName.StartsWith("Envelope_"))
                            {
                                fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression);
                            }
                        }
                        foreach (System.Data.DataRow dr in ds2.Tables[0].Rows)
                        {
                            SharpMap.Data.FeatureDataRow fdr = fdt.NewRow();
                            foreach (System.Data.DataColumn col in ds2.Tables[0].Columns)
                            {
                                if (col.ColumnName != this.GeometryColumn && col.ColumnName != "sharpmap_tempgeometry" && !col.ColumnName.StartsWith("Envelope_"))
                                {
                                    fdr[col.ColumnName] = dr[col];
                                }
                            }
                            if (dr["sharpmap_tempgeometry"] != DBNull.Value)
                            {
                                fdr.Geometry = SharpMap.Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])dr["sharpmap_tempgeometry"]);
                            }
                            fdt.AddRow(fdr);
                        }
                        ds.Tables.Add(fdt);
                    }
                }
            }
        }
Пример #11
0
 /// <summary>
 /// Returns a datarow based on a RowID
 /// </summary>
 /// <param name="RowID"></param>
 /// <returns>datarow</returns>
 public SharpMap.Data.FeatureDataRow GetFeature(uint RowID)
 {
     using (SqlConnection conn = new SqlConnection(_ConnectionString))
     {
         string strSQL = "SELECT *, " + this.GeometryColumn + " AS sharpmap_tempgeometry FROM " + this.Table + " WHERE " + this.ObjectIdColumn + "='" + RowID.ToString() + "'";
         using (SqlDataAdapter adapter = new SqlDataAdapter(strSQL, conn))
         {
             DataSet ds = new DataSet();
             conn.Open();
             adapter.Fill(ds);
             conn.Close();
             if (ds.Tables.Count > 0)
             {
                 FeatureDataTable fdt = new FeatureDataTable(ds.Tables[0]);
                 foreach (System.Data.DataColumn col in ds.Tables[0].Columns)
                 {
                     if (col.ColumnName != this.GeometryColumn && col.ColumnName != "sharpmap_tempgeometry" && !col.ColumnName.StartsWith("Envelope_"))
                     {
                         fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression);
                     }
                 }
                 if (ds.Tables[0].Rows.Count > 0)
                 {
                     System.Data.DataRow          dr  = ds.Tables[0].Rows[0];
                     SharpMap.Data.FeatureDataRow fdr = fdt.NewRow();
                     foreach (System.Data.DataColumn col in ds.Tables[0].Columns)
                     {
                         if (col.ColumnName != this.GeometryColumn && col.ColumnName != "sharpmap_tempgeometry" && !col.ColumnName.StartsWith("Envelope_"))
                         {
                             fdr[col.ColumnName] = dr[col];
                         }
                     }
                     if (dr["sharpmap_tempgeometry"] != DBNull.Value)
                     {
                         fdr.Geometry = SharpMap.Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])dr["sharpmap_tempgeometry"]);
                     }
                     return(fdr);
                 }
                 else
                 {
                     return(null);
                 }
             }
             else
             {
                 return(null);
             }
         }
     }
 }
Пример #12
0
 private SharpMap.Styles.LabelStyle GetStyleForStateLabel(SharpMap.Data.FeatureDataRow row)
 {
     SharpMap.Styles.LabelStyle style = new SharpMap.Styles.LabelStyle()
     {
         ForeColor = fontStateColor
     };
     if (row.ItemArray[3].Equals("HI"))
     {
         style.ForeColor = Color.Black;
     }
     style.Font = fontStateLabels;
     style.CollisionDetection  = true;
     style.CollisionBuffer     = new SizeF(50, 50);
     style.HorizontalAlignment = SharpMap.Styles.LabelStyle.HorizontalAlignmentEnum.Center;
     style.Enabled             = false;
     return(style);
 }
Пример #13
0
    private static SharpMap.Styles.VectorStyle GetFullStationStyle(SharpMap.Data.FeatureDataRow row)
    {
        SharpMap.Styles.VectorStyle style = new SharpMap.Styles.VectorStyle();
        string s1 = row["Oid"].ToString();
        string s2 = row["id"].ToString();

        if (Int32.Parse(s1) < 6)
        {
            style.PointColor = new SolidBrush(Color.DarkOrange);
            style.PointSize  = 20f;
        }
        else
        {
            style.PointColor = new SolidBrush(Color.DeepSkyBlue);
            style.PointSize  = 10f;
        }
        return(style);
    }
Пример #14
0
        public FeatureDataRow <TTarget> ConvertRow(IFeatureDataRecord source)
        {
            if (typeof(TSource) == typeof(TTarget) && source is FeatureDataRow)
            {
                return(source as FeatureDataRow <TTarget>);
            }
            TTarget oid = _conversionDelegate((TSource)source.GetOid());
            FeatureDataRow <TTarget> row = _target.NewRow(oid);

            object[] vals = new object[source.FieldCount];
            vals[_oidColumnIndex] = oid;
            source.GetValues(vals);
            row.ItemArray = vals;
            //row.Geometry = source.Geometry.IsValid ? source.Geometry : source.Geometry.Buffer(0.0);
            row.Geometry = source.Geometry;

            return(row);
        }
Пример #15
0
        private static FeatureDataTable <TOid> internalCreateTableWithId(FeatureDataTable tableCopy, DataColumn objectIdColumn, IGeometryFactory factory)
        {
            FeatureDataTable <TOid> tableWithId = new FeatureDataTable <TOid>(tableCopy, objectIdColumn.ColumnName, factory);

            // TODO: shouldn't this be in the base class? Need to check if changing base behavior will break stuff.
            foreach (DataColumn col in tableCopy.Columns)
            {
                if (String.Compare(col.ColumnName, objectIdColumn.ColumnName, StringComparison.InvariantCultureIgnoreCase) == 0)
                {
                    continue;
                }

                DataColumn colCopy = new DataColumn(col.ColumnName, col.DataType);
                colCopy.AllowDBNull       = col.AllowDBNull;
                colCopy.AutoIncrement     = col.AutoIncrement;
                colCopy.AutoIncrementSeed = col.AutoIncrementSeed;
                colCopy.AutoIncrementStep = col.AutoIncrementStep;
                colCopy.DateTimeMode      = col.DateTimeMode;
                colCopy.DefaultValue      = col.DefaultValue;

                foreach (DictionaryEntry entry in col.ExtendedProperties)
                {
                    colCopy.ExtendedProperties[entry.Key] = entry.Value;
                }

                colCopy.MaxLength = col.MaxLength;
                colCopy.ReadOnly  = col.ReadOnly;
                colCopy.Unique    = col.Unique;
                tableWithId.Columns.Add(colCopy);
            }

            foreach (DataRow row in tableCopy)
            {
                FeatureDataRow <TOid> newRow = tableWithId.NewRow() as FeatureDataRow <TOid>;
                Debug.Assert(newRow != null);
                Int32 itemCount = newRow.ItemArray.Length;
                newRow.ItemArray = new Object[itemCount];
                //Array.Copy(row.ItemArray, newRow.ItemArray, itemCount);
                newRow.ItemArray = row.ItemArray;
                tableWithId.AddRow(newRow);
            }

            return(tableWithId);
        }
Пример #16
0
 public IStyle GetStyle(FeatureDataRow attribute)
 {
     IStyle returnStyle;
     String value = Convert.ToString(attribute[_columnName]);
     if (!_stylePreserver.TryGetValue(value, out returnStyle))
     {
         if (GetStyleFunction != null)
         {
             returnStyle = GetStyleFunction(attribute);
             if (returnStyle == null) returnStyle = _default;
             _stylePreserver.Add(value, returnStyle);
         }
         else
             returnStyle = _default;
     }
     //returnStyle.MinVisible = _default.MinVisible;
     //returnStyle.MaxVisible = _default.MaxVisible;
     return returnStyle;
 }
Пример #17
0
        protected bool Equals(FeatureDataRow other)
        {
            var thisItems = ItemArray;
            var otherItems = other.ItemArray;

            if (thisItems.Length != otherItems.Length)
            {
                return false;
            }

            for (int i = 0; i < otherItems.Length; i++)
            {
                if (!Equals(thisItems[i], otherItems[i]))
                {
                    return false;
                }
            }

            return true;
        }
Пример #18
0
        protected bool Equals(FeatureDataRow other)
        {
            var thisItems  = ItemArray;
            var otherItems = other.ItemArray;

            if (thisItems.Length != otherItems.Length)
            {
                return(false);
            }

            for (int i = 0; i < otherItems.Length; i++)
            {
                if (!Equals(thisItems[i], otherItems[i]))
                {
                    return(false);
                }
            }

            return(true);
        }
Пример #19
0
    /// <summary>
    /// This method is used for determining the color of country based on attributes.
    /// It is used as a delegate for the CustomTheme class.
    /// </summary>
    /// <param name="row"></param>
    /// <returns></returns>
    private IVectorStyle GetCountryStyle(SharpMap.Data.FeatureDataRow row)
    {
        IVectorStyle style = new SharpMap.Styles.VectorStyle();

        switch (row["NAME"].ToString().ToLower())
        {
        case "denmark":     //If country name is Danmark, fill it with green
            style.Fill = Brushes.Green;
            return(style);

        case "united states":     //If country name is USA, fill it with Blue and add a red outline
            style.Fill    = Brushes.Blue;
            style.Outline = Pens.Red;
            return(style);

        case "china":     //If country name is China, fill it with red
            style.Fill = Brushes.Red;
            return(style);

        default:
            break;
        }
        //If country name starts with S make it yellow
        if (row["NAME"].ToString().StartsWith("S"))
        {
            style.Fill = Brushes.Yellow;
            return(style);
        }
        // If geometry is a (multi)polygon and the area of the polygon is less than 30, make it cyan
        else if (row.Geometry.GetType() == typeof(SharpMap.Geometries.MultiPolygon) && (row.Geometry as SharpMap.Geometries.MultiPolygon).Area < 30 ||
                 row.Geometry.GetType() == typeof(SharpMap.Geometries.Polygon) && (row.Geometry as SharpMap.Geometries.Polygon).Area < 30)
        {
            style.Fill = Brushes.Cyan;
            return(style);
        }
        else //None of the above -> Use the default style
        {
            return(null);
        }
    }
Пример #20
0
 private SharpMap.Styles.VectorStyle GetStyleForShape(SharpMap.Data.FeatureDataRow row)
 {
     SharpMap.Styles.VectorStyle style = new SharpMap.Styles.VectorStyle();
     if (bandStates.Contains(row.ItemArray[6]))
     {
         style.Fill    = Brushes.Green;
         style.Outline = new Pen(Color.Black, 1);
     }
     else
     {
         style.Fill    = Brushes.DarkRed;
         style.Outline = new Pen(Color.Black, 1);
     }
     if (!states.Contains(row.ItemArray[6]))
     //if (row.ItemArray[6].Equals("PR"))
     {
         style.Fill    = Brushes.White; // ignore non-50 states for WAS award coloring
         style.Outline = new Pen(Color.White, 1);
     }
     //style.Line = new Pen(Color.Black, 1);
     style.EnableOutline = true;
     return(style);
 }
 /// <summary>
 /// Initializes a new instance of the FeatureDataRowChangeEventArgs class.
 /// </summary>
 /// <param name="row"></param>
 /// <param name="action"></param>
 public FeatureDataRowChangeEventArgs(FeatureDataRow row, DataRowAction action)
 {
     _eventRow = row;
     _eventAction = action;
 }
Пример #22
0
            /// <summary>
            /// gets realtime data from public transport in city vilnius of lithuania
            /// </summary>
            private void GetVilniusTransportData(string line)
            {
                if (_isActive)
                {
                    return;
                }
                _isActive = true;

                //List<FeatureDataRow> newFeatures = new List<FeatureDataRow>();
                var fdt = VehicleDataTable();

                string url = "http://www.troleibusai.lt/puslapiai/services/vehiclestate.php?type=";

                switch (_transportType)
                {
                case TransportType.Bus:
                {
                    url += "bus";
                }
                break;

                case TransportType.TrolleyBus:
                {
                    url += "trolley";
                }
                break;
                }

                if (!string.IsNullOrEmpty(line))
                {
                    url += "&line=" + line;
                }

                url += "&app=SharpMap.WinFormSamples";

                var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);

                request.Timeout          = Timeout;
                request.ReadWriteTimeout = request.Timeout;
                request.Accept           = "*/*";
                request.KeepAlive        = false;

                string xml;

                using (var response = request.GetResponse() as System.Net.HttpWebResponse)
                {
                    if (response == null)
                    {
                        return;
                    }

                    using (var responseStream = response.GetResponseStream())
                    {
                        if (responseStream == null)
                        {
                            return;
                        }
                        using (var read = new System.IO.StreamReader(responseStream))
                        {
                            xml = read.ReadToEnd();
                        }
                    }
                }

                var doc = new System.Xml.XmlDocument();

                {
                    doc.LoadXml(xml);

                    var devices = doc.GetElementsByTagName("Device");
                    foreach (System.Xml.XmlNode dev in devices)
                    {
                        if (dev.Attributes == null)
                        {
                            continue;
                        }

                        double?lat = null, lng = null;
                        SharpMap.Data.FeatureDataRow dr = fdt.NewRow();
                        dr["Id"] = int.Parse(dev.Attributes["ID"].InnerText);
                        foreach (System.Xml.XmlElement elem in dev.ChildNodes)
                        {
                            // Debug.WriteLine(d.Id + "->" + elem.Name + ": " + elem.InnerText);

                            switch (elem.Name)
                            {
                            case "Lat":
                                lat = double.Parse(elem.InnerText, System.Globalization.CultureInfo.InvariantCulture);
                                break;

                            case "Lng":
                                lng = double.Parse(elem.InnerText, System.Globalization.CultureInfo.InvariantCulture);
                                break;

                            case "Bearing":
                                if (!string.IsNullOrEmpty(elem.InnerText))
                                {
                                    dr["Bearing"] = double.Parse(elem.InnerText, System.Globalization.CultureInfo.InvariantCulture);
                                }
                                break;

                            case "LineNum":
                                dr["Line"] = elem.InnerText;
                                break;

                            case "AreaName":
                                dr["AreaName"] = elem.InnerText;
                                break;

                            case "StreetName":
                                dr["StreetName"] = elem.InnerText;
                                break;

                            case "TrackType":
                                dr["TrackType"] = elem.InnerText;
                                break;

                            case "LastStop":
                                dr["LastStop"] = elem.InnerText;
                                break;

                            case "Time":
                                dr["Time"] = elem.InnerText;
                                break;
                            }
                        }

                        if (lat.HasValue && lng.HasValue)
                        {
                            dr.Geometry = _factory.CreatePoint(new GeoAPI.Geometries.Coordinate(lng.Value, lat.Value));
                            fdt.Rows.Add(dr);
                        }
                    }
                }

                Features.Clear();
                var features = (FeatureDataTable)Features;

                foreach (SharpMap.Data.FeatureDataRow featureDataRow in fdt.Rows)
                {
                    var fdr = features.NewRow();
                    fdr.ItemArray = featureDataRow.ItemArray;
                    fdr.Geometry  = featureDataRow.Geometry;
                    features.AddRow(fdr);
                }
                features.AcceptChanges();

                _isActive = false;
            }
Пример #23
0
        public int CompareTo(object obj)
        {
            FeatureDataRow row = (FeatureDataRow)obj;

            return(Table.Rows.IndexOf(this).CompareTo(Table.Rows.IndexOf(row)));
        }
Пример #24
0
        /// <summary>
        /// Intitalizes a new instance of the FeatureDataTable class with the specified table name.
        /// </summary>
        /// <param name="table"></param>
        public FeatureDataTable(DataTable table)
            : base(table.TableName)
        {
            //if (table.DataSet != null)
            //{
            //    if ((table.CaseSensitive != table.DataSet.CaseSensitive))
            //    {
            //        CaseSensitive = table.CaseSensitive;
            //    }
            //    if ((table.Locale.ToString() != table.DataSet.Locale.ToString()))
            //    {
            //        Locale = table.Locale;
            //    }
            //    if ((table.Namespace != table.DataSet.Namespace))
            //    {
            //        Namespace = table.Namespace;
            //    }
            //}

            //Prefix = table.Prefix;
            //MinimumCapacity = table.MinimumCapacity;
            //DisplayExpression = table.DisplayExpression;

            //if (table.DataSet != null)
            //{
            //    if ((table.CaseSensitive != table.DataSet.CaseSensitive))
            //    {
            //        CaseSensitive = table.CaseSensitive;
            //    }
            //    if ((table.Locale.ToString() != table.DataSet.Locale.ToString()))
            //    {
            //        Locale = table.Locale;
            //    }
            //    if ((table.Namespace != table.DataSet.Namespace))
            //    {
            //        Namespace = table.Namespace;
            //    }
            //}


            //创建新的返回表
            base.Columns.Add(new DataColumn("ID", System.Type.GetType("System.Int32")));
            base.Columns.Add(new DataColumn("Name", System.Type.GetType("System.String")));
            base.Columns.Add(new DataColumn("Type", System.Type.GetType("System.String")));

            int i = 0;

            for (i = 0; i < table.Rows.Count; i++)
            {
                FeatureDataRow newRow = this.NewRow();
                newRow["ID"]   = table.Rows[i]["ID"];
                newRow["Name"] = table.Rows[i]["Name"];
                //将原表中的类型放到新的类型字段Type中
                if (table.Columns.Contains("StationType"))
                {
                    newRow["Type"] = table.Rows[i]["StationType"];
                }
                else
                {
                    newRow["Type"] = table.Rows[i]["CardType"];
                }
                newRow.Geometry = new SharpMap.Geometries.Point(Convert.ToDouble(table.Rows[i]["Geo_X"]), Convert.ToDouble(table.Rows[i]["Geo_Y"]));
                base.Rows.Add(newRow);
                newRow = null;
            }
        }
Пример #25
0
 private BaseLabel CreateLabel(FeatureDataRow fdr, Geometry feature, string text, float rotation, LabelStyle style, Map map, Graphics g)
 {
     return CreateLabel(fdr, feature, text, rotation, Priority, style, map, g, _getLocationMethod);
 }
Пример #26
0
        /// <summary>
        /// Returns the style based on a numeric DataColumn, where style
        /// properties are linearly interpolated between max and min values.
        /// </summary>
        /// <param name="row">Feature</param>
        /// <returns><see cref="SharpMap.Styles.IStyle">Style</see> calculated by a linear interpolation between the min/max styles</returns>
        public IStyle GetStyle(FeatureDataRow row)
        {
            Double weighting;

            try
            {
                weighting = Convert.ToDouble(row[_columnName]);
            }
            catch
            {
                throw new InvalidOperationException(
                    "Invalid attribute type in gradient theme. " +
                    "Couldn't parse weighting attribute (must be numeric).");
            }

            if (MinStyle == null)
            {
                throw new InvalidOperationException("Cannot create a gradient style if the MinStyle is missing.");
            }

            if (MaxStyle == null)
            {
                throw new InvalidOperationException("Cannot create a gradient style if the MaxStyle is missing.");
            }

            Type minStyleType = MinStyle.GetType();
            Type maxStyleType = MaxStyle.GetType();

            if (minStyleType != maxStyleType)
            {
                throw new ArgumentException("MinStyle and MaxStyle must be of the same type");
            }

            CalculateStyleDelegate styleCalculator;
            _styleTypeFunctionTable.TryGetValue(minStyleType.TypeHandle, out styleCalculator);

            if (styleCalculator == null)
            {
                throw new ArgumentException(
                    "Only SharpMap.Styles.VectorStyle and SharpMap.Styles.LabelStyle " +
                    "are supported for the gradient theme");
            }

            return styleCalculator(MinStyle, MaxStyle, weighting);
        }
 private static String fdrLabel(FeatureDataRow fdr)
 {
     return String.Format("Feature {0} with GeometryType {1}: {2}",
       fdr.GetOid(), fdr.Geometry.GeometryTypeName, fdr.Geometry.ToString());
 }
Пример #28
0
 /// <summary>
 /// Removes the feature row from the table.
 /// </summary>
 /// <param name="row">Row to remove.</param>
 public void RemoveRow(FeatureDataRow <TOid> row)
 {
     Rows.Remove(row);
 }
Пример #29
0
        private static BaseLabel CreateLabel(FeatureDataRow fdr, Geometry feature, string text, float rotation, int priority, LabelStyle style, Map map, Graphics g, GetLocationMethod _getLocationMethod)
        {
            BaseLabel lbl = null;

            SizeF size = VectorRenderer.SizeOfString(g, text, style.Font);

            if (feature is ILineal)
            {
                var line = feature as LineString;
                if (line != null)
                {
                    if (style.IsTextOnPath == false)
                    {
                        if (size.Width < 0.95 * line.Length / map.PixelWidth || style.IgnoreLength)
                        {
                            var positiveLineString = PositiveLineString(line, false);
                            var lineStringPath = LineStringToPath(positiveLineString, map /*, false*/);
                            var rect = lineStringPath.GetBounds();

                            if (style.CollisionDetection && !style.CollisionBuffer.IsEmpty)
                            {
                                var cbx = style.CollisionBuffer.Width;
                                var cby = style.CollisionBuffer.Height;
                                rect.Inflate(2 * cbx, 2 * cby);
                                rect.Offset(-cbx, -cby);
                            }
                            var labelBox = new LabelBox(rect);

                            lbl = new PathLabel(text, lineStringPath, 0, priority, labelBox, style);
                        }
                    }
                    else
                    {
                        //get centriod
                        System.Drawing.PointF position2 = map.WorldToImage(feature.GetBoundingBox().GetCentroid());
                        lbl = new Label(text, position2, rotation, priority, style);
                        if (size.Width < 0.95 * line.Length / map.PixelWidth || !style.IgnoreLength)
                        {
                            CalculateLabelAroundOnLineString(line, ref lbl, map, g, size);
                        }
                    }
                }
                return lbl;
            }
            
            PointF position = Transform.WorldtoMap(feature.GetBoundingBox().GetCentroid(), map);
            if (_getLocationMethod != null)
            {
                Point p = _getLocationMethod(fdr);
                if (p !=null)
                    position = Transform.WorldtoMap(p, map);
            }
            position.X = position.X - size.Width*(short) style.HorizontalAlignment*0.5f;
            position.Y = position.Y - size.Height*(short) (2-(int)style.VerticalAlignment)*0.5f;
            if (position.X - size.Width > map.Size.Width || position.X + size.Width < 0 ||
                position.Y - size.Height > map.Size.Height || position.Y + size.Height < 0)
                return null;

            if (!style.CollisionDetection)
                lbl = new Label(text, position, rotation, priority, null, style);
            else
            {
                //Collision detection is enabled so we need to measure the size of the string
                lbl = new Label(text, position, rotation, priority,
                                new LabelBox(position.X - size.Width*0.5f - style.CollisionBuffer.Width,
                                             position.Y + size.Height*0.5f + style.CollisionBuffer.Height,
                                             size.Width + 2f*style.CollisionBuffer.Width,
                                             size.Height + style.CollisionBuffer.Height*2f), style);
            }

            /*
            if (feature is LineString)
            {
                var line = feature as LineString;

                //Only label feature if it is long enough, or it is definately wanted                
                if (line.Length / map.PixelSize > size.Width || style.IgnoreLength)
                {
                    CalculateLabelOnLinestring(line, ref lbl, map);
                }
                else
                    return null;
            }
            */
            return lbl;
        }
Пример #30
0
 /// <summary>
 /// Returns the <see cref="System.Drawing.Color">color</see> based on an attribute value
 /// </summary>
 /// <param name="row">DataRow</param>
 /// <returns>Style generated by GetStyle-Delegate</returns>
 public IStyle GetStyle(FeatureDataRow row)
 {
     IStyle style = _getStyleDelegate(row);
     if (style != null)
         return style;
     else
         return _defaultStyle;
 }
Пример #31
0
		/// <summary>
		/// Initializes a new instance of the <see cref="GeometryProvider"/>
		/// </summary>
		/// <param name="feature">Feature to be in this datasource</param>
		public GeometryProvider(FeatureDataRow feature)
		{
			_Geometries = new Collection<IGeometry>();
			_Geometries.Add(feature.Geometry);
		}
Пример #32
0
 private void ShowToolTip(FeatureDataRow fdr)
 {
     if (fdr != null)
     {
         
         MapControl.BeginInvoke(new Action(() =>
         {
             var _t = new ToolTip();
             _toolTip = _t;
             _t/*oolTip*/.ToolTipTitle = fdr.Table.TableName;
             
             _t/*oolTip*/.Show(ToText(fdr), MapControl);
         }));
     }
     else
     {
         //MapControl.BeginInvoke(new MethodInvoker( () => _toolTip.Hide(MapControl)));
     }
 }
Пример #33
0
 /// <summary>
 /// Removes the row from the table
 /// </summary>
 /// <param name="row">Row to remove</param>
 public void RemoveRow(FeatureDataRow row)
 {
     base.Rows.Remove(row);
 }
Пример #34
0
        // TODO: refactor. too many lines!
        /// <summary>
        /// Filters the features to be processed by a CQL filter
        /// </summary>
        /// <param name="row">A <see cref="T:SharpMap.Data.FeatureDataRow"/> to test.</param>
        /// <param name="cqlString">A CQL string defining the filter </param>
        /// <returns>GeoJSON string with featureinfo results</returns>
        public bool CqlFilter(FeatureDataRow row, string cqlString)
        {
            bool toreturn = true;
            // check on filter type (AND, OR, NOT)
            string[] splitstring = { " " };
            string[] cqlStringItems = cqlString.Split(splitstring, StringSplitOptions.RemoveEmptyEntries);
            string[] comparers = { "==", "!=", "<", ">", "<=", ">=", "BETWEEN", "LIKE", "IN" };
            for (int i = 0; i < cqlStringItems.Length; i++)
            {
                bool tmpResult = true;
                // check first on AND OR NOT, only the case if multiple checks have to be done
                bool AND = true;
                bool OR = false;
                bool NOT = false;
                if (cqlStringItems[i] == "AND") { i++; }
                if (cqlStringItems[i] == "OR") { AND = false; OR = true; i++; }
                if (cqlStringItems[i] == "NOT") { AND = false; NOT = true; i++; }
                if ((NOT && !toreturn) || (AND && !toreturn))
                    break;
                // valid cql starts always with the column name
                string column = cqlStringItems[i];
                int columnIndex = row.Table.Columns.IndexOf(column);
                Type t = row.Table.Columns[columnIndex].DataType;
                if (columnIndex < 0)
                    break;
                i++;
                string comparer = cqlStringItems[i];
                i++;
                // if the comparer isn't in the comparerslist stop
                if (!comparers.Contains(comparer))
                    break;
                if (comparer == comparers[8])//IN 
                {
                    // read all the items until the list is closed by ')' and merge them
                    // all items are assumed to be separated by space merge them first
                    // items are merged because a item might contain a space itself, 
                    // and in this case it's splitted at the wrong place
                    string IN = "";
                    while (!cqlStringItems[i].Contains(")"))
                    {
                        IN = IN + " " + cqlStringItems[i];
                        i++;
                    }
                    IN = IN + " " + cqlStringItems[i];
                    string[] splitters = { "('", "', '", "','", "')" };
                    List<string> items = IN.Split(splitters, StringSplitOptions.RemoveEmptyEntries).ToList();

                    tmpResult = items.Contains(Convert.ToString(row[columnIndex], NfInfo));
                }
                else if (comparer == comparers[7])//LIKE
                {
                    // to implement
                    //tmpResult = true;
                }
                else if (comparer == comparers[6])//BETWEEN
                {
                    // get type number of string
                    if (t == typeof(string))
                    {
                        string string1 = cqlStringItems[i];
                        i += 2; // skip the AND in BETWEEN
                        string string2 = cqlStringItems[i];
                        tmpResult = 0 < String.Compare(Convert.ToString(row[columnIndex], NfInfo), string1, Ordinal) &&
                                    0 > String.Compare(Convert.ToString(row[columnIndex], NfInfo), string2, Ordinal);

                    }
                    else if (t == typeof(double))
                    {
                        double value1 = Convert.ToDouble(cqlStringItems[i], NfInfo);
                        i += 2; // skip the AND in BETWEEN
                        double value2 = Convert.ToDouble(cqlStringItems[i], NfInfo);
                        tmpResult = value1 < Convert.ToDouble(row[columnIndex], NfInfo) && value2 > Convert.ToDouble(row[columnIndex], NfInfo);
                    }
                    else if (t == typeof(int))
                    {
                        int value1 = Convert.ToInt32(cqlStringItems[i]);
                        i += 2;
                        int value2 = Convert.ToInt32(cqlStringItems[i]);
                        tmpResult = value1 < Convert.ToInt32(row[columnIndex], NfInfo) && value2 > Convert.ToInt32(row[columnIndex], NfInfo);
                    }
                }
                else
                {
                    if (t == typeof(string))
                    {
                        string cqlValue = Convert.ToString(cqlStringItems[i], NfInfo);
                        string rowValue = Convert.ToString(row[columnIndex], NfInfo);
                        if (comparer == comparers[5]) //>=
                        {
                            tmpResult = 0 <= String.Compare(rowValue, cqlValue, Ordinal);
                        }
                        else if (comparer == comparers[4]) //<=
                        {
                            tmpResult = 0 >= String.Compare(rowValue, cqlValue, Ordinal);
                        }
                        else if (comparer == comparers[3]) //>
                        {
                            tmpResult = 0 < String.Compare(rowValue, cqlValue, Ordinal);
                        }
                        else if (comparer == comparers[2]) //<
                        {
                            tmpResult = 0 > String.Compare(rowValue, cqlValue, Ordinal);
                        }
                        else if (comparer == comparers[1]) //!=
                        {
                            tmpResult = rowValue != cqlValue;
                        }
                        else if (comparer == comparers[0]) //==
                        {
                            tmpResult = rowValue == cqlValue;
                        }
                    }
                    else
                    {
                        double value = Convert.ToDouble(cqlStringItems[i], NfInfo);
                        if (comparer == comparers[5]) //>=
                        {
                            tmpResult = Convert.ToDouble(row[columnIndex], NfInfo) >= value;
                        }
                        else if (comparer == comparers[4]) //<=
                        {
                            tmpResult = Convert.ToDouble(row[columnIndex], NfInfo) <= value;
                        }
                        else if (comparer == comparers[3]) //>
                        {
                            tmpResult = Convert.ToDouble(row[columnIndex], NfInfo) > value;
                        }
                        else if (comparer == comparers[2]) //<
                        {
                            tmpResult = Convert.ToDouble(row[columnIndex], NfInfo) < value;
                        }
                        else if (comparer == comparers[1]) //!=
                        {
                            tmpResult = Convert.ToDouble(row[columnIndex], NfInfo) != value;
                        }
                        else if (comparer == comparers[0]) //==
                        {
                            tmpResult = Convert.ToDouble(row[columnIndex], NfInfo) == value;
                        }
                    }
                }
                if (AND)
                    toreturn = tmpResult;
                if (OR && tmpResult)
                    toreturn = true;
                if (toreturn && NOT && tmpResult)
                    toreturn = false;

            }
            //OpenLayers.Filter.Comparison.EQUAL_TO = “==”;
            //OpenLayers.Filter.Comparison.NOT_EQUAL_TO = “!=”;
            //OpenLayers.Filter.Comparison.LESS_THAN = “<”;
            //OpenLayers.Filter.Comparison.GREATER_THAN = “>”;
            //OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO = “<=”;
            //OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO = “>=”;
            //OpenLayers.Filter.Comparison.BETWEEN = “..”;
            //OpenLayers.Filter.Comparison.LIKE = “~”;
            //IN (,,)

            return toreturn;
        }
Пример #35
0
 /// <summary>
 /// Adds a feature row to the table.
 /// </summary>
 /// <param name="row">The feature row to add.</param>
 public void AddRow(FeatureDataRow <TOid> row)
 {
     Rows.Add(row);
 }
Пример #36
0
        private static void setFeatureRowFromIFeatureDataRecord(IFeatureDataRecord srcFeature, FeatureDataRow targetFeature)
        {
            for (int i = 0; i < srcFeature.FieldCount; i++)
            {
                string colName = srcFeature.GetName(i);
                targetFeature[colName] = srcFeature.GetValue(i);
            }

            targetFeature.Geometry = srcFeature.Geometry;

            targetFeature.IsFullyLoaded = targetFeature.IsFullyLoaded || srcFeature.IsFullyLoaded;
        }
Пример #37
0
 public FeatureDataRowProxy(FeatureDataRow row)
 {
     _row = row;
 }
Пример #38
0
 /// <summary>
 /// Returns the <see cref="System.Drawing.Color">color</see> based on an attribute value
 /// </summary>
 /// <param name="row">DataRow</param>
 /// <returns>Style generated by GetStyle-Delegate</returns>
 public SharpMap.Styles.IStyle GetStyle(SharpMap.Data.FeatureDataRow row)
 {
     return(GetStyle(row));
 }
Пример #39
0
        private string ToText(FeatureDataRow fdr)
        {
            var sb = new StringBuilder();
            if (fdr.Geometry != null)
            {
                sb.AppendFormat("Geometry:\n  Type: {0}\n  SRID: {1}\n", 
                    fdr.Geometry.GeometryType, fdr.Geometry.SRID);
                switch (fdr.Geometry.Dimension)
                {
                    case Dimension.Surface:
                        sb.AppendFormat("  Area: {0}\n", fdr.Geometry.Area);
                        break;
                    case Dimension.Curve:
                        sb.AppendFormat("  Length: {0}\n", fdr.Geometry.Length);
                        break;
                    case Dimension.Point:
                        sb.AppendFormat("  Position: {0}\n", fdr.Geometry.AsText());
                        break;
                }
            }

            sb.Append("Data:\n");
            foreach (DataColumn col in fdr.Table.Columns)
                sb.AppendFormat("  {0}: {1}\n", col.Caption, fdr[col] == DBNull.Value ? "NULL" : fdr[col]);

            Logger.Debug(fmh => fmh("\n{0}\n{1}", fdr.Table.TableName,  sb.ToString(0, sb.Length-1)));

            return sb.ToString(0, sb.Length - 1);
        }
Пример #40
0
 protected override double GetAttributeValue(FeatureDataRow row)
 {
     return Convert.ToDouble(row[_ColumnName]);
 }
Пример #41
0
        /// <summary>
        /// Creates a new table in a Microsoft SQL Server database and copies rows from an existing datasource.
        /// </summary>
        /// <remarks>
        /// <para>The datatable created will contain six extra columns besides the attribute data: "OID" (Object ID row),
        /// "WKB_Geometry" (Geometry stored as WKB), and Envelope_MinX, Envelope_MinY, Envelope_MaxX, Envelope_MaxY
        /// for geometry bounding box.</para>
        /// <para>
        /// <example>
        /// Upload a ShapeFile to a database:
        /// <code>
        /// public void CreateDatabase(string shapeFile)
        /// {
        ///		if (!System.IO.File.Exists(shapeFile))
        ///		{
        ///			MessageBox.Show("File not found");
        ///			return;
        ///		}
        ///		ShapeFile shp = new ShapeFile(shapeFile, false);
        ///		//Create tablename from filename
        ///		string tablename = shapeFile.Substring(shapeFile.LastIndexOf('\\') + 1,
        ///			shapeFile.LastIndexOf('.') - shapeFile.LastIndexOf('\\') - 1);
        ///		//Create connectionstring
        ///		string connstr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|GeoDatabase.mdf;Integrated Security=True;User Instance=True";
        ///		int count = SharpMap.Data.Providers.MsSql.CreateDataTable(shp, tablename, connstr);
        ///		MessageBox.Show("Uploaded " + count.ToString() + " features to datatable '" + tablename + "'");
        ///	}
        /// </code>
        /// </example>
        /// </para>
        /// </remarks>
        /// <param name="datasource">Datasource to upload</param>
        /// <param name="tablename">Name of table to create (existing table will be overwritten!)</param>
        /// <param name="connstr">Connection string to database</param>
        /// <returns>Number or rows inserted, -1 if failed and 0 if table created but no rows inserted.</returns>
        public static int CreateDataTable(SharpMap.Data.Providers.IProvider datasource, string tablename, string connstr)
        {
            datasource.Open();
            FeatureDataRow       geom    = datasource.GetFeature(0);
            DataColumnCollection columns = geom.Table.Columns;
            int counter = -1;

            using (SqlConnection conn = new SqlConnection(connstr))
            {
                SqlCommand command = new SqlCommand();
                command.Connection = conn;

                conn.Open();
                //Try to drop table if it exists
                try
                {
                    command.CommandText = "DROP TABLE \"" + tablename + "\";";
                    command.ExecuteNonQuery();
                }
                catch { }
                //Create new table for storing the datasource
                string sql = "CREATE TABLE " + tablename + " (oid INTEGER IDENTITY PRIMARY KEY, WKB_Geometry Image, " +
                             "Envelope_MinX real, Envelope_MinY real, Envelope_MaxX real, Envelope_MaxY real";
                foreach (DataColumn col in columns)
                {
                    if (col.DataType != typeof(String))
                    {
                        sql += ", " + col.ColumnName + " " + Type2SqlType(col.DataType).ToString();
                    }
                    else
                    {
                        sql += ", " + col.ColumnName + " VARCHAR(256)";
                    }
                }
                command.CommandText = sql + ");";
                command.ExecuteNonQuery();
                counter++;
                List <uint> indexes = datasource.GetObjectIDsInView(datasource.GetExtents());
                //Select all indexes in shapefile, loop through each feature and insert them one-by-one
                foreach (uint idx in indexes)
                {
                    //Get feature from shapefile
                    SharpMap.Data.FeatureDataRow    feature = datasource.GetFeature(idx);
                    SharpMap.Geometries.BoundingBox box     = feature.Geometry.GetBoundingBox();
                    if (counter == 0)
                    {
                        //Create insert script
                        string strSQL = " (";
                        foreach (DataColumn col in feature.Table.Columns)
                        {
                            strSQL += "@" + col.ColumnName + ",";
                        }

                        strSQL += "@WKB_Geometry,@Envelope_MinX,@Envelope_MinY, " +
                                  "@Envelope_MaxX,@Envelope_MaxY)";
                        strSQL = "INSERT INTO " + tablename + strSQL.Replace("@", "") + " VALUES" + strSQL;

                        command.CommandText = strSQL;
                        command.Parameters.Clear();
                        //Add datacolumn parameters
                        foreach (DataColumn col in feature.Table.Columns)
                        {
                            command.Parameters.Add("@" + col.ColumnName, Type2SqlType(col.DataType));
                        }

                        //Add geometry parameters
                        command.Parameters.Add("@WKB_Geometry", SqlDbType.VarBinary);
                        command.Parameters.Add("@Envelope_MinX", SqlDbType.Real);
                        command.Parameters.Add("@Envelope_MinY", SqlDbType.Real);
                        command.Parameters.Add("@Envelope_MaxX", SqlDbType.Real);
                        command.Parameters.Add("@Envelope_MaxY", SqlDbType.Real);
                    }
                    //Set values
                    foreach (DataColumn col in feature.Table.Columns)
                    {
                        command.Parameters["@" + col.ColumnName].Value = feature[col];
                    }
                    command.Parameters["@WKB_Geometry"].Value  = feature.Geometry.AsBinary();                    //Add the geometry as Well-Known Binary
                    command.Parameters["@Envelope_MinX"].Value = box.Left;
                    command.Parameters["@Envelope_MinY"].Value = box.Bottom;
                    command.Parameters["@Envelope_MaxX"].Value = box.Right;
                    command.Parameters["@Envelope_MaxY"].Value = box.Top;

                    //Insert row
                    command.ExecuteNonQuery();
                    counter++;
                }
                //Create indexes
                command.Parameters.Clear();
                command.CommandText = "CREATE INDEX [IDX_Envelope_MinX] ON " + tablename + " (Envelope_MinX)";
                command.ExecuteNonQuery();
                command.CommandText = "CREATE INDEX [IDX_Envelope_MinY] ON " + tablename + " (Envelope_MinY)";
                command.ExecuteNonQuery();
                command.CommandText = "CREATE INDEX [IDX_Envelope_MaxX] ON " + tablename + " (Envelope_MaxX)";
                command.ExecuteNonQuery();
                command.CommandText = "CREATE INDEX [IDX_Envelope_MaxY] ON " + tablename + " (Envelope_MaxY)";
                command.ExecuteNonQuery();

                conn.Close();
            }
            datasource.Close();
            return(counter);
        }
Пример #42
0
 /// <summary>
 /// Returns the style based on a numeric DataColumn, where style
 /// properties are linearly interpolated between max and min values.
 /// </summary>
 /// <param name="row">Feature</param>
 /// <returns><see cref="SharpMap.Styles.IStyle">Style</see> calculated by a linear interpolation between the min/max styles</returns>
 public virtual IStyle GetStyle(FeatureDataRow row)
 {
     double attr = 0;
     try
     {
         attr = GetAttributeValue(row);
     }
     catch
     {
         throw new ApplicationException(
             "Invalid Attribute type in Gradient Theme - Couldn't parse attribute (must be numerical)");
     }
     if (_minStyle.GetType() != _maxStyle.GetType())
         throw new ArgumentException("MinStyle and MaxStyle must be of the same type");
     switch (MinStyle.GetType().FullName)
     {
         case "SharpMap.Styles.VectorStyle":
             return CalculateVectorStyle(MinStyle as VectorStyle, MaxStyle as VectorStyle, attr);
         case "SharpMap.Styles.LabelStyle":
             return CalculateLabelStyle(MinStyle as LabelStyle, MaxStyle as LabelStyle, attr);
         default:
             throw new ArgumentException(
                 "Only SharpMap.Styles.VectorStyle and SharpMap.Styles.LabelStyle are supported for the gradient theme");
     }
 }
Пример #43
0
 protected abstract double GetAttributeValue(FeatureDataRow row);
Пример #44
0
 /// <summary>
 /// Generates the label text for a given feature.
 /// </summary>
 /// <param name="feature">The feature to label.</param>
 /// <returns>The text of the label.</returns>
 public string GetLabelText(FeatureDataRow feature)
 {
     if (_getLabelMethod != null)
     {
         return _getLabelMethod(feature);
     }
     else
     {
         if (feature.IsNull(LabelColumn))
         {
             return String.Empty;
         }
         else
         {
             return feature[LabelColumn].ToString();
         }
     }
 }
Пример #45
0
 /// <summary>
 /// Adds a row to the FeatureDataTable
 /// </summary>
 /// <param name="row"></param>
 public void AddRow(FeatureDataRow row)
 {
     base.Rows.Add(row);
 }
Пример #46
0
        private static void mergeFeature(FeatureDataTable target,
                                         IFeatureDataRecord srcFeature,
                                         FeatureDataRow targetFeature,
                                         ColumnMapper columnMapper,
                                         ICoordinateTransformation transform,
                                         IGeometryFactory geoFactory,
                                         Boolean preserveChanges)
        {
            if (targetFeature == null)
            {
                targetFeature = target.NewRow();
                setFeatureRowFromIFeatureDataRecord(srcFeature, targetFeature, columnMapper, transform, geoFactory);
                target.AddRow(targetFeature);
            }
            else
            {
                if (preserveChanges && targetFeature.RowState == DataRowState.Modified)
                {
                    throw new NotImplementedException("Merging updates to original features " +
                                                      "state not yet implemented.");
                }

                setFeatureRowFromIFeatureDataRecord(srcFeature, targetFeature, columnMapper, transform, geoFactory);
            }
        }
Пример #47
0
 /// <summary>
 /// Initializes a new instance of the FeatureDataRowChangeEventArgs class.
 /// </summary>
 /// <param name="row"></param>
 /// <param name="action"></param>
 public FeatureDataRowChangeEventArgs(FeatureDataRow row, DataRowAction action)
 {
     this.eventRow    = row;
     this.eventAction = action;
 }
Пример #48
0
        // FIX_PERF
        private static void setFeatureRowFromIFeatureDataRecord(IFeatureDataRecord srcFeature,
                                                                FeatureDataRow targetFeature,
                                                                ColumnMapper columnMapper,
                                                                ICoordinateTransformation transform,
                                                                IGeometryFactory geoFactory)
        {
            //for (Int32 i = 0; i < srcFeature.FieldCount; i++)
            //{
            //    String colName = srcFeature.GetName(i);
            //    targetFeature[colName] = srcFeature.GetValue(i);
            //}
            if (transform != null)//jd: to prevent case when transform is null -  probably because a test was done earlier. need to check
            {
                if (srcFeature.Geometry.SpatialReference.EqualParams(transform.Target))
                {
                    transform = null;
                }
            }

            srcFeature.GetValues(columnMapper.SourceValues);
            targetFeature.ItemArray = columnMapper.Map();
            targetFeature.Geometry = transform == null
                                         ? srcFeature.Geometry
                                         : transform.Transform(srcFeature.Geometry, geoFactory);
            targetFeature.IsFullyLoaded = targetFeature.IsFullyLoaded || srcFeature.IsFullyLoaded;
        }
Пример #49
0
 private static void mergeFeature(FeatureDataTable target, IFeatureDataRecord srcFeature, FeatureDataRow targetFeature, bool preserveChanges)
 {
     if (targetFeature == null)
     {
         targetFeature = target.NewRow();
         setFeatureRowFromIFeatureDataRecord(srcFeature, targetFeature);
         target.AddRow(targetFeature);
     }
     else
     {
         if (preserveChanges && targetFeature.RowState == DataRowState.Modified)
         {
             throw new NotImplementedException("Merging updates to original features state not yet implemented.");
         }
         else
         {
             setFeatureRowFromIFeatureDataRecord(srcFeature, targetFeature);
         }
     }
 }
 public Boolean Read()
 {
     bool read = false;
     if (_nextRowIndex < _table.Rows.Count)
     {
         _currentRow = _table[_nextRowIndex++];
         read = true;
     }
     
     return read;
 }
Пример #51
0
            public IStyle GetStyle(FeatureDataRow fdr)
            {
                VectorStyle retval = new VectorStyle();

                if (fdr["Bearing"] == DBNull.Value)
                {
                    Bitmap bmp = new Bitmap(36, 36);
                    Graphics g = Graphics.FromImage(bmp);
                    g.Clear(Color.Wheat);
                    g.FillEllipse(Brushes.Green, 0, 0, 36, 36);
                    g.DrawEllipse(new Pen(Brushes.Yellow, 3), 4, 4, 28, 28);
                    g.DrawString("H", new Font("Arial", 18, FontStyle.Bold), Brushes.Yellow, new RectangleF(2, 2, 34, 34), new StringFormat{ Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center});
                    g.Dispose();
                    bmp.MakeTransparent(Color.Wheat);
                    retval.Symbol = bmp;
                }
                else
                {
                    retval.Symbol = ColoredArrow(_brush);
                    Single rot =  (Single)(Double)fdr["Bearing"];
                    retval.SymbolRotation = rot % 360f;
                }
                return retval;

            }
Пример #52
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GeometryProvider"/>
 /// </summary>
 /// <param name="feature">Feature to be in this datasource</param>
 public GeometryProvider(FeatureDataRow feature)
 {
     _Geometries = new List<Geometry>();
     _Geometries.Add(feature.Geometry);
 }
Пример #53
0
 bool Filter(FeatureDataRow fdr)
 {
     return Convert.ToInt32(fdr[0]) == _id;
 }
Пример #54
0
        public void RenderLayer(IVectorLayer layer, Map map, System.Drawing.Graphics g)
        {
            if (map.Center == null)
            {
                throw (new ApplicationException("Cannot render map. View center not specified"));
            }

            g.SmoothingMode = layer.SmoothingMode;
            SharpMap.Geometries.BoundingBox envelope = map.Envelope; //View to render
            if (layer.CoordinateTransformation != null)
            {
                envelope = GeometryTransform.TransformBox(
                    envelope,
                    layer.CoordinateTransformation.MathTransform.Inverse());
            }

            //List<SharpMap.Geometries.Geometry> features = this.DataSource.GetGeometriesInView(map.Envelope);

            if (layer.DataSource == null)
            {
                throw (new ApplicationException("DataSource property not set on layer '" + layer.LayerName + "'"));
            }

            //If thematics is enabled, we use a slighty different rendering approach
            if (layer.Theme != null)
            {
                SharpMap.Data.FeatureDataSet ds = new SharpMap.Data.FeatureDataSet();
                layer.DataSource.Open();
                layer.DataSource.ExecuteIntersectionQuery(envelope, ds);
                layer.DataSource.Close();

                FeatureDataTable features = (FeatureDataTable)ds.Tables[0];

                if (layer.CoordinateTransformation != null)
                {
                    for (int i = 0; i < features.Count; i++)
                    {
                        features[i].Geometry = GeometryTransform.TransformGeometry(features[i].Geometry, layer.CoordinateTransformation.MathTransform);
                    }
                }

                //Linestring outlines is drawn by drawing the layer once with a thicker line
                //before drawing the "inline" on top.
                if (layer.Style.EnableOutline)
                {
                    //foreach (SharpMap.Geometries.Geometry feature in features)
                    for (int i = 0; i < features.Count; i++)
                    {
                        SharpMap.Data.FeatureDataRow feature = features[i];
                        //Draw background of all line-outlines first
                        if (feature.Geometry is SharpMap.Geometries.LineString)
                        {
                            IVectorStyle outlinestyle1 = layer.Theme.GetStyle(feature);
                            if (outlinestyle1.Enabled && outlinestyle1.EnableOutline)
                            {
                                SharpMap.Rendering.VectorRenderer.DrawLineString(g, feature.Geometry as LineString, outlinestyle1.Outline, map);
                            }
                        }
                        else if (feature.Geometry is SharpMap.Geometries.MultiLineString)
                        {
                            IVectorStyle outlinestyle2 = layer.Theme.GetStyle(feature);
                            if (outlinestyle2.Enabled && outlinestyle2.EnableOutline)
                            {
                                SharpMap.Rendering.VectorRenderer.DrawMultiLineString(g, feature.Geometry as MultiLineString, outlinestyle2.Outline, map);
                            }
                        }
                    }
                }

                for (int i = 0; i < features.Count; i++)
                {
                    SharpMap.Data.FeatureDataRow feature = features[i];
                    IVectorStyle style = layer.Theme.GetStyle(feature);
                    RenderGeometry(g, map, layer.ClippingEnabled, feature.Geometry, style);
                }
            }
            else
            {
                layer.DataSource.Open();

                Collection <Geometry> geoms = layer.DataSource.GetGeometriesInView(envelope);
                layer.DataSource.Close();

                if (layer.CoordinateTransformation != null)
                {
                    for (int i = 0; i < geoms.Count; i++)
                    {
                        geoms[i] = GeometryTransform.TransformGeometry(geoms[i], layer.CoordinateTransformation.MathTransform);
                    }
                }

                //Linestring outlines is drawn by drawing the layer once with a thicker line
                //before drawing the "inline" on top.
                if (layer.Style.EnableOutline)
                {
                    foreach (SharpMap.Geometries.Geometry geom in geoms)
                    {
                        if (geom != null)
                        {
                            //Draw background of all line-outlines first
                            switch (geom.GetType().FullName)
                            {
                            case "SharpMap.Geometries.LineString":
                                SharpMap.Rendering.VectorRenderer.DrawLineString(g, geom as LineString, layer.Style.Outline, map);
                                break;

                            case "SharpMap.Geometries.MultiLineString":
                                SharpMap.Rendering.VectorRenderer.DrawMultiLineString(g, geom as MultiLineString, layer.Style.Outline, map);
                                break;

                            default:
                                break;
                            }
                        }
                    }
                }

                for (int i = 0; i < geoms.Count; i++)
                {
                    if (geoms[i] != null)
                    {
                        RenderGeometry(g, map, layer.ClippingEnabled, geoms[i], layer.Style);
                    }
                }
            }


            //base.Render(g, map);
        }