示例#1
0
        public void TestSectorPointCoverage()
        {
            Random r = new Random();

            foreach (var manager in new ISectorManager[] { new MercatorSectorManager(), new CubeSectorManager() })
            {
                var sectors = new List <ISector>();
                foreach (var root in manager.GetTopmostOSMSectors())
                {
                    sectors.AddRange(root.GetChildrenAtLevel(3));
                }
                for (int i = 0; i < 1000; i++)
                {
                    LongLat longLat;
                    if (manager is MercatorSectorManager)
                    {
                        // mercator can't show poles
                        longLat = new LongLat(r.NextDouble() * 2 * Math.PI - Math.PI, (r.NextDouble() - 0.5) * 85.051129 * 2 * Math.PI / 180);
                    }
                    else
                    {
                        longLat = new LongLat(r.NextDouble() * 2 * Math.PI - Math.PI, r.NextDouble() * Math.PI - Math.PI / 2);
                    }
                    var sectorsThatCover = sectors.Where(x => x.ContainsLongLat(longLat)).ToList();
                    Assert.AreEqual(sectorsThatCover.Count, 1);
                }
            }
        }
示例#2
0
        internal static VertexIndiceBuffer MakeSphereSegExplicit(GraphicsDevice graphicsDevice, ISector root, double diameter, double minX, double minY, double maxX, double maxY, EditorCamera camera)
        {
            Vector3d cameraVector = new LongLat(camera.cameraRotX, camera.cameraRotY).ToSphereVector(); // TODO: this is hacky

            VertexIndiceBuffer buffer = new VertexIndiceBuffer();
            List <VertexPositionNormalTexture> vertices = new List <VertexPositionNormalTexture>();

            double radius             = diameter / 2;
            int    verticalSegments   = Math.Max((int)((maxY - minY) * 50), 1);
            int    horizontalSegments = Math.Max((int)((maxX - minX) * 50), 1);

            for (int i = 0; i <= verticalSegments; i++)
            {
                double y = (minY + (maxY - minY) * i / (double)verticalSegments);
                for (int j = 0; j <= horizontalSegments; j++)
                {
                    double x = (minX + (maxX - minX) * j / (double)horizontalSegments);

                    double tx = j / (double)horizontalSegments;
                    double ty = i / (double)verticalSegments;
                    // stole this equation
                    Vector3d normal     = root.ProjectToSphereCoordinates(new Vector2d(x, y));
                    Vector3d position   = normal * (float)radius; // switched dy and dz here to align the poles from how we had them
                    Vector2d texturepos = new Vector2d((float)tx, (float)ty);
                    vertices.Add(new VertexPositionNormalTexture((position - cameraVector).ToVector3(), normal.ToVector3(), texturepos));
                }
            }
            List <int> indices = MakeIndices(horizontalSegments, verticalSegments);

            buffer.vertices = new VertexBuffer(graphicsDevice, VertexPositionNormalTexture.VertexDeclaration, vertices.Count, BufferUsage.WriteOnly);
            buffer.vertices.SetData(vertices.ToArray());
            buffer.indices = new IndexBuffer(graphicsDevice, IndexElementSize.ThirtyTwoBits, indices.Count, BufferUsage.WriteOnly);
            buffer.indices.SetData(indices.ToArray());
            return(buffer);
        }
示例#3
0
        private void SetExifData()
        {
            // GPS version
            var image = Image;
            var exif  = new ExifWorks.ExifWorks(ref image);

            // center coordinate
            var center = new LongLat();

            foreach (var corner in Document.GetMapCornersLongLat())
            {
                center += corner / 4;
            }

            var ver          = new byte[] { 2, 2, 0, 0 };
            var longitudeRef = new byte[] { Convert.ToByte(center.Longitude < 0 ? 'W' : 'E'), 0 };
            var longitude    = ExifUtil.GetExifGpsCoordinate(center.Longitude);
            var latitudeRef  = new byte[] { Convert.ToByte(center.Latitude < 0 ? 'S' : 'N'), 0 };
            var latitude     = ExifUtil.GetExifGpsCoordinate(center.Latitude);

            exif.SetProperty((int)ExifWorks.ExifWorks.TagNames.GpsVer, ver, ExifWorks.ExifWorks.ExifDataTypes.UnsignedLong);
            exif.SetProperty((int)ExifWorks.ExifWorks.TagNames.GpsLongitudeRef, longitudeRef, ExifWorks.ExifWorks.ExifDataTypes.AsciiString);
            exif.SetProperty((int)ExifWorks.ExifWorks.TagNames.GpsLongitude, longitude, ExifWorks.ExifWorks.ExifDataTypes.UnsignedRational);
            exif.SetProperty((int)ExifWorks.ExifWorks.TagNames.GpsLatitudeRef, latitudeRef, ExifWorks.ExifWorks.ExifDataTypes.AsciiString);
            exif.SetProperty((int)ExifWorks.ExifWorks.TagNames.GpsLatitude, latitude, ExifWorks.ExifWorks.ExifDataTypes.UnsignedRational);
            if (Properties.EncodingInfo.Encoder.MimeType == "image/jpeg")
            {
                exif.SetProperty((int)ExifWorks.ExifWorks.TagNames.JPEGQuality, new byte[] { (byte)(100 * ((JpegEncodingInfo)Properties.EncodingInfo).Quality) }, ExifWorks.ExifWorks.ExifDataTypes.UnsignedByte);
            }

            exif.SetPropertyString((int)ExifWorks.ExifWorks.TagNames.SoftwareUsed, Strings.QuickRoute + " " + Document.GetVersionString());
        }
示例#4
0
        public void TestParallelPerformance()
        {
            LongLat        longLat       = new LongLat(-87.3294527 * Math.PI / 180, 30.4668536 * Math.PI / 180);
            CubeSector     root          = new CubeSector(CubeSector.CubeSectorFace.LEFT, 0, 0, 0);
            Vector2d       relativeCoord = root.ProjectToLocalCoordinates(longLat.ToSphereVector());
            List <ISector> sectors       = root.GetSectorAt(relativeCoord.X, relativeCoord.Y, 6).GetChildrenAtLevel(8);
            Stopwatch      sw            = new Stopwatch();

            sw.Start();
            foreach (var sector in sectors)
            {
                ProceduralTileBuffer buffer = new ProceduralTileBuffer(sector);
                buffer.LoadLinesFromFile();
                buffer.GenerateVertices();
                buffer.Dispose();
            }
            double sequentialSecs = sw.Elapsed.TotalSeconds; // 5.585 secs

            sw.Restart();
            Parallel.ForEach(sectors, sector =>
            {
                ProceduralTileBuffer buffer = new ProceduralTileBuffer(sector);
                buffer.LoadLinesFromFile();
                buffer.GenerateVertices();
                buffer.Dispose();
            });
            double parallelSecs    = sw.Elapsed.TotalSeconds;       // 5.056 secs
            double speedMultiplier = sequentialSecs / parallelSecs; // 1.105 (seems to vary between 1.7 at highest and 1.1 at lowest, not the best multiplier but could still be worthwhile)
        }
