Ejemplo n.º 1
0
        /// <summary>
        /// Converts coordinates in decimal degrees to projected meters.
        /// </summary>
        /// <param name="lonlat">The point in decimal degrees.</param>
        /// <returns>Point in projected meters</returns>
        public override SharpMap.Geometries.Point DegreesToMeters(SharpMap.Geometries.Point lonlat)
        {
            double dLongitude = Degrees2Radians(lonlat.X);
            double dLatitude  = Degrees2Radians(lonlat.Y);

            double con;                                 /* temporary angle variable             */
            double rh1;                                 /* height above ellipsoid               */
            double sinphi;                              /* sin value                            */
            double theta;                               /* angle                                */
            double ts;                                  /* small value t                        */


            con = Math.Abs(Math.Abs(dLatitude) - HALF_PI);
            if (con > EPSLN)
            {
                sinphi = Math.Sin(dLatitude);
                ts     = tsfnz(e, dLatitude, sinphi);
                rh1    = this._semiMajor * f0 * Math.Pow(ts, ns);
            }
            else
            {
                con = dLatitude * ns;
                if (con <= 0)
                {
                    throw new ApplicationException();
                }
                rh1 = 0;
            }
            theta = ns * adjust_lon(dLongitude - center_lon);
            return(new SharpMap.Geometries.Point(
                       rh1 * Math.Sin(theta) + this._falseEasting,
                       rh - rh1 * Math.Cos(theta) + this._falseNorthing));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Converts coordinates in decimal degrees to projected meters.
        /// </summary>
        /// <param name="lonlat">The point in decimal degrees.</param>
        /// <returns>Point in projected meters</returns>
        public override SharpMap.Geometries.Point DegreesToMeters(SharpMap.Geometries.Point lonlat)
        {
            double lon = Degrees2Radians(lonlat.X);
            double lat = Degrees2Radians(lonlat.Y);

            double delta_lon = 0.0;             /* Delta longitude (Given longitude - center    */
            double sin_phi, cos_phi;            /* sin and cos value				*/
            double al, als;                     /* temporary values				*/
            double c, t, tq;                    /* temporary values				*/
            double con, n, ml;                  /* cone constant, small m			*/

            delta_lon = adjust_lon(lon - central_meridian);
            sincos(lat, out sin_phi, out cos_phi);

            al  = cos_phi * delta_lon;
            als = Math.Pow(al, 2);
            c   = esp * Math.Pow(cos_phi, 2);
            tq  = Math.Tan(lat);
            t   = Math.Pow(tq, 2);
            con = 1.0 - es * Math.Pow(sin_phi, 2);
            n   = r_major / Math.Sqrt(con);
            ml  = r_major * mlfn(e0, e1, e2, e3, lat);

            return(new SharpMap.Geometries.Point(
                       scale_factor * n * al * (1.0 + als / 6.0 * (1.0 - t + c + als / 20.0 *
                                                                   (5.0 - 18.0 * t + Math.Pow(t, 2) + 72.0 * c - 58.0 * esp))) + false_easting
                       ,
                       scale_factor * (ml - ml0 + n * tq * (als * (0.5 + als / 24.0 *
                                                                   (5.0 - t + 9.0 * c + 4.0 * Math.Pow(c, 2) + als / 30.0 * (61.0 - 58.0 * t
                                                                                                                             + Math.Pow(t, 2) + 600.0 * c - 330.0 * esp))))) + false_northing));
        }
Ejemplo n.º 3
0
        private Bitmap GeneratePartialBitmap(SharpMap.Geometries.Point center, XPosition xPos, YPosition yPos)
        {
            double x = center.X, y = center.Y;

            switch (xPos)
            {
            case XPosition.Right:
                x += m_Map.Envelope.Width;
                break;

            case XPosition.Left:
                x -= m_Map.Envelope.Width;
                break;
            }

            switch (yPos)
            {
            case YPosition.Top:
                y += m_Map.Envelope.Height;
                break;

            case YPosition.Bottom:
                y -= m_Map.Envelope.Height;
                break;
            }

            m_Map.Center = new SharpMap.Geometries.Point(x, y);
            return(m_Map.GetMap() as Bitmap);
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Returns the geometry corresponding to the Object ID
 /// </summary>
 /// <param name="oid">Object ID</param>
 /// <returns>geometry</returns>
 public SharpMap.Geometries.Geometry GetGeometryByID(uint oid)
 {
     SharpMap.Geometries.Geometry geom = null;
     using (System.Data.OleDb.OleDbConnection conn = new OleDbConnection(_ConnectionString))
     {
         string strSQL = "Select " + this.XColumn + ", " + this.YColumn + " FROM " + this.Table + " WHERE " + this.ObjectIdColumn + "=" + oid.ToString();
         using (System.Data.OleDb.OleDbCommand command = new OleDbCommand(strSQL, conn))
         {
             conn.Open();
             using (System.Data.OleDb.OleDbDataReader dr = command.ExecuteReader())
             {
                 if (dr.Read())
                 {
                     //If the read row is OK, create a point geometry from the XColumn and YColumn and return it
                     if (dr[0] != DBNull.Value && dr[1] != DBNull.Value)
                     {
                         geom = new SharpMap.Geometries.Point((double)dr[0], (double)dr[1]);
                     }
                 }
             }
             conn.Close();
         }
     }
     return(geom);
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Converts coordinates in projected meters to decimal degrees.
        /// </summary>
        /// <param name="p">Point in meters</param>
        /// <returns>Transformed point in decimal degrees</returns>
        public override SharpMap.Geometries.Point MetersToDegrees(SharpMap.Geometries.Point p)
        {
            double dLongitude = Double.NaN;
            double dLatitude  = Double.NaN;

            /* Inverse equations
             * -----------------*/
            double dX = p.X - this._falseEasting;
            double dY = p.Y - this._falseNorthing;
            double ts = Math.Exp(-dY / (this._semiMajor * k0));           //t

            double chi = HALF_PI - 2 * Math.Atan(ts);
            double e4  = Math.Pow(e, 4);
            double e6  = Math.Pow(e, 6);
            double e8  = Math.Pow(e, 8);

            dLatitude = chi + (e2 * 0.5 + 5 * e4 / 24 + e6 / 12 + 13 * e8 / 360) * Math.Sin(2 * chi)
                        + (7 * e4 / 48 + 29 * e6 / 240 + 811 * e8 / 11520) * Math.Sin(4 * chi) +
                        +(7 * e6 / 120 + 81 * e8 / 1120) * Math.Sin(6 * chi) +
                        +(4279 * e8 / 161280) * Math.Sin(8 * chi);

            //dLatitude = phi2z(e,ts,out flag);

            /*if (flag != 0)
             * {
             *      throw new ApplicationException();
             * }*/
            dLongitude = (p.X - this._falseEasting) / (this._semiMajor * k0) + lon_center;
            //dLongitude = adjust_lon(lon_center + dX/(this._semiMajor * k0));

            return(new SharpMap.Geometries.Point(Radians2Degrees(dLongitude), Radians2Degrees(dLatitude)));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Returns the geometry corresponding to the Object ID
        /// </summary>
        /// <param name="oid">Object ID</param>
        /// <returns>geometry</returns>
        public SharpMap.Geometries.Geometry GetGeometryByID(uint oid)
        {
            SharpMap.Geometries.Geometry geom = null;
            using (PgConnection conn = new PgConnection(_ConnectionString))
            {
                String strSql = String.Format("SELECT AsBinary({0}) As Geom FROM {1} WHERE {2} = '{3}'",
                                              this.GeometryColumn,
                                              this.Table,
                                              this.ObjectIdColumn,
                                              oid);

                conn.Open();
                using (PgCommand command = new PgCommand(strSql, conn))
                {
                    using (PgDataReader dr = command.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            object obj = dr[0];
                            if (typeof(PgPoint) == obj.GetType())
                            {
                                geom = new SharpMap.Geometries.Point(((PgPoint)obj).X, ((PgPoint)obj).Y);
                            }
                            else if (obj != DBNull.Value)
                            {
                                geom = SharpMap.Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])dr[0]);
                            }
                        }
                    }
                }
                conn.Close();
            }
            return(geom);
        }
Ejemplo n.º 7
0
        public static SharpMap.Geometries.LinearRing CreateRectangle(SharpMap.Geometries.Point center, System.Drawing.SizeF size)
        {
            var wh = new System.Drawing.SizeF(size.Width * 0.5f, size.Height * 0.5f);
            var lt = new SharpMap.Geometries.Point(center.X - wh.Width, center.Y + wh.Height);
            var rb = new SharpMap.Geometries.Point(center.X + wh.Width, center.Y - wh.Height);

            return(CreateRectangle(lt, rb));
        }
 public MapZoomChangedEventArgs(double previousZoom, double currentZoom, GeoPoint previousCenter,
                                GeoPoint currentCenter)
 {
     _previousZoom   = previousZoom;
     _currentZoom    = currentZoom;
     _previousCenter = previousCenter;
     _currentCenter  = currentCenter;
 }
Ejemplo n.º 9
0
 public GeoPoint(SharpMap.Geometries.Point p)
 {
     this.X           = p.X;
     this.Y           = p.Y;
     this.Z           = 0;
     SpatialReference = null;
     dim = 0;
 }
Ejemplo n.º 10
0
 public void ImageToWorld_DefaultMap_ReturnValue()
 {
     SharpMap.Map map = new SharpMap.Map(new System.Drawing.Size(500, 200));
     map.Center = new SharpMap.Geometries.Point(23, 34);
     map.Zoom   = 1000;
     SharpMap.Geometries.Point p = map.ImageToWorld(new System.Drawing.PointF(242.5f, 92));
     Assert.AreEqual(new SharpMap.Geometries.Point(8, 50), p);
 }
 public MapZoomChangedEventArgs(double previousZoom, double currentZoom, GeoPoint previousCenter,
                                GeoPoint currentCenter)
 {
     _previousZoom = previousZoom;
     _currentZoom = currentZoom;
     _previousCenter = previousCenter;
     _currentCenter = currentCenter;
 }
Ejemplo n.º 12
0
        public static void EnsureVisible(SharpMap.Map map, SharpMap.Geometries.Point pt)
        {
            const double ensureVisibleRatio = 0.1d;

            //Get current map envelope
            var bb = map.Envelope;

            System.Console.WriteLine(string.Format("Map envelope: {0}", bb));

            //Set valid envelope
            var evbb = bb.Grow(-ensureVisibleRatio * bb.Width, -ensureVisibleRatio * bb.Height);

            System.Console.WriteLine(string.Format("Valid envelope: {0}", evbb));

            //Test if Point is in valid envelope
            if (evbb.Contains(pt))
            {
                return;
            }

            //It is not
            System.Console.WriteLine(string.Format("Valid envelope does not contain {0}", pt));

            //LineString from Map.Center -> to Point
            var ls = new SharpMap.Geometries.LineString(new[] { evbb.GetCentroid(), pt });

            System.Console.WriteLine(string.Format("LineString Map.Center -> Point: {0}", ls));

            //Setup Linestring from BoundingBox
            var gf      = new NetTopologySuite.Geometries.GeometryFactory();
            var evbbpts = new System.Collections.Generic.List <SharpMap.Geometries.Point>(
                new[] { evbb.TopLeft, evbb.TopRight, evbb.BottomRight, evbb.BottomLeft, evbb.TopLeft });
            var evbblinearring = new SharpMap.Geometries.LineString(evbbpts);

            System.Console.WriteLine(string.Format("Linestring of valid envelope: {0}", evbblinearring));

            // convert geometries to NTS
            var ntsevbb = (NetTopologySuite.Geometries.LineString)
                          SharpMap.Converters.NTS.GeometryConverter.ToNTSGeometry(evbblinearring, gf);
            var ntsls = (NetTopologySuite.Geometries.LineString)
                        SharpMap.Converters.NTS.GeometryConverter.ToNTSGeometry(ls, gf);

            // Get intersection point
            var intGeo = ntsevbb.Intersection(ntsls);
            var intPt  = (NetTopologySuite.Geometries.Point)intGeo;

            System.Console.WriteLine(string.Format("Intersection point is: {0}", intPt));

            //Compute offset
            var dx = pt.X - intPt.X;
            var dy = pt.Y - intPt.Y;

            System.Console.WriteLine(string.Format("Map.Center needs to be shifted by: [{0}, {1}]", dx, dy));

            //Set new center Center
            map.Center = new SharpMap.Geometries.Point(map.Center.X + dx, map.Center.Y + dy);
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Transforms a coordinate point. The passed parameter point should not be modified.
 /// </summary>
 /// <param name="point"></param>
 /// <returns></returns>
 public override SharpMap.Geometries.Point Transform(SharpMap.Geometries.Point point)
 {
     SharpMap.Geometries.Point pOut = point.Clone();
     pOut.X /= SourceGCS.AngularUnit.RadiansPerUnit;
     pOut.X -= SourceGCS.PrimeMeridian.Longitude / SourceGCS.PrimeMeridian.AngularUnit.RadiansPerUnit;
     pOut.X += TargetGCS.PrimeMeridian.Longitude / TargetGCS.PrimeMeridian.AngularUnit.RadiansPerUnit;
     pOut.X *= SourceGCS.AngularUnit.RadiansPerUnit;
     return(pOut);
 }
Ejemplo n.º 14
0
 private void mapImage_MouseDown(SharpMap.Geometries.Point WorldPos, MouseEventArgs ImagePos)
 {
     if (ImagePos.Button == MouseButtons.Right)
     {
         IsPositionStart = false;
         mapImage.Cursor = Cursors.Hand;
         label11.Visible = false;
     }
 }
Ejemplo n.º 15
0
        /// <summary>
        /// Converts coordinates in projected meters to decimal degrees.
        /// </summary>
        /// <param name="p">Point in meters</param>
        /// <returns>Transformed point in decimal degrees</returns>
        public override SharpMap.Geometries.Point MetersToDegrees(SharpMap.Geometries.Point p)
        {
            double con, phi;                    /* temporary angles				*/
            double delta_phi;                   /* difference between longitudes		*/
            long   i;                           /* counter variable				*/
            double sin_phi, cos_phi, tan_phi;   /* sin cos and tangent values	*/
            double c, cs, t, ts, n, r, d, ds;   /* temporary variables		*/
            long   max_iter = 6;                /* maximun number of iterations	*/


            double x = p.X - false_easting;
            double y = p.Y - false_northing;

            con = (ml0 + y / scale_factor) / r_major;
            phi = con;
            for (i = 0;; i++)
            {
                delta_phi = ((con + e1 * Math.Sin(2.0 * phi) - e2 * Math.Sin(4.0 * phi) + e3 * Math.Sin(6.0 * phi))
                             / e0) - phi;
                phi += delta_phi;
                if (Math.Abs(delta_phi) <= EPSLN)
                {
                    break;
                }
                if (i >= max_iter)
                {
                    throw new ApplicationException("Latitude failed to converge");
                }
            }
            if (Math.Abs(phi) < HALF_PI)
            {
                sincos(phi, out sin_phi, out cos_phi);
                tan_phi = Math.Tan(phi);
                c       = esp * Math.Pow(cos_phi, 2);
                cs      = Math.Pow(c, 2);
                t       = Math.Pow(tan_phi, 2);
                ts      = Math.Pow(t, 2);
                con     = 1.0 - es * Math.Pow(sin_phi, 2);
                n       = r_major / Math.Sqrt(con);
                r       = n * (1.0 - es) / con;
                d       = x / (n * scale_factor);
                ds      = Math.Pow(d, 2);

                double lat = phi - (n * tan_phi * ds / r) * (0.5 - ds / 24.0 * (5.0 + 3.0 * t +
                                                                                10.0 * c - 4.0 * cs - 9.0 * esp - ds / 30.0 * (61.0 + 90.0 * t +
                                                                                                                               298.0 * c + 45.0 * ts - 252.0 * esp - 3.0 * cs)));
                double lon = adjust_lon(central_meridian + (d * (1.0 - ds / 6.0 * (1.0 + 2.0 * t +
                                                                                   c - ds / 20.0 * (5.0 - 2.0 * c + 28.0 * t - 3.0 * cs + 8.0 * esp +
                                                                                                    24.0 * ts))) / cos_phi));
                return(new SharpMap.Geometries.Point(Radians2Degrees(lon), Radians2Degrees(lat)));
            }
            else
            {
                return(new SharpMap.Geometries.Point(Radians2Degrees(HALF_PI * sign(y)), Radians2Degrees(central_meridian)));
            }
        }
Ejemplo n.º 16
0
 private static IList <SMPoint> GetPoints(SqlGeometry geometry)
 {
     SMPoint[] pts = new SMPoint[(int)geometry.STNumPoints()];
     for (int i = 1; i <= (int)geometry.STNumPoints(); i++)
     {
         SqlGeometry ptGeometry = geometry.STPointN(i);
         pts[i - 1] = new SMPoint((double)ptGeometry.STX, (double)ptGeometry.STY);
     }
     return(pts);
 }
Ejemplo n.º 17
0
        private void GetBounds(SharpMap.Geometries.Point p1, SharpMap.Geometries.Point p2, out SharpMap.Geometries.Point lowerLeft, out SharpMap.Geometries.Point upperRight)
        {
            lowerLeft  = new SharpMap.Geometries.Point(Math.Min(p1.X, p2.X), Math.Min(p1.Y, p2.Y));
            upperRight = new SharpMap.Geometries.Point(Math.Max(p1.X, p2.X), Math.Max(p1.Y, p2.Y));

            System.Diagnostics.Debug.WriteLine("p1: " + p1);
            System.Diagnostics.Debug.WriteLine("p2: " + p2);
            System.Diagnostics.Debug.WriteLine("lowerLeft: " + lowerLeft);
            System.Diagnostics.Debug.WriteLine("upperRight: " + upperRight);
        }
Ejemplo n.º 18
0
 private static IList<SMPoint> GetPoints(SqlGeometry geometry)
 {
     SMPoint[] pts = new SMPoint[(int)geometry.STNumPoints()];
     for (int i = 0; i < (int)geometry.STNumPoints(); i++)
     {
         SqlGeometry ptGeometry = geometry.STPointN(i);
         pts[i] = new SMPoint((double)ptGeometry.STX, (double)ptGeometry.STY);
     }
     return pts;
 }
Ejemplo n.º 19
0
        private void panel1_Paint(object sender, PaintEventArgs e)
        {
            //绘制测距的线条
            if (this.mapImage.ActiveTool == SharpMap.Forms.MapImage.Tools.Distance)
            {
                if (arrayDistancePoint.Count > 1)
                {
                    SharpMap.Geometries.Point[] temp = new SharpMap.Geometries.Point[arrayDistancePoint.Count];
                    for (int i = 0; i < temp.Length; i++)
                    {
                        try
                        {
                            temp[i] = (SharpMap.Geometries.Point)arrayDistancePoint[i];
                            PointF tempDrawRECTPoint = this.mapImage.Map.WorldToImage(temp[i]);
                            e.Graphics.DrawRectangle(new Pen(Global.DistancePointColor, 7), tempDrawRECTPoint.X - 1, tempDrawRECTPoint.Y - 1, 2, 2);
                        }
                        catch
                        { }
                    }
                    PointF[] DrawLineArray = new PointF[temp.Length];
                    for (int k = 0; k < DrawLineArray.Length; k++)
                    {
                        try
                        {
                            DrawLineArray[k] = this.mapImage.Map.WorldToImage(temp[k]);
                        }
                        catch
                        { }
                    }
                    e.Graphics.DrawLines(new Pen(Global.DistanceLineColor, 2), DrawLineArray);

                    double totalDistance = 0;

                    for (int j = 1; j < temp.Length; j++)
                    {
                        try
                        {
                            if (temp[j] != temp[j - 1])
                            {
                                double distance = Math.Round(Math.Sqrt(Math.Pow(temp[j].X - temp[j - 1].X, 2) + Math.Pow(temp[j].Y - temp[j - 1].Y, 2)) * Global.MapDistanceKey, 1);
                                distance       = Math.Round(distance, 1);
                                totalDistance += distance;
                                SharpMap.Geometries.Point tempPoint = new SharpMap.Geometries.Point((temp[j].X - temp[j - 1].X) / 2 + temp[j - 1].X, (temp[j].Y - temp[j - 1].Y) / 2 + temp[j - 1].Y);
                                e.Graphics.DrawString(distance.ToString() + "m", this.Font, new SolidBrush(Global.DistanceTextColor), this.mapImage.Map.WorldToImage(tempPoint));
                            }
                        }
                        catch
                        { }
                    }
                    this.toolStripLabel1.Text = "总长度:" + totalDistance.ToString() + "m ";

                    temp = null;
                }
            }
        }
Ejemplo n.º 20
0
        public override FeatureList process(FeatureList input, FilterEnv env)
        {
            FeatureList output = new FeatureList();

            //Boolean encontrado = false;
            SharpMap.Geometries.BoundingBox boundingBox = new SharpMap.Geometries.BoundingBox(longitudeMin, latitudeMin, longitudeMax, latitudeMax);

            foreach (Feature feature in input)
            {
                //if type of features is Point
                if (feature.row.Geometry is SharpMap.Geometries.Point)
                {
                    SharpMap.Geometries.Point p = (SharpMap.Geometries.Point)feature.row.Geometry;
                    if (boundingBox.Contains(p.GetBoundingBox()))
                    {
                        output.Add(feature);
                    }
                }
                //if type of features is Polygon
                else if (feature.row.Geometry is SharpMap.Geometries.Polygon)
                {
                    SharpMap.Geometries.Polygon polygon = (SharpMap.Geometries.Polygon)feature.row.Geometry;
                    if (boundingBox.Contains(polygon.GetBoundingBox()))
                    {
                        output.Add(feature);
                    }
                }
                //if type of features is MultiPolygon
                else if (feature.row.Geometry is SharpMap.Geometries.MultiPolygon)
                {
                    SharpMap.Geometries.MultiPolygon mp = (SharpMap.Geometries.MultiPolygon)feature.row.Geometry;
                    SharpMap.Geometries.BoundingBox  bb = mp.GetBoundingBox();
                    if (boundingBox.Contains(bb))
                    {
                        output.Add(feature);
                    }
                }
            }

            if (successor != null)
            {
                if (successor is FeatureFilter)
                {
                    FeatureFilter filter = (FeatureFilter)successor;
                    FeatureList   l      = filter.process(output, env);
                }
                else if (successor is FragmentFilter)
                {
                    FragmentFilter filter = (FragmentFilter)successor;
                    FragmentList   l      = filter.process(output, env);
                }
            }

            return(output);
        }
 void MapBox_MouseDown(SharpMap.Geometries.Point WorldPos, MouseEventArgs ImagePos)
 {
     if (IsMouseInLegendBox(ImagePos) && ImagePos.Button == MouseButtons.Left)
     {
         _downPoint = new Point(ImagePos.X, ImagePos.Y);
     }
     else
     {
         _downPoint = null;
     }
 }
Ejemplo n.º 22
0
        public ImageMapPoint(SharpMap.Geometries.Geometry geom, SharpMap.Map map, ImageMapStyle mapStyle)
            : base(geom, map)
        {
            this.Radius = mapStyle.Point.Radius;

            SharpMap.Geometries.Point P = geom as SharpMap.Geometries.Point;
            PointF pf = map.WorldToImage(P);

            map.MapTransform.TransformPoints(new PointF[] { pf });
            center = new System.Drawing.Point((int)pf.X, (int)pf.Y);
        }
Ejemplo n.º 23
0
        private static void AddRing(SqlGeometryBuilder builder, SMLinearRing linearRing)
        {
            SMPoint pt = linearRing.StartPoint;

            builder.BeginFigure(pt.X, pt.Y);
            for (int i = 1; i < linearRing.NumPoints; i++)
            {
                pt = linearRing.Point(i);
                builder.AddLine(pt.X, pt.Y);
            }
            builder.EndFigure();
        }
Ejemplo n.º 24
0
        private void mapImage_MouseUp(SharpMap.Geometries.Point WorldPos, MouseEventArgs ImagePos)
        {
            if (ImagePos.Button == MouseButtons.Left)
            {
                //左键
                switch (this.mapImage.ActiveTool)
                {
                //测距
                case SharpMap.Forms.MapImage.Tools.Distance:
                    if (!isStartMoveDistane)
                    {
                        arrayDistancePoint.Clear();
                    }
                    if (arrayDistancePoint.Count == 0)
                    {
                        arrayDistancePoint.Add(WorldPos);
                    }
                    arrayDistancePoint.Add(WorldPos);

                    isStartMoveDistane = true;
                    break;
                }
            }
            else if (ImagePos.Button == MouseButtons.Right)
            {
                //右键
                switch (this.mapImage.ActiveTool)
                {
                //当测距时若正在测距则停止添加新点,若已经停止测距则恢复成平移模式。
                case SharpMap.Forms.MapImage.Tools.Distance:
                    if (isStartMoveDistane)
                    {
                        isStartMoveDistane = false;
                        arrayDistancePoint.RemoveAt(arrayDistancePoint.Count - 1);
                        this.panel1.Refresh();
                    }
                    else
                    {
                        goto default;
                    }
                    break;

                //其余的时候都恢复成平移
                default:
                    this.btn_ZommIn.Checked   = false;
                    this.btn_ZommOut.Checked  = false;
                    this.btn_Move.Checked     = true;
                    this.btn_Distance.Checked = false;
                    this.mapImage.ActiveTool  = SharpMap.Forms.MapImage.Tools.Pan;
                    break;
                }
            }
        }
Ejemplo n.º 25
0
        public static SharpMap.Geometries.LinearRing CreateRectangle(SharpMap.Geometries.Point leftTop, SharpMap.Geometries.Point rightBottom)
        {
            var pts = new[]
            {
                leftTop,
                new SharpMap.Geometries.Point(rightBottom.X, leftTop.Y),
                rightBottom,
                new SharpMap.Geometries.Point(leftTop.X, rightBottom.Y),
                leftTop
            };

            return(new SharpMap.Geometries.LinearRing(pts));
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Transforms from world coordinate system (WCS) to image coordinates
        /// NOTE: This method DOES NOT take the MapTransform property into account (use SharpMap.Map.MapToWorld instead)
        /// </summary>
        /// <param name="p">Point in WCS</param>
        /// <param name="map">Map reference</param>
        /// <returns>Point in image coordinates</returns>
        public static System.Drawing.PointF WorldtoMap(SharpMap.Geometries.Point p, SharpMap.Map map)
        {
            //if (map.MapTransform != null && !map.MapTransform.IsIdentity)
            //	map.MapTransform.TransformPoints(new System.Drawing.PointF[] { p });
            System.Drawing.PointF result = new System.Drawing.Point();
            double Height = (map.Zoom * map.Size.Height) / map.Size.Width;
            double left   = map.Center.X - map.Zoom * 0.5;
            double top    = map.Center.Y + Height * 0.5 * map.PixelAspectRatio;

            result.X = (float)((p.X - left) / map.PixelWidth);
            result.Y = (float)((top - p.Y) / map.PixelHeight);
            return(result);
        }
Ejemplo n.º 27
0
 /// <summary>
 /// Initializes a new map
 /// </summary>
 /// <param name="size">Size of map in pixels</param>
 public Map(System.Drawing.Size size)
 {
     this.Size            = size;
     this.Layers          = new List <SharpMap.Layers.ILayer>();
     this.BackColor       = System.Drawing.Color.Transparent;
     this._MaximumZoom    = double.MaxValue;
     this._MinimumZoom    = 0;
     _MapTransform        = new System.Drawing.Drawing2D.Matrix();
     MapTransformInverted = new System.Drawing.Drawing2D.Matrix();
     _Center           = new SharpMap.Geometries.Point(0, 0);
     _Zoom             = 1;
     _PixelAspectRatio = 1.0;
 }
Ejemplo n.º 28
0
        private static void SharpMapLineStringToSqlGeometry(SqlGeometryBuilder geomBuilder, SMLineString lineString)
        {
            geomBuilder.BeginGeometry(OpenGisGeometryType.LineString);
            SMPoint point = lineString.StartPoint;

            geomBuilder.BeginFigure(point.X, point.Y);
            for (int i = 1; i < lineString.NumPoints; i++)
            {
                point = lineString.Point(i);
                geomBuilder.AddLine(point.X, point.Y);
            }
            geomBuilder.EndFigure();
            geomBuilder.EndGeometry();
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Renders a point to the map.
        /// </summary>
        /// <param name="g">Graphics reference</param>
        /// <param name="point">Point to render</param>
        /// <param name="symbol">Symbol to place over point</param>
        /// <param name="symbolscale">The amount that the symbol should be scaled. A scale of '1' equals to no scaling</param>
        /// <param name="offset">Symbol offset af scale=1</param>
        /// <param name="rotation">Symbol rotation in degrees</param>
        /// <param name="map">Map reference</param>
        public static void DrawPoint(System.Drawing.Graphics g, SharpMap.Geometries.Point point, System.Drawing.Bitmap symbol, float symbolscale, System.Drawing.PointF offset, float rotation, SharpMap.Map map)
        {
            if (point == null)
            {
                return;
            }
            if (symbol == null) //We have no point style - Use a default symbol
            {
                symbol = defaultsymbol;
            }

            System.Drawing.PointF pp = SharpMap.Utilities.Transform.WorldtoMap(point, map);

            Matrix startingTransform = g.Transform;

            if (rotation != 0 && !Single.IsNaN(rotation))
            {
                System.Drawing.PointF rotationCenter = System.Drawing.PointF.Add(pp, new System.Drawing.SizeF(symbol.Width / 2, symbol.Height / 2));
                Matrix transform = new Matrix();
                transform.RotateAt(rotation, rotationCenter);

                g.Transform = transform;

                if (symbolscale == 1f)
                {
                    g.DrawImageUnscaled(symbol, (int)(pp.X - symbol.Width / 2 + offset.X), (int)(pp.Y - symbol.Height / 2 + offset.Y));
                }
                else
                {
                    float width  = symbol.Width * symbolscale;
                    float height = symbol.Height * symbolscale;
                    g.DrawImage(symbol, (int)pp.X - width / 2 + offset.X * symbolscale, (int)pp.Y - height / 2 + offset.Y * symbolscale, width, height);
                }

                g.Transform = startingTransform;
            }
            else
            {
                if (symbolscale == 1f)
                {
                    g.DrawImageUnscaled(symbol, (int)(pp.X - symbol.Width / 2 + offset.X), (int)(pp.Y - symbol.Height / 2 + offset.Y));
                }
                else
                {
                    float width  = symbol.Width * symbolscale;
                    float height = symbol.Height * symbolscale;
                    g.DrawImage(symbol, (int)pp.X - width / 2 + offset.X * symbolscale, (int)pp.Y - height / 2 + offset.Y * symbolscale, width, height);
                }
            }
        }
Ejemplo n.º 30
0
 public override SharpMap.Geometries.Point Transform(SharpMap.Geometries.Point point)
 {
     if (!(point is SharpMap.Geometries.Point3D))
     {
         throw new ArgumentException("Datum transformation requires a 3D point");
     }
     if (!_isInverse)
     {
         return(Apply(point as SharpMap.Geometries.Point3D));
     }
     else
     {
         return(ApplyInverted(point as SharpMap.Geometries.Point3D));
     }
 }
Ejemplo n.º 31
0
        public void BL2XY(double iLongtitude, double iLatitude, out double iProjectedX, out double iProjectedY)
        {
            SharpMap.Geometries.Point ptInput = new SharpMap.Geometries.Point(iLongtitude, iLatitude);
            iProjectedX = -1;
            iProjectedY = -1;

            //if (Math.Abs(ptInput.X) > 360)
            //    return null;

            int nCenterLongitude = ((int)(ptInput.X / 3)) * 3;

            CoordinateSystemFactory cFac = new SharpMap.CoordinateSystems.CoordinateSystemFactory();
            //创建椭球体
            IEllipsoid       ellipsoid = cFac.CreateFlattenedSphere("Xian 1980", 6378140, 298.257, SharpMap.CoordinateSystems.LinearUnit.Metre);
            IHorizontalDatum datum     = cFac.CreateHorizontalDatum("Xian_1980", DatumType.HD_Geocentric, ellipsoid, null);

            //创建地理坐标系
            SharpMap.CoordinateSystems.IGeographicCoordinateSystem gcs = cFac.CreateGeographicCoordinateSystem(
                "Xian 1980", SharpMap.CoordinateSystems.AngularUnit.Degrees, datum,
                SharpMap.CoordinateSystems.PrimeMeridian.Greenwich,
                new AxisInfo("Lon", AxisOrientationEnum.East),
                new AxisInfo("Lat", AxisOrientationEnum.North));

            List <ProjectionParameter> parameters = new List <ProjectionParameter>(5);

            parameters.Add(new ProjectionParameter("latitude_of_origin", 0));
            parameters.Add(new ProjectionParameter("central_meridian", nCenterLongitude));
            parameters.Add(new ProjectionParameter("scale_factor", 1.0));
            parameters.Add(new ProjectionParameter("false_easting", 500000));
            parameters.Add(new ProjectionParameter("false_northing", 0.0));

            //创建投影坐标系
            SharpMap.CoordinateSystems.IProjection projection = cFac.CreateProjection("Transverse Mercator", "Transverse_Mercator", parameters);

            SharpMap.CoordinateSystems.IProjectedCoordinateSystem coordsys = cFac.CreateProjectedCoordinateSystem(
                "Xian_1980_3_Degree_GK_CM", gcs,
                projection, SharpMap.CoordinateSystems.LinearUnit.Metre,
                new AxisInfo("East", AxisOrientationEnum.East),
                new AxisInfo("North", AxisOrientationEnum.North));

            //创建坐标转换器
            ICoordinateTransformation trans = new CoordinateTransformationFactory().CreateFromCoordinateSystems(gcs, coordsys);

            //工作区坐标到投影坐标系的转换
            SharpMap.Geometries.Point ptOutput = trans.MathTransform.Transform(ptInput);
            iProjectedX = ptOutput.X;
            iProjectedY = ptOutput.Y;
        }
Ejemplo n.º 32
0
	protected void imgMap_Click(object sender, ImageClickEventArgs e)
	{
		//Set center of the map to where the client clicked
		//We set up a simple empty map so we can use the ImageToWorld() method for easy conversion from Image to World coordinates
		SharpMap.Map myMap = new SharpMap.Map(new Size(Convert.ToInt32(imgMap.Width.Value), Convert.ToInt32(imgMap.Height.Value)));
		myMap.Center = Center; myMap.Zoom = Zoom;
		Center = myMap.ImageToWorld(new System.Drawing.Point(e.X, e.Y));

		//Set zoom value if any of the zoom tools were selected
		if (rblMapTools.SelectedValue == "0") //Zoom in
			Zoom = Zoom * 0.5;
		else if (rblMapTools.SelectedValue == "1") //Zoom out
			Zoom = Zoom * 2;
		//Create the map
		GenerateMap();
	}
Ejemplo n.º 33
0
        /// <summary>
        /// Converts coordinates in projected meters to decimal degrees.
        /// </summary>
        /// <param name="p">Point in meters</param>
        /// <returns>Transformed point in decimal degrees</returns>
        public override SharpMap.Geometries.Point MetersToDegrees(SharpMap.Geometries.Point p)
        {
            double dLongitude = Double.NaN;
            double dLatitude  = Double.NaN;

            double rh1;                                 /* height above ellipsoid	*/
            double con;                                 /* sign variable		*/
            double ts;                                  /* small t			*/
            double theta;                               /* angle			*/
            long   flag;                                /* error flag			*/

            flag = 0;
            double dX = p.X - this._falseEasting;
            double dY = rh - p.Y + this._falseNorthing;

            if (ns > 0)
            {
                rh1 = Math.Sqrt(dX * dX + dY * dY);
                con = 1.0;
            }
            else
            {
                rh1 = -Math.Sqrt(dX * dX + dY * dY);
                con = -1.0;
            }
            theta = 0.0;
            if (rh1 != 0)
            {
                theta = Math.Atan2((con * dX), (con * dY));
            }
            if ((rh1 != 0) || (ns > 0.0))
            {
                con       = 1.0 / ns;
                ts        = Math.Pow((rh1 / (this._semiMajor * f0)), con);
                dLatitude = phi2z(e, ts, out flag);
                if (flag != 0)
                {
                    throw new ApplicationException();
                }
            }
            else
            {
                dLatitude = -HALF_PI;
            }
            dLongitude = adjust_lon(theta / ns + center_lon);
            return(new SharpMap.Geometries.Point(Radians2Degrees(dLongitude), Radians2Degrees(dLatitude)));
        }
        private void FormMovingObjectOverTileLayer_Load(object sender, EventArgs e)
        {

            //Lisbon...
#if DotSpatialProjections
            var mathTransform = LayerTools.Wgs84toGoogleMercator;
            SharpMap.Geometries.BoundingBox geom = GeometryTransform.TransformBox(
                new SharpMap.Geometries.BoundingBox(-9.205626, 38.690993, -9.123736, 38.740837),
                mathTransform.Source, mathTransform.Target);
#else
            var mathTransform = LayerTools.Wgs84toGoogleMercator.MathTransform;
            SharpMap.Geometries.BoundingBox geom = GeometryTransform.TransformBox(
                new SharpMap.Geometries.BoundingBox(-9.205626, 38.690993, -9.123736, 38.740837),
                mathTransform);
#endif


            //Google Background
            TileAsyncLayer layer2 = new TileAsyncLayer(new OsmTileSource(), "TileLayer - OSM");


            this.mapBox1.Map.BackgroundLayer.Add(layer2);

            //Adds a static layer
            VectorLayer staticLayer = new VectorLayer("Fixed Marker");
            //position = geom.GetCentroid();
            List<SharpMap.Geometries.Geometry> aux = new List<SharpMap.Geometries.Geometry>();
            aux.Add(geom.GetCentroid());
            staticLayer.Style.Symbol = Resources.PumpSmall;
            SharpMap.Data.Providers.GeometryProvider geoProviderFixed = new SharpMap.Data.Providers.GeometryProvider(aux);
            staticLayer.DataSource = geoProviderFixed;
            this.mapBox1.Map.Layers.Add(staticLayer);

            
            //Adds a moving variable layer
            VectorLayer pushPinLayer = new VectorLayer("PushPins");
            position = geom.GetCentroid();
            geos.Add(position);
            pushPinLayer.Style.Symbol = Resources.OutfallSmall;
            SharpMap.Data.Providers.GeometryProvider geoProvider = new SharpMap.Data.Providers.GeometryProvider(geos);
            pushPinLayer.DataSource = geoProvider;
            this.mapBox1.Map.VariableLayers.Add(pushPinLayer);

            this.mapBox1.Map.ZoomToBox(geom);
            this.mapBox1.Refresh();

        }
Ejemplo n.º 35
0
	protected void Page_Load(object sender, EventArgs e)
	{
		if (Page.IsPostBack) 
		{
			//Page is post back. Restore center and zoom-values from viewstate
			Center = (SharpMap.Geometries.Point)ViewState["mapCenter"];
			Zoom = (double)ViewState["mapZoom"];
		}
		else
		{
			Center = new SharpMap.Geometries.Point(0,0);
			Zoom = 360;
			//Create the map
			GenerateMap();
		}
		PrintWmsInfo();
	}
Ejemplo n.º 36
0
	protected void Page_Load(object sender, EventArgs e)
	{
		if (Page.IsPostBack) 
		{
			//Page is post back. Restore center and zoom-values from viewstate
			Center = (SharpMap.Geometries.Point)ViewState["mapCenter"];
			Zoom = (double)ViewState["mapZoom"];
		}
		else
		{
			//This is the initial view of the map.
			Center = new SharpMap.Geometries.Point(12,48);
			Zoom = 45;
			//Create the map
			GenerateMap();
		}
	}
Ejemplo n.º 37
0
	protected void ddlProjection_SelectedIndexChanged(object sender, EventArgs e)
	{
		//Transform current view to new coordinate system and zoom to the transformed box
		string PreviousProj = ViewState["currentProj"].ToString();
		string SelectedProj = ddlProjection.SelectedValue;

		//Points defining the current view 
		SharpMap.Geometries.Point left = new SharpMap.Geometries.Point(myMap.Envelope.Left, myMap.Center.Y);
		SharpMap.Geometries.Point right = new SharpMap.Geometries.Point(myMap.Envelope.Right, myMap.Center.Y);
		SharpMap.Geometries.Point center = myMap.Center;

		if (PreviousProj != "Pseudo")
		{
			//Transform current view back to geographic coordinates
			ICoordinateTransformation trans = GetTransform(PreviousProj);
			left = GeometryTransform.TransformPoint(new SharpMap.Geometries.Point(myMap.Envelope.Left, myMap.Center.Y), trans.MathTransform.Inverse());
			right = GeometryTransform.TransformPoint(new SharpMap.Geometries.Point(myMap.Envelope.Right, myMap.Center.Y), trans.MathTransform.Inverse());
			center = GeometryTransform.TransformPoint(myMap.Center, trans.MathTransform.Inverse());
		}
		//If both PreviousSRID and SelectedSRID are projected coordsys, first transform to geographic

		if (SelectedProj == "Pseudo")
		{
			myMap.Center = center;
			myMap.Zoom = Math.Abs(right.X - left.X);
		}
		else //Project coordinates to new projection
		{
			//Transform back to geographic and over to new projection
			ICoordinateTransformation trans = GetTransform(SelectedProj);
			left = GeometryTransform.TransformPoint(left, trans.MathTransform);
			right = GeometryTransform.TransformPoint(right, trans.MathTransform);
			center = GeometryTransform.TransformPoint(center, trans.MathTransform);
			myMap.Center = center;
			myMap.Zoom = Math.Abs(right.X - left.X);
			SharpMap.Geometries.BoundingBox envelopeGcs =GeometryTransform.TransformBox(myMap.Envelope, trans.MathTransform.Inverse());
			litEnvelopeLatLong.Text = envelopeGcs.ToString();
		}
		GenerateMap();
	}
Ejemplo n.º 38
0
 /// <summary>
 /// Renders a point to the map.
 /// </summary>
 /// <param name="g">Graphics reference</param>
 /// <param name="point">Point to render</param>
 /// <param name="symbol">Symbol to place over point</param>
 /// <param name="symbolscale">The amount that the symbol should be scaled. A scale of '1' equals to no scaling</param>
 /// <param name="offset">Symbol offset af scale=1</param>
 /// <param name="rotation">Symbol rotation in degrees</param>
 /// <param name="map">Map reference</param>
 public static void DrawCircle(System.Drawing.Graphics g, SharpMap.Geometries.GISCircle circle, System.Drawing.Brush brush, System.Drawing.Pen pen, bool clip, SharpMap.Map map)
 {
     if (circle == null)
         return;
       double radius = circle.RadiusSexagecimal;
     SharpMap.Geometries.Point p = new SharpMap.Geometries.Point(circle.X - radius, circle.Y - radius);
     System.Drawing.PointF pp0 = SharpMap.Utilities.Transform.WorldtoMap(p, map);
     p.X = circle.X + radius;
     p.Y = circle.Y + radius;
     System.Drawing.PointF pp1 = SharpMap.Utilities.Transform.WorldtoMap(p, map);
     System.Drawing.Rectangle rect = new System.Drawing.Rectangle((int)pp0.X, (int)pp0.Y, (int)(pp1.X - pp0.X), (int)(pp1.Y - pp0.Y));
     g.FillEllipse(brush, rect);
     g.DrawEllipse(pen, rect);
     pp1 = SharpMap.Utilities.Transform.WorldtoMap(circle, map);
 }
Ejemplo n.º 39
0
        public override FeatureList process(FeatureList input, FilterEnv env)
        {
            FeatureList output = new FeatureList();

            // HACER ALGO DEL ESTILO:

            if (transform == null)
            {
                //Create zone UTM 32N projection
                IProjectedCoordinateSystem utmProj = CreateUtmProjection(32);

                //Create geographic coordinate system (lets just reuse the CS from the projection)
                IGeographicCoordinateSystem geoCS = utmProj.GeographicCoordinateSystem;

                //Create transformation
                CoordinateTransformationFactory ctFac = new CoordinateTransformationFactory();

                // TODO DANI Mirar de donde viene este source y target
                ICoordinateTransformation Coordinatetransform = null;// TODO = ctFac.CreateFromCoordinateSystems(source, target);

                //cs
                string wkt = "GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137,298.257223563]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.0174532925199433]]";
                //ICoordinateSystem cs = SharpMap.Converters.WellKnownText.CoordinateSystemWktReader.Parse(wkt) as ICoordinateSystem;
                ICoordinateSystem cs = ProjNet.Converters.WellKnownText.CoordinateSystemWktReader.Parse(wkt) as ICoordinateSystem;
                //wgs84
                GeographicCoordinateSystem wgs84 = GeographicCoordinateSystem.WGS84;

                //gcs
                CoordinateSystemFactory cFac = new ProjNet.CoordinateSystems.CoordinateSystemFactory();
                //CoordinateSystemFactory cFac = new SharpMap.CoordinateSystems.CoordinateSystemFactory();
                //Create Bessel 1840 geographic coordinate system
                IEllipsoid ellipsoid = cFac.CreateFlattenedSphere("Bessel 1840", 6377397.155, 299.15281, LinearUnit.Metre);
                IHorizontalDatum datum = cFac.CreateHorizontalDatum("Bessel 1840", DatumType.HD_Geocentric, ellipsoid, null);
                IGeographicCoordinateSystem gcs = cFac.CreateGeographicCoordinateSystem("Bessel 1840", AngularUnit.Degrees, datum,
                    PrimeMeridian.Greenwich, new AxisInfo("Lon", AxisOrientationEnum.East),
                    new AxisInfo("Lat", AxisOrientationEnum.North));

                //coordsys
                //Collection<ProjectionParameter> parameters = new Collection<ProjectionParameter>(5);
                List<ProjectionParameter> parameters = new List<ProjectionParameter>();
                parameters.Add(new ProjectionParameter("latitude_of_origin", 0));
                parameters.Add(new ProjectionParameter("central_meridian", 110));
                parameters.Add(new ProjectionParameter("scale_factor", 0.997));
                parameters.Add(new ProjectionParameter("false_easting", 3900000));
                parameters.Add(new ProjectionParameter("false_northing", 900000));
                IProjection projection = cFac.CreateProjection("Mercator_1SP", "Mercator_1SP", parameters);
                IProjectedCoordinateSystem coordsys =
               cFac.CreateProjectedCoordinateSystem("Makassar / NEIEZ", gcs, projection, LinearUnit.Metre,
                                                    new AxisInfo("East", AxisOrientationEnum.East),
                                                    new AxisInfo("North", AxisOrientationEnum.North));

                Coordinatetransform = ctFac.CreateFromCoordinateSystems(gcs, coordsys);//gcsWGS84 -> gcenCsWGS84

                //Apply transformation
                transform = Coordinatetransform.MathTransform;

            }

            SharpMap.Geometries.Point p = new SharpMap.Geometries.Point(30.0, 20.0);

            p = GeometryTransform.TransformPoint(p,transform);
/*IMPORTANTE
            foreach (Feature feature in input)
            {
                feature.row.Geometry = GeometryTransform.TransformGeometry(feature.row.Geometry, transform);
                //feature.row.Geometry = GeometryTransform.TransformMultiPolygon(feature.row.Geometry, transform);
            }
IMPORTANTE*/
            foreach (Feature f in input)
            {
                output.Add(f);//output = input
            }

            // Cosas a cambiar:
            // Primero, la construccion del transform está siguiendo el ejemplo, pero hay que tener en cuenta los datos del xml y construirlo en consecuencia
            // Segundo, el filtro debe retornar una NUEVA lista, y no modificar la inicial. Ahora modifica los valores de la lista inicial
            // IMPORTANTE RETORNAR NUEVA LISTA OUTPUT <----------- FALTA POR HACER
#if TODO
            // first time through, establish a working SRS for output data.
            if (working_srs == null)
            {
                // first try to use the terrain SRS if so directed:
                SpatialReference new_out_srs = getUseTerrainSRS() ? env.getTerrainSRS() : null;
                if (new_out_srs == null)
                {
                    // failing that, see if we have an SRS in a resource:
                    if (getSRS() == null && getSRSScript() != null)
                    {
                        ScriptResult r = env.getScriptEngine().run(getSRSScript(), env);
                        if (r.isValid())
                            setSRS(env.getSession().getResources().getSRS(r.ToString()));
                        else
                            env.getReport().error(r.ToString());
                    }

                    new_out_srs = srs;
                }

                // set the "working" SRS that will be used for all features passing though this filter:
                working_srs = new_out_srs != null ? new_out_srs : env.getInputSRS();

                // LOCALIZE points around a local origin (the working extent's centroid)
                if (working_srs != null && getLocalize()) //&& env.getExtent().getArea() > 0.0 )
                {
                    if (env.getCellExtent().getSRS().isGeographic() && env.getCellExtent().getWidth() > 179.0)
                    {
                        //NOP - no localization for big geog extent ... needs more thought perhaps
                    }
                    else
                    {
                        GeoPoint centroid0 = new_out_srs != null ?
                            new_out_srs.transform(env.getCellExtent().getCentroid()) :
                            env.getCellExtent().getCentroid();

                        // we do want the localizer point on the surface if possible:
                        GeoPoint centroid = clampToTerrain(centroid0, env);
                        if (centroid == null)
                            centroid = centroid0;

                        Matrixd localizer;

                        // For geocentric datasets, we need a special localizer matrix:
                        if (working_srs.isGeocentric())
                        {
                            localizer = working_srs.getEllipsoid().createGeocentricInvRefFrame(centroid);
                            localizer.invert(localizer);
                        }

                        // For projected datasets, just a simple translation:
                        else
                        {
                            localizer = osg.Matrixd.translate(-centroid);
                        }

                        working_srs = working_srs.cloneWithNewReferenceFrame(localizer);
                    }
                }
            }

            // we have to assign the output SRS on each pass
            if (working_srs != null)
            {
                env.setOutputSRS(working_srs);
            }

            return base.process(input, env);
#endif
            //throw new NotImplementedException();

            if (successor != null)
            {
                if (successor is FeatureFilter)
                {
                    FeatureFilter filter = (FeatureFilter)successor;
                    FeatureList l = filter.process(output, env);
                }
                else if (successor is FragmentFilter)
                {
                    FragmentFilter filter = (FragmentFilter)successor;
                    FragmentList l = filter.process(output, env);
                }
            }

            return output;
        }
Ejemplo n.º 40
0
 /// <summary>
 /// Calculate the floating point error metric 
 /// </summary>
 /// <returns></returns>
 public double ErrorMetric(SharpMap.Geometries.BoundingBox box)
 {
     SharpMap.Geometries.Point temp = new SharpMap.Geometries.Point(1, 1) + (box.Max - box.Min);
     return temp.X*temp.Y;
 }
Ejemplo n.º 41
0
        protected override void OnMouseUp(MouseEventArgs e)
        {
            base.OnMouseUp(e);
            if (_map != null)
            {
                if (MouseUp != null)
                    MouseUp(_map.ImageToWorld(new Point(e.X, e.Y)), e);

                if (e.Button == MouseButtons.Left || e.Button == MouseButtons.Middle)
                {
                    if (_activeTool == Tools.ZoomOut)
                    {
                        double scale = 0.5;
                        if (_dragging)
                        {
                            if (e.Y - _dragStartPoint.Y < 0) //Zoom out
                                scale = (float)Math.Pow(1 / (float)(_dragStartPoint.Y - e.Y), 0.5);
                            else //Zoom in
                                scale = 1 + (e.Y - _dragStartPoint.Y) * 0.1;
                        }
                        else
                        {
                            _map.Center = _map.ImageToWorld(new Point(e.X, e.Y));

                            if (MapCenterChanged != null)
                                MapCenterChanged(_map.Center);
                        }

                        _map.Zoom /= scale;

                        if (MapZoomChanged != null)
                            MapZoomChanged(_map.Zoom);
                    }
                    else if (_activeTool == Tools.ZoomIn)
                    {
                        double scale = 2;
                        if (_dragging)
                        {
                            if (e.Y - _dragStartPoint.Y < 0) //Zoom out
                                scale = (float)Math.Pow(1 / (float)(_dragStartPoint.Y - e.Y), 0.5);
                            else //Zoom in
                                scale = 1 + (e.Y - _dragStartPoint.Y) * 0.1;
                        }
                        else
                        {
                            _map.Center = _map.ImageToWorld(new Point(e.X, e.Y));

                            if (MapCenterChanged != null)
                                MapCenterChanged(_map.Center);
                        }

                        _map.Zoom *= 1 / scale;

                        if (MapZoomChanged != null)
                            MapZoomChanged(_map.Zoom);

                    }
                    else if ((_activeTool == Tools.Pan && !(_shiftButtonDragRectangleZoom && (Control.ModifierKeys & Keys.Shift) != Keys.None)) ||
                        (e.Button == System.Windows.Forms.MouseButtons.Left && _dragging && (_activeTool == Tools.DrawLine || _activeTool == Tools.DrawPolygon)))
                    {
                        if (_dragging)
                        {
                            if (MapCenterChanged != null)
                                MapCenterChanged(_map.Center);
                        }
                        else
                        {
                            if (_panOnClick)
                            {
                                _map.Center = _map.ImageToWorld(new Point(e.X, e.Y));

                                if (MapCenterChanged != null)
                                    MapCenterChanged(_map.Center);
                            }
                        }
                    }
                    else if (_activeTool == Tools.Query || _activeTool == Tools.QueryGeometry)
                    {
                        if (_map.Layers.Count > _queryLayerIndex && _queryLayerIndex > -1)
                        {
                            var layer = _map.Layers[_queryLayerIndex] as ICanQueryLayer;
                            if (layer != null)
                            {
                                BoundingBox bounding;
                                bool isPoint = false;
                                if (_dragging)
                                {
                                    GeoPoint lowerLeft;
                                    GeoPoint upperRight;
                                    GetBounds(_map.ImageToWorld(_dragStartPoint), _map.ImageToWorld(_dragEndPoint), out lowerLeft, out upperRight);

                                    bounding = new BoundingBox(lowerLeft, upperRight);
                                }
                                else
                                {
                                    bounding =
                                        _map.ImageToWorld(new Point(e.X, e.Y)).GetBoundingBox().Grow(_map.PixelSize*
                                                                                                     _queryGrowFactor);
                                    isPoint = true;
                                }

                                Data.FeatureDataSet ds = new Data.FeatureDataSet();
                                if (_activeTool == Tools.Query)
                                    layer.ExecuteIntersectionQuery(bounding, ds);
                                else
                                {
                                    Geometry geom;
                                    if (isPoint && QueryGrowFactor == 0)
                                        geom = _map.ImageToWorld(new Point(e.X, e.Y));
                                    else    
                                        geom = bounding.ToGeometry();
                                    layer.ExecuteIntersectionQuery(geom, ds);
                                }

                                if (ds.Tables.Count > 0)
                                    if (MapQueried != null) MapQueried(ds.Tables[0]);
                                    else if (MapQueried != null) MapQueried(new Data.FeatureDataTable());
                            }

                        }
                        else
                            MessageBox.Show("No active layer to query");
                    }
                    else if (_activeTool == Tools.ZoomWindow || (_shiftButtonDragRectangleZoom && (Control.ModifierKeys & Keys.Shift) != Keys.None))
                    {
                        if (_rectangle.Width > 0 && _rectangle.Height > 0)
                        {
                            GeoPoint lowerLeft;
                            GeoPoint upperRight;
                            GetBounds(_map.ImageToWorld(_dragStartPoint), _map.ImageToWorld(_dragEndPoint), out lowerLeft, out upperRight);
                            _dragEndPoint.X = 0;
                            _dragEndPoint.Y = 0;

                            _map.ZoomToBox(new BoundingBox(lowerLeft, upperRight));
                            
                            if (MapZoomChanged != null)
                                MapZoomChanged(_map.Zoom);

                        }
                    }
                    else if (_activeTool == Tools.DrawPoint)
                    {
                        if (GeometryDefined != null)
                        {
                            GeometryDefined(Map.ImageToWorld(new PointF(e.X, e.Y)));
                        }
                    }
                    else if (_activeTool == Tools.DrawPolygon || _activeTool == Tools.DrawLine)
                    {
                        //pointArray = null;
                        if (_pointArray == null)
                        {
                            _pointArray = new SharpMap.Geometries.Point[2];
                            _pointArray[0] = Map.ImageToWorld(e.Location);
                            _pointArray[1] = Map.ImageToWorld(e.Location);
                        }
                        else
                        {
                            SharpMap.Geometries.Point[] temp = new SharpMap.Geometries.Point[_pointArray.GetUpperBound(0) + 2];
                            for (int i = 0; i <= _pointArray.GetUpperBound(0); i++)
                                temp[i] = _pointArray[i];

                            temp[temp.GetUpperBound(0)] = Map.ImageToWorld(e.Location);
                            _pointArray = temp;
                        }
                    }
                }


                if (_dragging)
                {
                    _dragging = false;
                    if (_activeTool == Tools.Query)
                        Invalidate(_rectangle);
                    if (_activeTool == Tools.ZoomWindow || _activeTool == Tools.Query)
                        _rectangle = Rectangle.Empty;

                    Refresh();
                }
                else if (_activeTool == Tools.ZoomIn || _activeTool == Tools.ZoomOut || _activeTool == Tools.Pan)
                {
                    Refresh();
                }
            }
        }
Ejemplo n.º 42
0
        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e);
            if (_map != null)
            {
                if (e.Button == MouseButtons.Left || e.Button == MouseButtons.Middle) //dragging
                {
                    _dragStartPoint = e.Location;
                    _dragEndPoint = e.Location;
                    _dragStartCoord = _map.Center;
                    _orgScale = _map.Zoom;
                }

                if (MouseDown != null)
                    MouseDown(_map.ImageToWorld(new Point(e.X, e.Y)), e);
            }
        }
Ejemplo n.º 43
0
        private Bitmap GeneratePartialBitmap(GeoPoint center, XPosition xPos, YPosition yPos)
        {
            double x = center.X, y = center.Y;

            switch (xPos)
            {
                case XPosition.Right:
                    x += _map.Envelope.Width;
                    break;
                case XPosition.Left:
                    x -= _map.Envelope.Width;
                    break;
            }

            switch (yPos)
            {
                case YPosition.Top:
                    y += _map.Envelope.Height;
                    break;
                case YPosition.Bottom:
                    y -= _map.Envelope.Height;
                    break;
            }

            _map.Center = new GeoPoint(x, y);
            return _map.GetMap() as Bitmap;
        }
Ejemplo n.º 44
0
 /// <summary>
 /// Returns the geometry corresponding to the Object ID
 /// </summary>
 /// <param name="oid">Object ID</param>
 /// <returns>geometry</returns>
 public SharpMap.Geometries.Geometry GetGeometryByID(uint oid)
 {
     SharpMap.Geometries.Geometry geom = null;
     using (System.Data.OleDb.OleDbConnection conn = new OleDbConnection(_ConnectionString))
     {
         string strSQL = "Select " + this.XColumn + ", " + this.YColumn + " FROM " + this.Table + " WHERE " + this.ObjectIdColumn + "=" + oid.ToString();
         using (System.Data.OleDb.OleDbCommand command = new OleDbCommand(strSQL, conn))
         {
             conn.Open();
             using (System.Data.OleDb.OleDbDataReader dr = command.ExecuteReader())
             {
                 if(dr.Read())
                 {
                     //If the read row is OK, create a point geometry from the XColumn and YColumn and return it
                     if (dr[0] != DBNull.Value && dr[1] != DBNull.Value)
                         geom = new SharpMap.Geometries.Point((double)dr[0], (double)dr[1]);
                 }
             }
             conn.Close();
         }
     }
     return geom;
 }
 public ReportElement()
 {
   UltimoPunto = null;
   PuntoActual = null;
 }
 internal void AddInformation(ReportElement rpt)
 {
   // la idea es aproximar el esquema de velocidades por trapecios.
   if (rpt._VelocidadMaxima > _VelocidadMaxima)
   {
     _VelocidadMaxima = rpt._VelocidadMaxima;
   }
   if (_Estado == EstadosPosibles.Transito)
   {
     PuntoActual = ProyectarPunto(rpt.Longitud, rpt.Latitud);
     ActualizarDistanciaRecorrida();
     /*System.Diagnostics.Debug.WriteLine(this.PuntoActual);
     System.Diagnostics.Debug.WriteLine(this.UltimoPunto);
     System.Diagnostics.Debug.WriteLine(this.DistanciaRecorrida);*/
   }
 }
 private void ActualizarDistanciaRecorrida()
 {
   _DistanciaRecorrida += CalcularDistanciaSegmento(UltimoPunto, PuntoActual);
   UltimoPunto = PuntoActual;
 }
Ejemplo n.º 48
0
		/// <summary>
		/// Initializes a new map
		/// </summary>
		/// <param name="size">Size of map in pixels</param>
		public Map(System.Drawing.Size size)
		{
			this.Size = size;
			this.Layers = new List<SharpMap.Layers.ILayer>();
			this.BackColor = System.Drawing.Color.Transparent;
			this._MaximumZoom = double.MaxValue;
			this._MinimumZoom = 0;
			_MapTransform = new System.Drawing.Drawing2D.Matrix();
			MapTransformInverted = new System.Drawing.Drawing2D.Matrix();
			_Center = new SharpMap.Geometries.Point(0, 0);
			_Zoom = 1;
			_PixelAspectRatio = 1.0;
		}		
Ejemplo n.º 49
0
        /// <summary>
        /// Return an array with the six affine transformation parameters {a,b,c,d,e,f} and the sum of the squares of the residuals (s0)
        /// </summary>
        /// <remarks>
        /// a,b defines scale vector 1 of coordinate system, d,e scale vector 2. c,f defines offset.
        /// <para>
        /// Converting from input (X,Y) to output coordinate system (X',Y') is done by:
        /// X' = a*X + b*Y + c, Y' = d*X + e*Y + f
        /// </para>
        /// <para>
        /// Transformation based on Mikhail "Introduction to Modern Photogrammetry" p. 399-300.
        /// Extended to arbitrary number of measurements by M. Nielsen
        /// </para>
        /// </remarks>
        /// <returns>Array with the six transformation parameters and sum of squared residuals:  a,b,c,d,e,f,s0</returns>
        public double[] GetAffineTransformation()
        {
            if(inputs.Count<3)
                throw(new System.Exception("At least 3 measurements required to calculate affine transformation"));

            //double precision isn't always enough when transforming large numbers.
            //Lets subtract some mean values and add them later again:
            //Find approximate center values:
            SharpMap.Geometries.Point meanInput = new SharpMap.Geometries.Point(0, 0);
            SharpMap.Geometries.Point meanOutput = new SharpMap.Geometries.Point(0, 0);
            for (int i = 0; i < inputs.Count; i++)
            {
                meanInput.X += inputs[i].X;
                meanInput.Y += inputs[i].Y;
                meanOutput.X += outputs[i].X;
                meanOutput.Y += outputs[i].Y;
            }
            meanInput.X = Math.Round(meanInput.X / inputs.Count);
            meanInput.Y = Math.Round(meanInput.Y / inputs.Count);
            meanOutput.X = Math.Round(meanOutput.X / inputs.Count);
            meanOutput.Y = Math.Round(meanOutput.Y / inputs.Count);

            double[][] N = CreateMatrix(3,3);
            //Create normal equation: transpose(B)*B
            //B: matrix of calibrated values. Example of row in B: [x , y , -1]
            for (int i = 0; i < inputs.Count; i++)
            {
                //Subtract mean values
                inputs[i].X -= meanInput.X;
                inputs[i].Y -= meanInput.Y;
                outputs[i].X -= meanOutput.X;
                outputs[i].Y -= meanOutput.Y;
                //Calculate summed values
                N[0][0] += Math.Pow(inputs[i].X,2);
                N[0][1] +=	inputs[i].X*inputs[i].Y;
                N[0][2] += -inputs[i].X;
                N[1][1] += Math.Pow(inputs[i].Y,2);
                N[1][2] += -inputs[i].Y;
            }
            N[2][2] = inputs.Count;

            double[] t1 = new double[3];
            double[] t2 = new double[3];

            for (int i = 0; i < inputs.Count; i++)
            {
                t1[0] += inputs[i].X * outputs[i].X;
                t1[1] += inputs[i].Y * outputs[i].X;
                t1[2] += -outputs[i].X;

                t2[0] += inputs[i].X * outputs[i].Y;
                t2[1] += inputs[i].Y * outputs[i].Y;
                t2[2] += -outputs[i].Y;
            }
            double[] trans = new double[7];
            // Solve equation N = transpose(B)*t1
            double frac = 1 / (-N[0][0]*N[1][1]*N[2][2]+N[0][0]*Math.Pow(N[1][2],2)+Math.Pow(N[0][1],2)*N[2][2]-2*N[1][2]*N[0][1]*N[0][2]+N[1][1]*Math.Pow(N[0][2],2));
            trans[0] = (-N[0][1]*N[1][2]*t1[2]+N[0][1]*  t1[1]*N[2][2]-N[0][2]*N[1][2]*t1[1]+N[0][2]*N[1][1]*t1[2]-t1[0]*N[1][1]*N[2][2]+t1[0]*Math.Pow(N[1][2],2)) * frac;
            trans[1] = (-N[0][1]*N[0][2]*t1[2]+N[0][1]*  t1[0]*N[2][2]+N[0][0]*N[1][2]*t1[2]-N[0][0]*t1[1]*N[2][2]-N[0][2]*N[1][2]*t1[0]+Math.Pow(N[0][2],2)*t1[1]) * frac;
            trans[2] = -(-N[1][2]*N[0][1]*t1[0]+Math.Pow(N[0][1],2)*t1[2]+N[0][0]*N[1][2]*t1[1]-N[0][0]*N[1][1]*t1[2]-N[0][2]*N[0][1]*t1[1]+N[1][1]*N[0][2]*t1[0]) * frac;
            trans[2] += - meanOutput.X + meanInput.X;
            // Solve equation N = transpose(B)*t2
            trans[3] = (-N[0][1]*N[1][2]*t2[2]+N[0][1]*  t2[1]*N[2][2]-N[0][2]*N[1][2]*t2[1]+N[0][2]*N[1][1]*t2[2]-t2[0]*N[1][1]*N[2][2]+t2[0]*Math.Pow(N[1][2],2)) * frac;
            trans[4] = (-N[0][1]*N[0][2]*t2[2]+N[0][1]*  t2[0]*N[2][2]+N[0][0]*N[1][2]*t2[2]-N[0][0]*t2[1]*N[2][2]-N[0][2]*N[1][2]*t2[0]+Math.Pow(N[0][2],2)*t2[1]) * frac;
            trans[5] = -(-N[1][2]*N[0][1]*t2[0]+Math.Pow(N[0][1],2)*t2[2]+N[0][0]*N[1][2]*t2[1]-N[0][0]*N[1][1]*t2[2]-N[0][2]*N[0][1]*t2[1]+N[1][1]*N[0][2]*t2[0]) * frac;
            trans[5] += - meanOutput.Y + meanInput.Y;

            //Restore values
            for (int i = 0; i < inputs.Count; i++)
            {
                inputs[i].X += meanInput.X;
                inputs[i].Y += meanInput.Y;
                outputs[i].X += meanOutput.X;
                outputs[i].Y += meanOutput.Y;
            }

            //Calculate s0
            double s0=0;
            for (int i = 0; i < inputs.Count; i++)
            {
                double x = inputs[i].X * trans[0] + inputs[i].Y * trans[1] + trans[2];
                double y = inputs[i].X * trans[3] + inputs[i].Y * trans[4] + trans[5];
                s0 += Math.Pow(x-outputs[i].X,2) + Math.Pow(y-outputs[i].Y,2);
            }
            trans[6] = Math.Sqrt(s0) / (inputs.Count);
            return trans;
        }
Ejemplo n.º 50
0
        public static SharpMap.Geometries.LinearRing CreateEllipse(SharpMap.Geometries.Point center,
                                                                    System.Drawing.SizeF size,
                                                                    int segmentsPerQuadrant)
        {
            const double piHalf = System.Math.PI * 0.5d;

            var step = piHalf / segmentsPerQuadrant;

            var pts = new SharpMap.Geometries.Point[4 * segmentsPerQuadrant + 1];
            var angle = 0d;
            for (var i = 0; i < 4 * segmentsPerQuadrant; i++)
            {
                pts[i] = new SharpMap.Geometries.Point(center.X + System.Math.Cos(angle) * size.Width,
                                                       center.Y + System.Math.Sin(angle) * size.Height);
                angle += step;
            }
            pts[pts.Length - 1] = pts[0];
            return new SharpMap.Geometries.LinearRing(pts);
        }
Ejemplo n.º 51
0
 internal void SetElementToLaunch(string layerName, string IDVehicle)
 {
   if (layerName != "" && IDVehicle != "")
   {
     TransponderToSetInformation = ((Layers_[layerName] as SharpMap.Layers.VectorLayer).DataSource as SharpMap.Data.Providers.MemoryDataProviderBase).GetTransponderByVehicleID(IDVehicle);
     SharpMap.Geometries.Geometry geometry = ((Layers_[layerName] as SharpMap.Layers.VectorLayer).DataSource as SharpMap.Data.Providers.MemoryDataProviderBase).GetGeometryByVehicleID(IDVehicle);
     CoordinateToLaunch = geometry == null ? null : geometry.GetBoundingBox().GetCentroid();
     return;
   }
   CoordinateToLaunch = null;
   TransponderToSetInformation = "";
 }
Ejemplo n.º 52
0
        private void GetBounds(SharpMap.Geometries.Point p1, SharpMap.Geometries.Point p2, out SharpMap.Geometries.Point lowerLeft, out SharpMap.Geometries.Point upperRight)
        {
            lowerLeft = new SharpMap.Geometries.Point(Math.Min(p1.X, p2.X), Math.Min(p1.Y, p2.Y));
            upperRight = new SharpMap.Geometries.Point(Math.Max(p1.X, p2.X), Math.Max(p1.Y, p2.Y));

            System.Diagnostics.Debug.WriteLine("p1: " + p1);
            System.Diagnostics.Debug.WriteLine("p2: " + p2);
            System.Diagnostics.Debug.WriteLine("lowerLeft: " + lowerLeft);
            System.Diagnostics.Debug.WriteLine("upperRight: " + upperRight);
        }
Ejemplo n.º 53
0
        /// <summary>
        /// Returns the geometry corresponding to the Object ID
        /// </summary>
        /// <param name="oid">Object ID</param>
        /// <returns>geometry</returns>
        public SharpMap.Geometries.Geometry GetGeometryByID(uint oid)
        {
            SharpMap.Geometries.Geometry geom = null;
            using (PgConnection conn = new PgConnection(_ConnectionString))
            {
                String strSql = String.Format("SELECT AsBinary({0}) As Geom FROM {1} WHERE {2} = '{3}'",
                                              this.GeometryColumn,
                                              this.Table,
                                              this.ObjectIdColumn,
                                              oid);

                conn.Open();
                using (PgCommand command = new PgCommand(strSql, conn))
                {
                    using (PgDataReader dr = command.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            object obj = dr[0];
                            if (typeof(PgPoint) == obj.GetType())
                                geom = new SharpMap.Geometries.Point(((PgPoint)obj).X, ((PgPoint)obj).Y);
                            else if (obj != DBNull.Value)
                                geom = SharpMap.Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])dr[0]);
                        }
                    }
                }
                conn.Close();
            }
            return geom;
        }