示例#5
0
        // move some of our files to the Android assets folder
        private static void HelpZenithAndroid()
        {
            LongLat           longLat       = new LongLat(-87.3294527 * Math.PI / 180, 30.4668536 * Math.PI / 180); // Pensacola
            CubeSector        ourRoot       = new CubeSector(CubeSector.CubeSectorFace.LEFT, 0, 0, 0);
            Vector2d          relativeCoord = ourRoot.ProjectToLocalCoordinates(longLat.ToSphereVector());
            HashSet <ISector> sectorsToLoad = new HashSet <ISector>();

            foreach (var r in ZCoords.GetSectorManager().GetTopmostOSMSectors())
            {
                sectorsToLoad.Add(r);
                for (int z = 1; z <= 3; z++)
                {
                    foreach (var child in r.GetChildrenAtLevel(z))
                    {
                        sectorsToLoad.Add(child);
                    }
                }
            }
            for (int z = 4; z <= 8; z++)
            {
                ISector sector = ourRoot.GetSectorAt(relativeCoord.X, relativeCoord.Y, z);
                for (int i = 0; i < 25; i++)
                {
                    sectorsToLoad.Add(new CubeSector(((CubeSector)sector).sectorFace, sector.X + i / 5 - 2, sector.Y + i % 5 - 2, sector.Zoom));
                }
            }
            foreach (var sector in sectorsToLoad)
            {
                MoveSectorImage(sector);
                MoveSectorOSM(sector);
            }
        }
示例#6
0
 /// <summary>
 /// Creating a new document using the specified map, route, laps, initial transformation matrix, projection origin and document settings, and adding one new session with the specified route and laps.
 /// </summary>
 /// <param name="map"></param>
 /// <param name="route"></param>
 /// <param name="laps"></param>
 /// <param name="initialTransformationMatrix"></param>
 /// <param name="projectionOrigin"></param>
 /// <param name="settings"></param>
 public Document(Map map, Route route, LapCollection laps, GeneralMatrix initialTransformationMatrix, LongLat projectionOrigin, DocumentSettings settings)
 {
     Map = map;
       sessions.Add(new Session(route, laps, map.Image.Size, initialTransformationMatrix, projectionOrigin, settings.DefaultSessionSettings));
       this.settings = settings;
       UpdateDocumentToCurrentVersion(this);
 }
示例#7
0
        public void SetLongLat(LongLat ll)
        {
            LongLat.Longatude = ll.Longatude;
            LongLat.Latatude  = ll.Latatude;
            LongLat.pCode     = ll.pCode;

            PostCode = ll.pCode;
        }
示例#8
0
 private ISector GetContainingSector(LongLat x, int level)
 {
     foreach (var root in ZCoords.GetSectorManager().GetTopmostOSMSectors())
     {
         if (root.ContainsLongLat(x))
         {
             Vector2d localAgain = root.ProjectToLocalCoordinates(x.ToSphereVector());
             return(root.GetSectorAt(localAgain.X, localAgain.Y, level));
         }
     }
     throw new NotImplementedException();
 }
示例#9
0
        public void drawMap(Graphics g, int width, int height, Point center)
        {
            try
            {
                int nScale = mapview.Getlevel(tlVectorControl1.ScaleRatio);
                if (nScale == -1)
                {
                    return;
                }
                LongLat longlat = LongLat.Empty;
                //计算中心点经纬度

                longlat = mapview.OffSet(mapview.ZeroLongLat, mapview.Getlevel(1), center.X, center.Y);
                ImageAttributes imageA = new ImageAttributes();
                longlat = mapview.OffSetZero(-(int)(center.X * tlVectorControl1.ScaleRatio), -(int)(center.Y * tlVectorControl1.ScaleRatio));

                int chose = Convert.ToInt32(ConfigurationSettings.AppSettings.Get("chose"));
                if (chose == 1)
                {
                    g.Clear(Color.White);//ColorTranslator.FromHtml("#EBEAE8")

                    Color color = ColorTranslator.FromHtml("#EBEAE8");
                    imageA.SetColorKey(color, color);
                }
                else if (chose == 2)
                {
                    Color color  = ColorTranslator.FromHtml("#F4F4FB");
                    Color color2 = ColorTranslator.FromHtml("#EFF0F1");//EFF0F1
                    //imageAttributes2.SetColorKey(color, color);
                    //imageAttributes2.SetColorKey(color2, color2);
                    imageA.SetColorKey(color2, color);
                }
                //imageA.
                //g.InterpolationMode = InterpolationMode.HighQualityBicubic;


                mapview.Paint(g, width, height, nScale, longlat.Longitude, longlat.Latitude, imageA);
                //绘制比例尺
                Point p1 = new Point(20, height - 30);
                Point p2 = new Point(20, height - 20);
                Point p3 = new Point(80, height - 20);
                Point p4 = new Point(80, height - 30);

                //g.DrawLines(new Pen(Color.Black, 2), new Point[4] { p1, p2, p3, p4 });
                //string str1 = string.Format("{0}公里", MapViewObj.GetMiles(nScale));
                //g.DrawString(str1, new Font("宋体", 10), Brushes.Black, 30, height - 40);
            }
            catch (Exception e1)
            {
            }
        }
示例#10
0
        /// <summary>
        ///   Constructor
        /// </summary>
        public WorkerFrm()
        {
            InitializeComponent();

            try
            {
                this._keyServiceUsers              = new ServiceUserCollection();
                this._keyServiceUsers.ObjectAdded += new Cura.Common.Collection <ServiceUser> .CollectionChangeEvent(this.KeyServiceUsersChanged);

                this._keyServiceUsers.ObjectRemoved += new Cura.Common.Collection <ServiceUser> .CollectionChangeEvent(this.KeyServiceUsersChanged);

                this._availabilities = new AvailabilityCollection();

                this._availabilities.ObjectAdded += new Cura.Common.Collection <Availability> .CollectionChangeEvent(this.AvailabilitiesChanged);

                this._availabilities.ObjectRemoved += new Cura.Common.Collection <Availability> .CollectionChangeEvent(this.AvailabilitiesChanged);

                this._longLat = new LongLat();

                this.tabControl1.SelectedIndex = 0;

                int weeks = Settings.Instance.rotaweekcount;

                for (int i = 0; i < weeks; i++)
                {
                    treeView1.Nodes.Add("Week " + (i + 1).ToString());
                }

                treeView1.MouseDown += (sender, args) => treeView1.SelectedNode = treeView1.GetNodeAt(args.X, args.Y);

                //show core hours first
                splitContainer5.Panel1Collapsed = false;
                splitContainer5.Panel2Collapsed = true;


                ((OLVColumn)callHistoryObjectListView.Columns[0]).GroupKeyGetter = delegate(object rowObject)
                {
                    Call_Slim model = rowObject as Call_Slim;

                    return(model.Day);
                };

                numberLbl.Text = String.Format("{0} Number", Settings.Instance.WorkerNumberAlias).Trim();
                splitContainer8.SplitterDistance = pictureBox12.Width + numberLbl.Width + 5;
            }
            catch (Exception ex)
            {
                Cura.Common.Common.LogError("Failed To Initialise Worker Form", ex);
            }
        }
示例#11
0
        public static double GetDistance(LongLat l1, LongLat l2, string unit)
        {
            if (l1 == null || l2 == null)
            {
                return(-1);
            }

            if (l1.IsEmpty || l2.IsEmpty)
            {
                return(-1);
            }

            if (!l1.HasLongLat || !l2.HasLongLat)
            {
                return(-1);
            }

            #region Haversine Formula

            double lat1 = Convert.ToDouble(l1.Latatude);
            double lon1 = Convert.ToDouble(l1.Longatude);

            double lat2 = Convert.ToDouble(l2.Latatude);
            double lon2 = Convert.ToDouble(l2.Longatude);


            double R    = 6371;                        // Radius of the earth in km
            double dLat = DegreeToRadian(lat2 - lat1); // deg2rad below
            double dLon = DegreeToRadian(lon2 - lon1);
            double a    =
                Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
                Math.Cos(DegreeToRadian(lat1)) * Math.Cos(DegreeToRadian(lat2)) *
                Math.Sin(dLon / 2) * Math.Sin(dLon / 2)
            ;
            double c   = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
            double dKM = R * c; // Distance in km

            #endregion

            //switch between units
            switch (unit.ToLower())
            {
            case "m":
                return(dKM * 0.62137);

            default:
                return(dKM);
            }
        }
    public int IComparer.Compare(object a, object b)
    {
        LongLat o1 = (LongLat)a;
        LongLat o2 = (LongLat)b;

        if (o1.Longitude > o2.Longitude)
        {
            return(-1);                    // flipped for descending
        }
        else if (o1.Latitude < o2.Longitude)
        {
            return(1);                     // flipped for descending
        }
        // secondary sort on latitude when values are equal
        return(o1.Latitude > o2.Latitude ? -1 : 1);                // flipped for descending
    }
示例#13
0
        private static string DownloadBusStops(LongLat input)
        {
            var client = new RestClient();

            client.BaseUrl       = new Uri(@"https://api.tfl.gov.uk");
            client.Authenticator = new SimpleAuthenticator("app_id", "2960d12f", "app_key", "f75abe891c0d1aec03fd1e396b9afe40");

            var request = new RestRequest();

            request.Resource = $"StopPoint?stopTypes=NaptanPublicBusCoachTram&radius=1000&lat={input.latitude}&lon={input.longitude}";


            var response = client.Execute(request);

            return(response.Content);
        }
示例#14
0
        private void DoCubeFaceTest(CubeSectorFace face, LongLat longLat, bool doXNotY, double expectedAnswer)
        {
            var      front  = new CubeSector(face, 0, 0, 0);
            Vector3d normal = front.sectorFace.GetFaceNormal();
            Vector3d down   = front.sectorFace.GetFaceDownDirection();
            Vector3d right  = front.sectorFace.GetFaceRightDirection();

            if (doXNotY)
            {
                ZAssert.AssertIsClose(front.GetRel(normal, right, longLat.ToSphereVector()), expectedAnswer);
            }
            else
            {
                ZAssert.AssertIsClose(front.GetRel(normal, down, longLat.ToSphereVector()), expectedAnswer);
            }
        }
示例#15
0
        private void WorkerFrm_Load(object sender, EventArgs e)
        {
            try
            {
                if (!_longLat.IsEmpty)
                {
                    GoogleMapLocation location;

                    if (!_longLat.HasLongLat)
                    {
                        //if there aint any long lat info, then try and get some
                        location = new GoogleMapLocation(new GoogleMapAddress(_longLat.pCode, "UK"));
                    }
                    else if (_longLat.pCode == null && _longLat.HasLongLat)
                    {
                        //if there aint post code information then use this to get it
                        location = new GoogleMapLocation(_longLat);
                    }
                    else
                    {
                        //if there is both then whoopdie do basil!
                        location = new GoogleMapLocation(new GoogleMapAddress(_longLat.pCode, "UK"), _longLat);
                    }

                    //get the current long lat
                    _longLat = location.LongLat;

                    //set the postcode to match
                    PostCode = _longLat.pCode;

                    //try to add the marker location
                    webBrowser1.AddLocationMarker(location);
                }
            }
            catch (Exception ex)
            {
                //ignore
            }

            if (_id != 0)
            {
                eNumberTxt.ReadOnly  = true;
                eNumberTxt.BackColor = ColorTranslator.FromHtml("#FFEDE5");
            }
        }
示例#16
0
        public void TestSectorLoadPerformance()
        {
            LongLat    longLat       = new LongLat(-87.3294527 * Math.PI / 180, 30.4668536 * Math.PI / 180);
            CubeSector root          = new CubeSector(CubeSector.CubeSectorFace.LEFT, 0, 0, 0);
            Vector2d   relativeCoord = root.ProjectToLocalCoordinates(longLat.ToSphereVector());
            ISector    sector        = root.GetSectorAt(relativeCoord.X, relativeCoord.Y, 8);
            Stopwatch  sw            = new Stopwatch();

            sw.Start();
            ProceduralTileBuffer buffer = new ProceduralTileBuffer(sector);

            buffer.LoadLinesFromFile();
            double loadTimeSecs = sw.Elapsed.TotalSeconds; // 0.842 secs (1.781 tablet)

            sw.Restart();
            buffer.GenerateVertices();
            double vertSecs = sw.Elapsed.TotalSeconds; // 0.404 secs (0.773 tablet)
        }
示例#17
0
        private ISector GetSector(double mouseX, double mouseY, double cameraZoom)
        {
            int     zoom    = GetRoundedZoom(cameraZoom);
            LongLat longLat = new LongLat(mouseX, mouseY);

            foreach (var sector in ZCoords.GetSectorManager().GetTopmostOSMSectors())
            {
                if (sector.ContainsLongLat(longLat))
                {
                    var localCoord = sector.ProjectToLocalCoordinates(longLat.ToSphereVector());
                    var sectorAt   = sector.GetSectorAt(localCoord.X, localCoord.Y, zoom);
                    if (sectorAt != null)
                    {
                        return(sectorAt);
                    }
                }
            }
            return(null);
        }