Ejemplo n.º 54
0
 private static void SharpMapPointToSqlGeometry(SqlGeometryBuilder geomBuilder, SMPoint point)
 {
     geomBuilder.BeginGeometry(OpenGisGeometryType.Point);
     geomBuilder.BeginFigure(point.X, point.Y);
     geomBuilder.EndFigure();
     geomBuilder.EndGeometry();
 }
Ejemplo n.º 55
0
        /// <summary>
        /// Reads and parses the geometry with ID 'oid' from the ShapeFile
        /// </summary>
        /// <remarks><see cref="FilterDelegate">Filtering</see> is not applied to this method</remarks>
        /// <param name="oid">Object ID</param>
        /// <returns>geometry</returns>
        private SharpMap.Geometries.Geometry ReadGeometry(uint oid)
        {
            brShapeFile.BaseStream.Seek(GetShapeIndex(oid) + 8, 0); //Skip record number and content length
            ShapeType type = (ShapeType)brShapeFile.ReadInt32(); //Shape type
            if (type == ShapeType.Null)
                return null;
            if (_ShapeType == ShapeType.Point || _ShapeType==ShapeType.PointM || _ShapeType==ShapeType.PointZ)
            {
                SharpMap.Geometries.Point tempFeature = new SharpMap.Geometries.Point();
                return new SharpMap.Geometries.Point(brShapeFile.ReadDouble(), brShapeFile.ReadDouble());
            }
            else if (_ShapeType == ShapeType.Multipoint || _ShapeType == ShapeType.MultiPointM || _ShapeType == ShapeType.MultiPointZ)
            {
                brShapeFile.BaseStream.Seek(32 + brShapeFile.BaseStream.Position, 0); //skip min/max box
                SharpMap.Geometries.MultiPoint feature = new SharpMap.Geometries.MultiPoint();
                int nPoints = brShapeFile.ReadInt32(); // get the number of points
                if (nPoints == 0)
                    return null;
                for (int i = 0; i < nPoints; i++)
                    feature.Points.Add(new SharpMap.Geometries.Point(brShapeFile.ReadDouble(), brShapeFile.ReadDouble()));

                return feature;
            }
            else if (	_ShapeType == ShapeType.PolyLine || _ShapeType == ShapeType.Polygon ||
                        _ShapeType == ShapeType.PolyLineM || _ShapeType == ShapeType.PolygonM ||
                        _ShapeType == ShapeType.PolyLineZ || _ShapeType == ShapeType.PolygonZ)
            {
                brShapeFile.BaseStream.Seek(32 + brShapeFile.BaseStream.Position, 0); //skip min/max box

                int nParts = brShapeFile.ReadInt32(); // get number of parts (segments)
                if (nParts == 0)
                    return null;
                int nPoints = brShapeFile.ReadInt32(); // get number of points

                int[] segments = new int[nParts + 1];
                //Read in the segment indexes
                for (int b = 0; b < nParts; b++)
                    segments[b] = brShapeFile.ReadInt32();
                //add end point
                segments[nParts] = nPoints;

                if ((int)_ShapeType%10 == 3)
                {
                    SharpMap.Geometries.MultiLineString mline = new SharpMap.Geometries.MultiLineString();
                    for (int LineID = 0; LineID < nParts; LineID++)
                    {
                        SharpMap.Geometries.LineString line = new SharpMap.Geometries.LineString();
                        for (int i = segments[LineID]; i < segments[LineID + 1]; i++)
                            line.Vertices.Add(new SharpMap.Geometries.Point(brShapeFile.ReadDouble(), brShapeFile.ReadDouble()));
                        mline.LineStrings.Add(line);
                    }
                    if (mline.LineStrings.Count == 1)
                        return mline[0];
                    return mline;
                }
                else //(_ShapeType == ShapeType.Polygon etc...)
                {

                    //First read all the rings
                    List<SharpMap.Geometries.LinearRing> rings = new List<SharpMap.Geometries.LinearRing>();
                    for (int RingID = 0; RingID < nParts; RingID++)
                    {
                        SharpMap.Geometries.LinearRing ring = new SharpMap.Geometries.LinearRing();
                        for (int i = segments[RingID]; i < segments[RingID + 1]; i++)
                            ring.Vertices.Add(new SharpMap.Geometries.Point(brShapeFile.ReadDouble(), brShapeFile.ReadDouble()));
                        rings.Add(ring);
                    }
                    bool[] IsCounterClockWise = new bool[rings.Count];
                    int PolygonCount = 0;
                    for (int i = 0; i < rings.Count;i++)
                    {
                        IsCounterClockWise[i] = rings[i].IsCCW();
                        if (!IsCounterClockWise[i])
                            PolygonCount++;
                    }
                    if (PolygonCount == 1) //We only have one polygon
                    {
                        SharpMap.Geometries.Polygon poly = new SharpMap.Geometries.Polygon();
                        poly.ExteriorRing = rings[0];
                        if (rings.Count > 1)
                            for (int i = 1; i < rings.Count; i++)
                                poly.InteriorRings.Add(rings[i]);
                        return poly;
                    }
                    else
                    {
                        SharpMap.Geometries.MultiPolygon mpoly = new SharpMap.Geometries.MultiPolygon();
                        SharpMap.Geometries.Polygon poly = new SharpMap.Geometries.Polygon();
                        poly.ExteriorRing = rings[0];
                        for (int i = 1; i < rings.Count;i++)
                        {
                            if (!IsCounterClockWise[i])
                            {
                                mpoly.Polygons.Add(poly);
                                poly = new SharpMap.Geometries.Polygon(rings[i]);
                            }
                            else
                                poly.InteriorRings.Add(rings[i]);
                        }
                        mpoly.Polygons.Add(poly);
                        return mpoly;
                    }
                }
            }
            else
                throw (new ApplicationException("Shapefile type " + _ShapeType.ToString() + " not supported"));
        }