示例#18
0
 public static ApiReturn MakeApiCalls(string input)
 {
     try
     {
         ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
         var postCodeInfo       = DownloadPostcode(input);
         var longLat            = LongLat.FromJson(postCodeInfo);
         var busStopJson        = DownloadBusStops(longLat);
         var stopPoints         = StopPoint.FromJson(busStopJson);
         var firstTwoStopPoints = stopPoints.OrderBy(x => x.distance).Take(2).ToList();
         return(new ApiReturn(OutputAllBus(firstTwoStopPoints)));
     }
     catch (InvalidPostcodeException)
     {
         return(new ApiReturn());
     }
     catch (Exception e)
     {
         return(new ApiReturn(e));
     }
 }
示例#19
0
        private void 重新下载ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            (mapview as MapViewBase).ShowMapInfo = true;
            int   nScale = 0;
            float nn     = 1;

            nScale = mapview.Getlevel(documentControl1.ScaleRatio);
            //if(isIn)
            //nScale = mapview.Getlevel(documentControl1.ScaleRatio, out nn);
            //else
            //nScale = mapview.Getlevel2(documentControl1.ScaleRatio, out nn);
            if (nScale == -1)
            {
                return;
            }


            LongLat longlat = LongLat.Empty;
            //计算中心点经纬度
            //longlat = mapview.OffSet(mapview.ZeroLongLat, nScale, (int)(-200 / nn), (int)(-500 / nn));

            //downFlag = true;
            //for (double j = -1.8; j < 1.8; j = j + 0.03)
            //{
            //    for (double i = -1.3; i < 1.3; i = i + 0.01)
            //    {

            //        (mapview as MapViewGoogle).DownImages(14400, 9000, nScale, 107.8+j, 24.3+i);
            //        downFlag = true;
            //        (mapview as MapViewGoogle).OnDownCompleted += new DownCompleteEventHandler(DownImag);
            //        while (downFlag)
            //        {
            //        }

            //    }
            //}
            //(mapview as MapViewGoogle).DownImages(320000, 140000, nScale, 107.79, 24.5);
        }
示例#20
0
        /// <summary>
        /// Constructor
        /// </summary>
        public ServiceUserFrm()
        {
            InitializeComponent();

            this._keyWorkers = new WorkerCollection();

            this._keyWorkers.ObjectAdded += new Cura.Common.Collection <Worker> .CollectionChangeEvent(this.KeyWorkersChanged);

            this._keyWorkers.ObjectRemoved += new Cura.Common.Collection <Worker> .CollectionChangeEvent(this.KeyWorkersChanged);

            this._longLat = new LongLat();
            this.tabControl1.SelectedIndex = 0;

            ((OLVColumn)callHistoryObjectListView.Columns[0]).GroupKeyGetter = delegate(object rowObject)
            {
                Call_Slim model = rowObject as Call_Slim;

                return(model.Day);
            };

            numberLbl.Text = String.Format("{0} Number", Settings.Instance.ServiceUserNumberAlias).Trim();
            splitContainer8.SplitterDistance = pictureBox12.Width + numberLbl.Width + 5;
        }
        public static GeneralMatrix CreateInitialTransformationMatrix(Route route, Size mapSize, LongLat projectionOrigin)
        {
            // create initial adjustment: route should fit in the 75% inner rectangle of the map
              RectangleD routeRectangle = route.BoundingProjectedRectangle(projectionOrigin);
              RectangleD mapRectangle = new RectangleD(1.0 / 8.0 * mapSize.Width, 1.0 / 8.0 * mapSize.Height, 3.0 / 4.0 * mapSize.Width, 3.0 / 4.0 * mapSize.Height);

              // check width/height ratio for each of the rectangles, and adjust the map rectangle to have the same ratio as the route rectangle
              double routeRatio = routeRectangle.Width / routeRectangle.Height;
              double mapRatio = mapRectangle.Width / mapRectangle.Height;
              if (mapRatio < routeRatio)
              {
            // too narrow
            mapRectangle = new RectangleD(mapRectangle.Left, mapRectangle.Center.Y - mapRectangle.Width / routeRatio / 2.0, mapRectangle.Width, mapRectangle.Width / routeRatio);
              }
              else
              {
            // too wide
            mapRectangle = new RectangleD(mapRectangle.Center.X - mapRectangle.Height * routeRatio / 2.0, mapRectangle.Top, mapRectangle.Height * routeRatio, mapRectangle.Height);
              }

              GeneralMatrix t = LinearAlgebraUtil.CalculateTransformationMatrix(routeRectangle.LowerLeft, mapRectangle.UpperLeft, routeRectangle.UpperRight, mapRectangle.LowerRight, null, false);

              return t;
        }
示例#22
0
 protected Document(SerializationInfo info, StreamingContext context)
 {
     Map = (Map)(info.GetValue("map", typeof(Map)));
       settings = (DocumentSettings)(info.GetValue("settings", typeof(DocumentSettings)));
       sessions = (SessionCollection)(info.GetValue("sessions", typeof(SessionCollection)));
       projectionOrigin = (LongLat)(info.GetValue("projectionOrigin", typeof(LongLat)));
       // todo: how handle non-existing properties field?
       try
       {
     properties = (DocumentProperties)(info.GetValue("properties", typeof(DocumentProperties)));
       }
       catch (Exception)
       { }
 }
示例#23
0
        private void WorkerFrm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (DialogResult != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }

            if (firstnametxt.Text.Trim().Length == 0)
            {
                firstnameerrorpic.Visible = true;
                e.Cancel = true;
            }

            if (surnametxt.Text.Trim().Length == 0)
            {
                surnameerrorpic.Visible = true;
                e.Cancel = true;
            }

            if (_id == 0 && !ENumberAvailable)
            {
                pnumbererrorpic.Visible = true;

                pnumbererrodlbl.Text    = "( Already Exists )";
                pnumbererrodlbl.Visible = true;

                e.Cancel = true;
            }
            else if (eNumberTxt.Text.Trim().Length == 0)
            {
                pnumbererrorpic.Visible = true;

                pnumbererrodlbl.Text    = "( Invalid PNumber )";
                pnumbererrodlbl.Visible = true;

                e.Cancel = true;
            }



            //all good, update the location stuff

            try
            {
                if (PostCode == "")
                {
                    _longLat.Empty();
                }
                else if (PostCode != _longLat.pCode)
                {
                    //if the postcode has changed
                    _longLat.Empty();

                    _longLat.pCode = PostCode;


                    //get the google long lat locations (this will insert into pcodes.db)
                    GoogleMapLocation location;
                    location = new GoogleMapLocation(new GoogleMapAddress(PostCode, "UK"));

                    _longLat = location.LongLat;
                }
            }
            catch (Exception ex)
            {
                //ignore
            }
        }