Ejemplo n.º 56
0
        public static SharpMap.Geometries.LinearRing CreateRectangle(SharpMap.Geometries.Point center, System.Drawing.SizeF size)
        {
            var wh = new System.Drawing.SizeF(size.Width * 0.5f, size.Height * 0.5f);
            var lt = new SharpMap.Geometries.Point(center.X - wh.Width, center.Y + wh.Height);
            var rb = new SharpMap.Geometries.Point(center.X + wh.Width, center.Y - wh.Height);

            return CreateRectangle(lt, rb);
        }
Ejemplo n.º 57
0
        private static void GetBounds(GeoPoint p1, GeoPoint p2,
            out GeoPoint lowerLeft, out GeoPoint upperRight)
        {
            lowerLeft = new GeoPoint(Math.Min(p1.X, p2.X), Math.Min(p1.Y, p2.Y));
            upperRight = new GeoPoint(Math.Max(p1.X, p2.X), Math.Max(p1.Y, p2.Y));

            Debug.WriteLine("p1: " + p1);
            Debug.WriteLine("p2: " + p2);
            Debug.WriteLine("lowerLeft: " + lowerLeft);
            Debug.WriteLine("upperRight: " + upperRight);
        }
Ejemplo n.º 58
0
        /// <summary>
        /// Calculates the four helmert transformation parameters {a,b,c,d} and the sum of the squares of the residuals (s0)
        /// </summary>
        /// <remarks>
        /// <para>
        /// a,b defines scale vector 1 of coordinate system, d,e scale vector 2.
        /// c,f defines offset.
        /// </para>
        /// <para>
        /// Converting from input (X,Y) to output coordinate system (X',Y') is done by:
        /// X' = a*X + b*Y + c, Y' = -b*X + a*Y + d
        /// </para>
        /// <para>This is a transformation initially based on the affine transformation but slightly simpler.</para>
        /// </remarks>
        /// <returns>Array with the four transformation parameters, and sum of squared residuals: a,b,c,d,s0</returns>
        public double[] GetHelmertTransformation()
        {
            if (inputs.Count < 2)
                throw(new System.Exception("At least 2 measurements required to calculate helmert transformation"));

            //double precision isn't always enough. Lets subtract some mean values and add them later again:
            //Find approximate center values:
            SharpMap.Geometries.Point meanInput = new SharpMap.Geometries.Point(0, 0);
            SharpMap.Geometries.Point meanOutput = new SharpMap.Geometries.Point(0, 0);
            for (int i = 0; i < inputs.Count; i++)
            {
                meanInput.X += inputs[i].X;
                meanInput.Y += inputs[i].Y;
                meanOutput.X += outputs[i].X;
                meanOutput.Y += outputs[i].Y;
            }
            meanInput.X = Math.Round(meanInput.X / inputs.Count);
            meanInput.Y = Math.Round(meanInput.Y / inputs.Count);
            meanOutput.X = Math.Round(meanOutput.X / inputs.Count);
            meanOutput.Y = Math.Round(meanOutput.Y / inputs.Count);

            double b00=0;
            double b02=0;
            double b03=0;
            double[] t = new double[4];
            for (int i = 0; i < inputs.Count; i++)
            {
                //Subtract mean values
                inputs[i].X -= meanInput.X;
                inputs[i].Y -= meanInput.Y;
                outputs[i].X -= meanOutput.X;
                outputs[i].Y -= meanOutput.Y;
                //Calculate summed values
                b00 += Math.Pow(inputs[i].X,2) + Math.Pow(inputs[i].Y,2);
                b02 -=	inputs[i].X;
                b03 -=	inputs[i].Y;
                t[0] += -(inputs[i].X*outputs[i].X) - (inputs[i].Y*outputs[i].Y);
                t[1] += -(inputs[i].Y*outputs[i].X) + (inputs[i].X*outputs[i].Y);
                t[2] += outputs[i].X;
                t[3] += outputs[i].Y;
            }
            double frac = 1 / (-inputs.Count * b00 + Math.Pow(b02, 2) + Math.Pow(b03, 2));
            double[] result = new double[5];
            result[0] = (-inputs.Count * t[0] + b02 * t[2] + b03 * t[3]) * frac;
            result[1] = (-inputs.Count * t[1] + b03 * t[2] - b02 * t[3]) * frac;
            result[2] = (b02*t[0]+b03*t[1]-t[2]*b00) * frac + meanOutput.X;
            result[3] = (b03*t[0]-b02*t[1]-t[3]*b00) * frac + meanOutput.Y;

            //Restore values
            for (int i = 0; i < inputs.Count; i++)
            {
                inputs[i].X += meanInput.X;
                inputs[i].Y += meanInput.Y;
                outputs[i].X += meanOutput.X;
                outputs[i].Y += meanOutput.Y;
            }

            //Calculate s0
            double s0=0;
            for (int i = 0; i < inputs.Count; i++)
            {
                double x = inputs[i].X * result[0] + inputs[i].Y * result[1] + result[2];
                double y = -inputs[i].X * result[1] + inputs[i].Y * result[0] + result[3];
                s0 += Math.Pow(x-outputs[i].X,2) + Math.Pow(y-outputs[i].Y,2);
            }
            result[4] = Math.Sqrt(s0) / (inputs.Count);
            return result;
        }