示例#24
0
        private void ServiceUserFrm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (DialogResult != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }

            if (firstnametxt.Text.Trim().Length == 0)
            {
                firstnameerrorpic.Visible = true;
                e.Cancel = true;
            }

            if (surnametxt.Text.Trim().Length == 0)
            {
                surnameerrorpic.Visible = true;
                e.Cancel = true;
            }

            if (_id == 0 && !PNumberAvailable)
            {
                pnumbererrorpic.Visible = true;

                pnumbererrodlbl.Text    = "( Already Exists )";
                pnumbererrodlbl.Visible = true;

                e.Cancel = true;
            }
            else if (pNumberTxt.Text.Trim().Length == 0)
            {
                pnumbererrorpic.Visible = true;

                pnumbererrodlbl.Text    = "( Invalid PNumber )";
                pnumbererrodlbl.Visible = true;

                e.Cancel = true;
            }

            //change this to use call history stuff instead
            //if (_id != 0)
            //{
            //    DateTime serviceStart = PeriodStartDate;
            //    DateTime serviceEnd = serviceStart.AddDays(PeriodWeekCount * 7);

            //    if (CallManager.Instance.Calls.Where(c => c.ServiceUser.id == _id && !c.HasFullWorkers &&
            //                                         !(c.TimeTo > serviceStart && c.TimeFrom < serviceEnd)).Count() > 0)
            //    {

            //        MessageBox.Show("There are still unassigned calls outside this service period.", "Unassigned Calls", MessageBoxButtons.OK);
            //        e.Cancel = true;
            //    }
            //}


            //all good, update the location stuff



            try
            {
                if (PostCode == "")
                {
                    _longLat.Empty();
                }
                else if (PostCode != _longLat.pCode)
                {
                    //if the postcode has changed

                    GoogleMapLocation location;
                    location = new GoogleMapLocation(new GoogleMapAddress(PostCode, "UK"));

                    _longLat = location.LongLat;
                }
            }
            catch (Exception ex)
            {
                //ignore
            }
        }
示例#25
0
        private void tlVectorControl1_AfterPaintPage(object sender, ItopVector.Core.PaintMapEventArgs e)
        {
            int nScale = 0;

            switch ((int)(this.tlVectorControl1.DrawArea.ScaleUnit * 1000))
            {
            case 100:
                nScale = 8;
                break;

            case 200:
                nScale = 9;
                break;

            case 400:
                nScale = 10;
                break;

            case 1000:
                nScale = 11;
                break;

            case 2000:
                nScale = 12;
                break;

            case 4000:
                nScale = 13;
                break;

            default:
                return;
            }
            LongLat longlat = LongLat.Empty;
            //计算中心点经纬度

            int offsetY = (nScale - 10) * 25;

            longlat = mapview.OffSet(mapview.ZeroLongLat, nScale, -(int)(e.CenterPoint.X), -(int)(e.CenterPoint.Y));

            //创建地图
            System.Drawing.Image image = mapview.CreateMap(e.Bounds.Width, e.Bounds.Height, nScale, longlat.Longitude, longlat.Latitude);

            ImageAttributes imageAttributes = new ImageAttributes();
            ColorMatrix     matrix1         = new ColorMatrix();

            matrix1.Matrix00 = 1f;
            matrix1.Matrix11 = 1f;
            matrix1.Matrix22 = 1f;
            matrix1.Matrix33 = 0.9f;            //地图透明度
            matrix1.Matrix44 = 1f;
            //设置地图透明度
            imageAttributes.SetColorMatrix(matrix1, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

            //绘制地图
            e.G.DrawImage((Bitmap)image, e.Bounds, 0f, 0f, (float)image.Width, (float)image.Height, GraphicsUnit.Pixel, imageAttributes);

            //绘制中心点
            e.G.DrawEllipse(Pens.Red, e.Bounds.Width / 2 - 2, e.Bounds.Height / 2 - 2, 4, 4);
            e.G.DrawEllipse(Pens.Red, e.Bounds.Width / 2 - 1, e.Bounds.Height / 2 - 1, 2, 2);

            {    //绘制比例尺
                Point p1 = new Point(20, e.Bounds.Height - 30);
                Point p2 = new Point(20, e.Bounds.Height - 20);
                Point p3 = new Point(80, e.Bounds.Height - 20);
                Point p4 = new Point(80, e.Bounds.Height - 30);

                e.G.DrawLines(new Pen(Color.Black, 2), new Point[4] {
                    p1, p2, p3, p4
                });
                string str1 = string.Format("{0}公里", mapview.GetMiles(nScale));
                e.G.DrawString(str1, new Font("宋体", 10), Brushes.Black, 30, e.Bounds.Height - 40);
            }
            //			string s = string.Format("{0}行{1}列", nRows, nCols);
            string s = string.Format("经{0}:纬{1}", longlat.Longitude, longlat.Latitude);

            //			//显示中心点经纬度
            e.G.DrawString(s, new Font("宋体", 10), Brushes.Red, 20, 40);
        }
示例#26
0
 public Waypoint(DateTime time, LongLat longLat, double? altitude, double? heartRate, MapReadingState? mapReadingState, double? cadence, double? power)
     : this()
 {
     this.time = time;
       this.longLat = longLat;
       this.altitude = altitude;
       this.heartRate = heartRate;
       this.mapReadingState = mapReadingState;
       this.cadence = cadence;
       this.power = power;
 }
 private static LongLat ReadLongLat(BinaryReader br)
 {
     var longLat = new LongLat();
       longLat.Longitude = (double)br.ReadInt32() / 3600000;
       longLat.Latitude = (double)br.ReadInt32() / 3600000;
       return longLat;
 }
示例#28
0
        private void documentControl1_AfterPaintPage(object sender, ItopVector.Core.PaintMapEventArgs e)
        {
            (mapview as MapViewBase).ShowMapInfo = true;
            int   nScale = 0;
            float nn     = 1;

            nScale = mapview.Getlevel(documentControl1.ScaleRatio);
            //if(isIn)
            //nScale = mapview.Getlevel(documentControl1.ScaleRatio, out nn);
            //else
            //nScale = mapview.Getlevel2(documentControl1.ScaleRatio, out nn);
            if (nScale == -1)
            {
                return;
            }


            LongLat longlat = LongLat.Empty;

            //计算中心点经纬度

            longlat = mapview.OffSet(mapview.ZeroLongLat, nScale, (int)(e.CenterPoint.X / nn), (int)(e.CenterPoint.Y / nn));

            //创建地图

            System.Drawing.Image image = backbmp;
            //if (image != null && isdown) { } else
            if (nn >= 1)
            {
                //for (double i=-0.1;i<=0.1;i=i+0.01)
                //{
                //    for (double j = -0.1; j <= 0.1; j = j + 0.01)
                //    {
                //        image = mapview.CreateMap(e.Bounds.Width, e.Bounds.Height, nScale, longlat.Longitude + i, longlat.Latitude+j);
                //    }
                //}
                //image = mapview.CreateMap(1000, 1000, nScale, longlat.Longitude, longlat.Latitude);
                image = mapview.CreateMap(e.Bounds.Width, e.Bounds.Height, nScale, longlat.Longitude, longlat.Latitude);
            }
            else
            {
                image = mapview.CreateMap((int)(e.Bounds.Width / nn), (int)(e.Bounds.Height / nn), nScale, longlat.Longitude, longlat.Latitude);
            }
            //backbmp = image;
            ImageAttributes imageAttributes = new ImageAttributes();
            ColorMatrix     matrix1         = new ColorMatrix();

            matrix1.Matrix00 = 1f;
            matrix1.Matrix11 = 1f;
            matrix1.Matrix22 = 1f;
            matrix1.Matrix33 = 0.9f;            //地图透明度
            matrix1.Matrix44 = 1f;
            //设置地图透明度
            imageAttributes.SetColorMatrix(matrix1, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

            //int offx = 0;
            //int offy = 0;
            //if (isdown) {
            //    offx = Control.MousePosition.X - beginPoint.X;
            //    offy = Control.MousePosition.Y - beginPoint.Y;
            //}
            //e.G.TranslateTransform(offx, offy, MatrixOrder.Append);
            //绘制地图

            if (nn > 1)
            {
                int w1 = (int)(e.Bounds.Width * ((nn - 1) / 2));
                int h1 = (int)(e.Bounds.Height * ((nn - 1) / 2));

                Rectangle rt1 = e.Bounds;
                rt1.Inflate(w1, h1);
                e.G.CompositingQuality = CompositingQuality.HighQuality;
                e.G.DrawImage((Bitmap)image, rt1, 0f, 0f, (float)image.Width, (float)image.Height, GraphicsUnit.Pixel, imageAttributes);
            }
            else
            {
                e.G.DrawImage((Bitmap)image, e.Bounds, 0f, 0f, (float)image.Width, (float)image.Height, GraphicsUnit.Pixel, imageAttributes);
            }
            SolidBrush brush = new SolidBrush(Color.FromArgb(220, 75, 75, 75));

            //e.G.FillRectangle( brush,e.G.VisibleClipBounds);
            //绘制中心点
            e.G.DrawEllipse(Pens.Red, e.Bounds.Width / 2 - 2, e.Bounds.Height / 2 - 2, 4, 4);
            e.G.DrawEllipse(Pens.Red, e.Bounds.Width / 2 - 1, e.Bounds.Height / 2 - 1, 2, 2);
            ///107,159
            {    //绘制比例尺
                Point p1 = new Point(20, e.Bounds.Height - 30);
                Point p2 = new Point(20, e.Bounds.Height - 20);
                Point p3 = new Point(80, e.Bounds.Height - 20);
                Point p4 = new Point(80, e.Bounds.Height - 30);

                e.G.DrawLines(new Pen(Color.Black, 2), new Point[4] {
                    p1, p2, p3, p4
                });
                string str1 = string.Format("{0}公里", mapview.GetMiles(nScale));
                e.G.DrawString(str1, new Font("宋体", 10), Brushes.Black, 30, e.Bounds.Height - 40);
            }
//			string s = string.Format("{0}行{1}列", nRows, nCols);
            string s = string.Format("经{0}:纬{1}", longlat.Longitude, longlat.Latitude);

//			//显示中心点经纬度
            e.G.DrawString(s, new Font("宋体", 10), Brushes.Red, 20, 40);

//			IntPtr hDC = e.G.GetHdc();
//
//
//			LOGBRUSH brush;
//			brush.lbColor = 255;
//			brush.lbHatch = 10;
//			brush.lbStyle = 1;//BS_NULL
//			IntPtr hBursh = CreateBrushIndirect(ref brush);
//			IntPtr hPen = CreatePen(2, 1, 255);
//			IntPtr nOldPen = SelectObject(hDC, hPen);
//			IntPtr nOldBrush = SelectObject(hDC, hBursh);
//			SetROP2(hDC,10);
//			Rectangle((int)hDC, 100, 100, 50, 50);
////			SetROP2(hDC,10);
//			Rectangle((int)hDC, 150, 150, 50, 50);
//
//			SelectObject(hDC, nOldPen);
//			SelectObject(hDC, nOldBrush);
//			e.G.ReleaseHdc(hDC);
        }
示例#29
0
        public void Import()
        {
            importResult = new ImportResult();

            if (BeginWork != null)
            {
                BeginWork(this, new EventArgs());
            }

            XmlTextReader       reader    = new XmlTextReader(FileName);
            XPathDocument       doc       = new XPathDocument(reader);
            XPathNavigator      nav       = doc.CreateNavigator();
            XmlNamespaceManager nsManager = new XmlNamespaceManager(nav.NameTable);

            nsManager.AddNamespace("ns", "http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2");
            XPathNodeIterator activities = nav.Select("//ns:Activity", nsManager);

            while (activities.MoveNext())
            {
                XPathNavigator id = activities.Current.SelectSingleNode("ns:Id", nsManager);
                if (id != null && DateTime.Parse(id.Value).ToString("yyyy-MM-dd HH:mm:ss") == IdToImport)
                {
                    // the activity was found

                    // the laps
                    XPathNodeIterator   lapNodes      = activities.Current.Select("ns:Lap", nsManager);
                    List <RouteSegment> routeSegments = new List <RouteSegment>();
                    RouteSegment        routeSegment  = new RouteSegment();
                    while (lapNodes.MoveNext())
                    {
                        // the tracks
                        XPathNodeIterator trackNodes = lapNodes.Current.Select("ns:Track", nsManager);
                        int trackCount = 0;
                        while (trackNodes.MoveNext())
                        {
                            if (trackCount > 0)
                            {
                                if (routeSegment.Waypoints.Count > 1)
                                {
                                    routeSegments.Add(routeSegment);
                                }
                                routeSegment = new RouteSegment();
                            }
                            XPathNodeIterator trackpointNodes = trackNodes.Current.Select("ns:Trackpoint", nsManager);
                            DateTime          lastTime        = DateTime.MinValue;
                            LongLat           lastLongLat     = null;
                            int trackpointCount = 0;
                            while (trackpointNodes.MoveNext())
                            {
                                Waypoint waypoint = new Waypoint();
                                waypoint.Time = DateTime.Parse(trackpointNodes.Current.SelectSingleNode("ns:Time", nsManager).Value).ToUniversalTime();
                                XPathNavigator position = trackpointNodes.Current.SelectSingleNode("ns:Position", nsManager);
                                if (position != null)
                                {
                                    waypoint.LongLat = new LongLat(
                                        position.SelectSingleNode("ns:LongitudeDegrees", nsManager).ValueAsDouble,
                                        position.SelectSingleNode("ns:LatitudeDegrees", nsManager).ValueAsDouble);
                                }
                                if (trackpointNodes.Current.SelectSingleNode("ns:AltitudeMeters", nsManager) != null)
                                {
                                    waypoint.Altitude =
                                        trackpointNodes.Current.SelectSingleNode("ns:AltitudeMeters", nsManager).ValueAsDouble;
                                }
                                if (trackpointNodes.Current.SelectSingleNode("ns:HeartRateBpm/ns:Value", nsManager) != null)
                                {
                                    waypoint.HeartRate =
                                        trackpointNodes.Current.SelectSingleNode("ns:HeartRateBpm/ns:Value", nsManager).ValueAsDouble;
                                }

                                // do not add waypoint if it has the same location or time as the previous one
                                if (waypoint.LongLat != null && !waypoint.LongLat.Equals(lastLongLat) && waypoint.Time != lastTime)
                                {
                                    // special handling for positionless trackpoint in the beginning, use its time together with next position
                                    if (trackpointCount == 1 && lastLongLat == null && routeSegment.Waypoints.Count == 0)
                                    {
                                        waypoint.Time = lastTime;
                                    }
                                    routeSegment.Waypoints.Add(waypoint);
                                }
                                lastLongLat = waypoint.LongLat;
                                lastTime    = waypoint.Time;
                                trackpointCount++;
                            }
                            if (lastLongLat == null && routeSegment.Waypoints.Count > 1)
                            {
                                // special handling for positionless trackpoint in the end, use its time together with previous position
                                routeSegment.Waypoints[routeSegment.Waypoints.Count - 1].Time = lastTime;
                            }
                            trackCount++;
                        }
                    }

                    // add last route segment
                    if (routeSegment.Waypoints.Count > 1)
                    {
                        routeSegments.Add(routeSegment);
                    }

                    // set position of all start and end waypoints of the route segments if they are null
                    foreach (RouteSegment rs in routeSegments)
                    {
                        if (rs.FirstWaypoint.LongLat == null && rs.Waypoints.Count > 1)
                        {
                            rs.Waypoints[1] = rs.Waypoints[1].Clone();
                        }
                        if (rs.LastWaypoint.LongLat == null && rs.Waypoints.Count > 1)
                        {
                            rs.Waypoints[rs.Waypoints.Count - 1] = rs.Waypoints[rs.Waypoints.Count - 2].Clone();
                        }
                    }


                    // the laps
                    lapNodes = activities.Current.Select("ns:Lap", nsManager);
                    // first store all elapsed times
                    List <double> elapsedTimes = new List <double>();
                    LapCollection laps         = new LapCollection();
                    if (lapNodes.MoveNext())
                    {
                        DateTime startTime   = DateTime.Parse(lapNodes.Current.GetAttribute("StartTime", ""));
                        double   elapsedTime = 0;
                        do
                        {
                            elapsedTimes.Add(elapsedTime);
                            elapsedTime += lapNodes.Current.SelectSingleNode("ns:TotalTimeSeconds", nsManager).ValueAsDouble;
                        } while (lapNodes.MoveNext());


                        laps = RouteImporterUtil.CreateLapsFromElapsedTimes(startTime, elapsedTimes, routeSegments);
                    }

                    importResult.Route     = new Route(routeSegments);
                    importResult.Laps      = laps;
                    importResult.Succeeded = importResult.Route.Segments.Count > 0;
                    if (importResult.Route.Segments.Count == 0)
                    {
                        importResult.Error = ImportError.NoWaypoints;
                    }

                    break;
                }
            }
            reader.Close();
            if (EndWork != null)
            {
                EndWork(this, new EventArgs());
            }
        }
 private static void WriteLongLat(LongLat longLat, BinaryWriter bw)
 {
     bw.Write(Convert.ToInt32(longLat.Longitude * 3600000));
       bw.Write(Convert.ToInt32(longLat.Latitude * 3600000));
 }
示例#31
0
        private void SetExifData()
        {
            // GPS version
              var image = Image;
              var exif = new ExifWorks.ExifWorks(ref image);

              // center coordinate
              var center = new LongLat();
              foreach (var corner in Document.GetMapCornersLongLat())
              {
            center += corner / 4;
              }

              var ver = new byte[] { 2, 2, 0, 0 };
              var longitudeRef = new byte[] { Convert.ToByte(center.Longitude < 0 ? 'W' : 'E'), 0 };
              var longitude = ExifUtil.GetExifGpsCoordinate(center.Longitude);
              var latitudeRef = new byte[] { Convert.ToByte(center.Latitude < 0 ? 'S' : 'N'), 0 };
              var latitude = ExifUtil.GetExifGpsCoordinate(center.Latitude);
              exif.SetProperty((int)ExifWorks.ExifWorks.TagNames.GpsVer, ver, ExifWorks.ExifWorks.ExifDataTypes.UnsignedLong);
              exif.SetProperty((int)ExifWorks.ExifWorks.TagNames.GpsLongitudeRef, longitudeRef, ExifWorks.ExifWorks.ExifDataTypes.AsciiString);
              exif.SetProperty((int)ExifWorks.ExifWorks.TagNames.GpsLongitude, longitude, ExifWorks.ExifWorks.ExifDataTypes.UnsignedRational);
              exif.SetProperty((int)ExifWorks.ExifWorks.TagNames.GpsLatitudeRef, latitudeRef, ExifWorks.ExifWorks.ExifDataTypes.AsciiString);
              exif.SetProperty((int)ExifWorks.ExifWorks.TagNames.GpsLatitude, latitude, ExifWorks.ExifWorks.ExifDataTypes.UnsignedRational);
              if (Properties.EncodingInfo.Encoder.MimeType == "image/jpeg")
              {
            exif.SetProperty((int)ExifWorks.ExifWorks.TagNames.JPEGQuality, new byte[] {(byte)(100 * ((JpegEncodingInfo)Properties.EncodingInfo).Quality)}, ExifWorks.ExifWorks.ExifDataTypes.UnsignedByte);
              }

              exif.SetPropertyString((int)ExifWorks.ExifWorks.TagNames.SoftwareUsed, Strings.QuickRoute + " " + Document.GetVersionString());
        }
示例#32
0
 public static byte[] GetExifGpsPosition(LongLat longLat)
 {
     var lng = BitConverter.GetBytes(Convert.ToInt32(longLat.Longitude * 3600000));
       var lat = BitConverter.GetBytes(Convert.ToInt32(longLat.Latitude * 3600000));
       var x = BitConverter.GetBytes((int)int.MinValue + 1);
       var result = new byte[8];
       lng.CopyTo(result, 0);
       lat.CopyTo(result, 4);
       return result;
 }
示例#33
0
        /// <summary>
        /// This will try to read the string, but if the validation fails, then it will return false,
        ///   rather than throwing an exception.
        /// </summary>
        /// <param name="esriString">
        /// The string to test and define this projection if possible.
        /// </param>
        /// <returns>
        /// Boolean, true if at least the GEOGCS tag was found.
        /// </returns>
        public bool TryParseEsriString(string esriString)
        {
            if (esriString == null)
            {
                return(false);
            }

            if (!esriString.Contains("GEOGCS"))
            {
                return(false);
            }

            if (esriString.Contains("PROJCS") == false)
            {
                GeographicInfo.ParseEsriString(esriString);
                IsLatLon  = true;
                Transform = new LongLat();
                Transform.Init(this);
                return(true);
            }

            int iStart = esriString.IndexOf(@""",");

            Name = esriString.Substring(8, iStart - 8);
            int    iEnd = esriString.IndexOf("PARAMETER");
            string gcs;

            if (iEnd != -1)
            {
                gcs = esriString.Substring(iStart + 1, iEnd - (iStart + 2));
            }
            else
            {
                // an odd Esri projection string that doesn't have PARAMETER
                gcs = esriString.Substring(iStart + 1);
            }
            GeographicInfo.ParseEsriString(gcs);

            FalseEasting    = GetParameter(new string[] { "False_Easting", "Easting_At_False_Origin" }, ref FalseEastingAlias, esriString);
            FalseNorthing   = GetParameter(new string[] { "False_Northing", "Northing_At_False_Origin" }, ref FalseNorthingAlias, esriString);
            CentralMeridian = GetParameter("Central_Meridian", esriString);
            // Esri seems to indicate that these should be treated the same, but they aren't here... http://support.esri.com/en/knowledgebase/techarticles/detail/39992
            // CentralMeridian = GetParameter(new string[] { "Longitude_Of_Center", "Central_Meridian", "Longitude_Of_Origin" }, ref LongitudeOfCenterAlias, esriString);
            LongitudeOfCenter = GetParameter("Longitude_Of_Center", esriString);
            StandardParallel1 = GetParameter("Standard_Parallel_1", esriString);
            StandardParallel2 = GetParameter("Standard_Parallel_2", esriString);
            _scaleFactor      = GetParameter("Scale_Factor", esriString);
            alpha             = GetParameter("Azimuth", esriString);
            _longitudeOf1st   = GetParameter("Longitude_Of_1st", esriString);
            _longitudeOf2nd   = GetParameter("Longitude_Of_2nd", esriString);
            LatitudeOfOrigin  = GetParameter(new string[] { "Latitude_Of_Origin", "Latitude_Of_Center", "Central_Parallel" }, ref LatitudeOfOriginAlias, esriString);
            iStart            = esriString.LastIndexOf("UNIT");
            string unit = esriString.Substring(iStart, esriString.Length - iStart);

            Unit.ParseEsriString(unit);

            if (esriString.Contains("PROJECTION"))
            {
                iStart = esriString.IndexOf("PROJECTION") + 12;
                iEnd   = esriString.IndexOf("]", iStart) - 1;
                string projection = esriString.Substring(iStart, iEnd - iStart);

                Transform = TransformManager.DefaultTransformManager.GetProjection(projection);
                Transform.Init(this);
            }

            double?auxType = GetParameter("Auxiliary_Sphere_Type", esriString);

            if (auxType != null)
            {
                // While the Esri implementation sort of tip-toes around the datum transform,
                // we simply ensure that the spheroid becomes properly spherical based on the
                // parameters we have here.  (The sphereoid will be read as WGS84).
                AuxiliarySphereType = (AuxiliarySphereType)auxType;
                if (AuxiliarySphereType == AuxiliarySphereType.SemimajorAxis)
                {
                    // added by Jiri to properly re-initialize the 'web mercator auxiliary sphere' transform
                    Transform = KnownCoordinateSystems.Projected.World.WebMercator.Transform;
                }
                else if (AuxiliarySphereType == AuxiliarySphereType.SemiminorAxis)
                {
                    double r = GeographicInfo.Datum.Spheroid.PolarRadius;
                    GeographicInfo.Datum.Spheroid = new Spheroid(r);
                }
                else if (AuxiliarySphereType == AuxiliarySphereType.Authalic ||
                         AuxiliarySphereType == AuxiliarySphereType.AuthalicWithConvertedLatitudes)
                {
                    double a = GeographicInfo.Datum.Spheroid.EquatorialRadius;
                    double b = GeographicInfo.Datum.Spheroid.PolarRadius;
                    double r =
                        Math.Sqrt(
                            (a * a
                             +
                             a * b * b
                             / (Math.Sqrt(a * a - b * b) * Math.Log((a + Math.Sqrt(a * a - b * b)) / b, Math.E)))
                            / 2);
                    GeographicInfo.Datum.Spheroid = new Spheroid(r);
                }
            }

            if (FalseEasting != null)
            {
                FalseEasting = FalseEasting * Unit.Meters;
            }

            if (FalseNorthing != null)
            {
                FalseNorthing = FalseNorthing * Unit.Meters;
            }

            return(true);
        }
示例#34
0
        public RectangleD BoundingProjectedRectangle(LongLat projectionOrigin)
        {
            double minX = 0;
              double minY = 0;
              double maxX = 0;
              double maxY = 0;

              for (int i = 0; i < segments.Count; i++)
              {
            for (int j = 0; j < segments[i].Waypoints.Count; j++)
            {
              PointD projectedLocation = segments[i].Waypoints[j].LongLat.Project(projectionOrigin);
              if (projectedLocation.X < minX || (i == 0 && j == 0)) minX = projectedLocation.X;
              if (projectedLocation.Y < minY || (i == 0 && j == 0)) minY = projectedLocation.Y;
              if (projectedLocation.X > maxX || (i == 0 && j == 0)) maxX = projectedLocation.X;
              if (projectedLocation.Y > maxY || (i == 0 && j == 0)) maxY = projectedLocation.Y;
            }
              }
              return new RectangleD(new PointD(minX, minY), new SizeD(maxX - minX, maxY - minY));
        }
示例#35
0
        public PointD GetProjectedLocationFromParameterizedLocation(ParameterizedLocation parameterizedLocation,
            LongLat projectionOrigin)
        {
            List<Waypoint> waypoints = segments[parameterizedLocation.SegmentIndex].Waypoints;
              if (parameterizedLocation.IsNode) return waypoints[(int)parameterizedLocation.Value].LongLat.Project(projectionOrigin);
              var i = (int)parameterizedLocation.Floor().Value;
              if (i >= waypoints.Count - 1) i = waypoints.Count - 2;
              if (waypoints.Count < 2) return waypoints[0].LongLat.Project(projectionOrigin);
              double d = parameterizedLocation.Value - i;

              PointD p0 = waypoints[i].LongLat.Project(projectionOrigin);
              PointD p1 = waypoints[i + 1].LongLat.Project(projectionOrigin);

              return new PointD(p0.X + d * (p1.X - p0.X), p0.Y + d * (p1.Y - p0.Y));
        }