public GeoCoord Convert(RectCoord rectCoord)
        {
            if (rectCoord.Y < 1750000)
            {
                BasicTypeString = ConfigurationManager.AppSettings["LCS46_1"];
            }
            else
            {
                BasicTypeString = ConfigurationManager.AppSettings["LCS46_2"];
            }

            ProjectionInfo src = ProjectionInfo.FromProj4String(BasicTypeString);
            ProjectionInfo trg = ProjectionInfo.FromProj4String("+proj=longlat +datum=WGS84 +no_defs");

            double[] xy = { rectCoord.Y, rectCoord.X };
            double[] h  = { 0 };
            Reproject.ReprojectPoints(xy, h, src, trg, 0, 1);
            var geoCoord = new GeoCoord {
                Lon = xy[0], Lat = xy[1], Alt = h[0]
            };

            return(geoCoord);
        }
Esempio n. 2
0
        public static TriangulationList <Vector3> ReprojectTo(this TriangulationList <Vector3> triangulation, int sourceEpsgCode, int destinationEpsgCode)
        {
            if (sourceEpsgCode == destinationEpsgCode)
            {
                return(triangulation);
            }


            // Defines the starting coordiante system
            ProjectionInfo pSource = ProjectionInfo.FromEpsgCode(sourceEpsgCode);
            // Defines the starting coordiante system
            ProjectionInfo pTarget = ProjectionInfo.FromEpsgCode(destinationEpsgCode);


            double[] inputPoints = triangulation.Positions.SelectMany(pt => new double[] { pt.X, pt.Y }).ToArray();
            Reproject.ReprojectPoints(inputPoints, null, pSource, pTarget, 0, triangulation.NumPositions);

            for (int i = 0; i < triangulation.NumPositions; i++)
            {
                triangulation.Positions[i] = new Vector3((float)inputPoints[2 * i], (float)inputPoints[2 * i + 1], triangulation.Positions[i].Z);
            }
            return(triangulation);
        }
        private void OnMouseMove(object sender, GeoMouseArgs e)
        {
            double x = e.GeographicLocation.X;
            double y = e.GeographicLocation.Y;

            if (!targetProjection.Equals(map.Projection))
            {
                double[] xy =
                {
                    x,
                    y
                };
                Reproject.ReprojectPoints(xy, new[]
                {
                    0.0
                }, map.Projection, targetProjection, 0, 1);
                x = xy[0];
                y = xy[1];
            }

            xLabel.Text = $@"X: {x:0.#####}";
            yLabel.Text = $@"Y: {y:0.#####}";
        }
Esempio n. 4
0
        public void ProjectPoint()
        {
            //Sets up a array to contain the x and y coordinates
            double[] first = new double[2];
            first[0] = 0;
            first[1] = 1;

            double[] second = new double[2];
            second[0] = 0;
            second[1] = 1;
            //An array for the z coordinate
            double[] z = new double[1];
            z[0] = 1;
            //Defines the starting coordiante system
            ProjectionInfo pStart = KnownCoordinateSystems.Geographic.World.WGS1984;
            //Defines the ending coordiante system
            ProjectionInfo pEnd = KnownCoordinateSystems.Projected.NorthAmerica.USAContiguousLambertConformalConic;

            //Calls the reproject function that will transform the input location to the output locaiton
            Reproject.ReprojectPoints(first, z, pStart, pEnd, 0, 1);
            Reproject.ReprojectPoints(second, z, pStart, pEnd, 0, 1);

            Assert.AreEqual(first[0], second[0]);
            Assert.AreEqual(first[1], second[1]);

            Assert.AreNotEqual(first[0], 0);
            Assert.AreNotEqual(first[1], 1);
            Assert.AreNotEqual(second[0], 0);
            Assert.AreNotEqual(second[1], 1);

            Assert.AreEqual(first[0], 10723420.030693574);
            Assert.AreEqual(first[1], 1768929.0089786104);

            Assert.AreEqual(second[0], 10723420.030693574);
            Assert.AreEqual(second[1], 1768929.0089786104);
        }
Esempio n. 5
0
        //Calculates UTM coordinates of meteorological stations and stores in array lists...
        private void CalculateUTMOfMetStations()
        {
            var xy = new List <double>();
            var z  = new List <double>();

            ProjectionInfo source = KnownCoordinateSystems.Geographic.World.WGS1984;
            ProjectionInfo dest   = KnownCoordinateSystems.Projected.UtmWgs1984.WGS1984UTMZone44N;

            foreach (GMapMarkerCircle p in frmMainHPCM.metStationList)
            {
                xy.Add(p.Position.Lng);
                xy.Add(p.Position.Lat);
                z.Add(0);

                var xyA = xy.ToArray();
                var zA  = z.ToArray();
                Reproject.ReprojectPoints(xyA, zA, source, dest, 0, z.Count);
                metStationUTMCoordX.Add(xyA[0]);
                metStationUTMCoordY.Add(xyA[1]);

                xy.Clear();
                z.Clear();
            }
        }
Esempio n. 6
0
        /// <summary>
        /// This function gets the site information.
        /// </summary>
        private Site getSitesParameters(PolygonData polygon)
        {
            IFeature centroid = polygon.polygon.Centroid();
            var      newpoint = sitesPoints.AddFeature(centroid);

            Site   site             = new Site();
            var    xy               = new[] { centroid.Coordinates.First().X, centroid.Coordinates.First().Y };
            String projectionString = "GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[" +
                                      "\"WGS_1984\",6378137,298.257223562997]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.0174532925199433]]";
            var _wgs84Projection = ProjectionInfo.FromEsriString(projectionString);

            Reproject.ReprojectPoints(xy, new double[] { 0, 0 }, App.Map.Projection, _wgs84Projection, 0, 1);

            int indexNumber = (polygonData.IndexOf(polygon) + 1);

            site.Code = "CrwrAggregation:" + OutputResultName.Text + indexNumber.ToString();
            newpoint.DataRow.BeginEdit();
            newpoint.DataRow["SiteCode"] = site.Code.ToString();
            newpoint.DataRow.EndEdit();

            site.Name      = OutputResultName.Text + indexNumber.ToString();
            site.Latitude  = xy[1];
            site.Longitude = xy[0];
            //site.Elevation_m = 12;
            site.VerticalDatum = "Unkown";
            //site.LocalX = 12;
            //site.LocalY = 12;
            //site.PosAccuracy_m = 12;
            site.State  = "";
            site.County = "";
            //site.Comments = "testing";
            //site.Country = "Mexico";
            //site.SiteType = "Type";

            return(site);
        }
Esempio n. 7
0
        public Coordinate Transform(Coordinate coordinate)
        {
            var xy = new[] { coordinate.X, coordinate.Y };

            double[] z = null;
            if (!coordinate.Z.Equals(Coordinate.NullOrdinate))
            {
                z = new[] { coordinate.Z }
            }
            ;

            Reproject.ReprojectPoints(xy, z, Source, Target, 0, 1);

            var ret = (Coordinate)coordinate.Clone();

            ret.X = xy[0];
            ret.Y = xy[1];
            if (z != null)
            {
                ret.Z = z[0];
            }

            return(ret);
        }
Esempio n. 8
0
        private double[] LatLonReproject(double x, double y)
        {
            double[] xy = new double[2] {
                x, y
            };

            //Change y coordinate to be less than 90 degrees to prevent a bug.
            if (xy[1] >= 90)
            {
                xy[1] = 89.9;
            }
            if (xy[1] <= -90)
            {
                xy[1] = -89.9;
            }

            //Need to convert points to proper projection. Currently describe WGS84 points which may or may not be accurate.
            bool isWgs84;

            String wgs84String       = "GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137,298.257223562997]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.0174532925199433]]";
            String mapProjEsriString = App.Map.Projection.ToEsriString();

            isWgs84 = (mapProjEsriString.Equals(wgs84String));

            //If the projection is not WGS84, then convert points to properly describe desired location.
            if (!isWgs84)
            {
                double[]       z = new double[1];
                ProjectionInfo wgs84Projection      = ProjectionInfo.FromEsriString(wgs84String);
                ProjectionInfo currentMapProjection = ProjectionInfo.FromEsriString(mapProjEsriString);
                Reproject.ReprojectPoints(xy, z, wgs84Projection, currentMapProjection, 0, 1);
            }

            //Return array with 1 x and 1 y value.
            return(xy);
        }
Esempio n. 9
0
        private void B_Projection_Click(object sender, EventArgs e)
        {
            double fromX = double.Parse(TB_FromX.Text);
            double fromY = double.Parse(TB_FromY.Text);
            double toX, toY;

            _fromProj = new ProjectionInfo(TB_FromProj.Text);
            _toProj   = new ProjectionInfo(TB_ToProj.Text);

            double[][] points = new double[1][];
            points[0] = new double[] { fromX, fromY };
            //double[] Z = new double[1];
            try
            {
                Reproject.ReprojectPoints(points, _fromProj, _toProj, 0, 1);
                toX         = points[0][0];
                toY         = points[0][1];
                TB_ToX.Text = toX.ToString();
                TB_ToY.Text = toY.ToString();
            }
            catch
            {
            }
        }
Esempio n. 10
0
        public void GeometryReprojectTest()
        {
            List <IPoint> lPoints = new List <IPoint>();

            for (int i = 0; i < 10; ++i)
            {
                lPoints.Add(new Point(new Random().Next(50), new Random().Next(50)));
            }

            var multip = GeometryFactory.Default.CreateMultiPoint(lPoints.ToArray());

            IList <Coordinate> listCoord = multip.Coordinates;
            int iSize = listCoord.Count;

            double[] xy     = new double[iSize * 2];
            int      iIndex = 0;

            for (int i = 0; i < iSize; i++)
            {
                xy[iIndex++] = listCoord[i].X;
                xy[iIndex++] = listCoord[i].Y;
            }

            var projected  = ProjectionInfo.FromProj4String(KnownCoordinateSystems.Projected.World.WebMercator.ToProj4String());
            var geographic = ProjectionInfo.FromProj4String(KnownCoordinateSystems.Geographic.World.WGS1984.ToProj4String());

            Reproject.ReprojectPoints(xy, null, geographic, projected, 0, multip.Coordinates.Length);
            var multip2 = Reproject.ReprojectGeometry(multip, geographic, projected);

            listCoord = multip2.Coordinates;
            iSize     = listCoord.Count;
            double[] xy2 = new double[iSize * 2];
            iIndex = 0;
            for (int i = 0; i < iSize; i++)
            {
                xy2[iIndex++] = listCoord[i].X;
                xy2[iIndex++] = listCoord[i].Y;
            }

            Assert.AreEqual(xy, xy2);

            var lCoords = new List <Coordinate>();

            for (int i = 0; i < 10; ++i)
            {
                lCoords.Add(new Coordinate(new Random().Next(50), new Random().Next(50)));
            }

            var polygon = GeometryFactory.Default.CreatePolygon(lCoords.ToArray());

            listCoord = polygon.Coordinates;
            iSize     = listCoord.Count;
            xy        = new double[iSize * 2];
            iIndex    = 0;
            for (int i = 0; i < iSize; i++)
            {
                xy[iIndex++] = listCoord[i].X;
                xy[iIndex++] = listCoord[i].Y;
            }

            Reproject.ReprojectPoints(xy, null, geographic, projected, 0, polygon.Coordinates.Length);
            var polygon2 = Reproject.ReprojectGeometry(polygon, geographic, projected);

            listCoord = polygon2.Coordinates;
            iSize     = listCoord.Count;
            xy2       = new double[iSize * 2];
            iIndex    = 0;
            for (int i = 0; i < iSize; i++)
            {
                xy2[iIndex++] = listCoord[i].X;
                xy2[iIndex++] = listCoord[i].Y;
            }

            Assert.AreEqual(xy, xy2);
        }
Esempio n. 11
0
        static void Main(string[] args)
        {
            //if(false)
            {
                GeoCoderStatusCode status;
                var pp1 = GMapProviders.YahooMap.GetPoint("Lithuania,Vilnius", out status);

                //var pl = GMapProviders.OpenStreetMap.GetPlacemark(pp1.Value, out status);
            }

            if (false)
            {
                var p = PlateCarreeProjectionDarbAe.Instance;

                var l = new PointLatLng(29.4052130085331, 41.522866508209);

                Debug.WriteLine("121 * 256: " + 121 * 256 + "px : Y");
                Debug.WriteLine("144 * 256: " + 144 * 256 + "px : X");

                Debug.WriteLine("l: " + l);

                var px = p.FromLatLngToPixel(l, 0);

                Debug.WriteLine("FromLatLngToPixel: " + px);

                var ll = p.FromPixelToLatLng(px, 0);
                Debug.WriteLine("FromPixelToLatLng: " + ll);


                var tl = p.FromPixelToTileXY(px);

                Debug.WriteLine("FromPixelToTileXY: " + tl);
            }

            /*
             * 0/1 = 2
             * 1/2 = 1,5
             * 2/3 = 2
             * 3/4 = 2
             * 4/5 = 2,5
             * 5/6 = 2
             * 6/7 = 2
             * 7/8 = 2
             * 8/9 = 2,5
             * 9/10 = 2
             * 10/11 = 2,5
             * 11/12 = 2
             */

            if (false)
            {
                GMapProvider.TileImageProxy = WindowsFormsImageProxy.Instance;

                var p = LKS94Projection.Instance;
                //var p = PlateCarreeProjection.Instance;

                var pos = new PointLatLng(54.6961334816182, 25.2985095977783);

                {
                    var       zoom = 4;
                    var       px   = p.FromPixelToTileXY(p.FromLatLngToPixel(pos, zoom));
                    Exception ex   = null;
                    var       img  = GMaps.Instance.GetImageFrom(GMapProviders.LithuaniaMap, px, zoom, out ex);
                    File.WriteAllBytes(zoom + "z-" + px + ".png", img.Data.ToArray());
                }

                for (int i = 0; i < 12; i++)
                {
                    double scale  = p.GetGroundResolution(i, pos.Lat);
                    double scale2 = p.GetGroundResolution(i + 1, pos.Lat);

                    var s = scale / scale2;

                    Debug.WriteLine(i + "/" + (i + 1) + " = " + s);
                }
            }

#if DEBUG
            if (false)
            {
                GMapProvider.TileImageProxy = WindowsFormsImageProxy.Instance;

                //GMaps.Instance.PrimaryCache.DeleteOlderThan(DateTime.Now, GMapProviders.GoogleMap.DbId);

                GMaps.Instance.Mode = AccessMode.CacheOnly;

                using (Core c = new Core())
                {
                    //c.compensationOffset = new GPoint(200, 200);

                    c.minZoom  = 1;
                    c.maxZoom  = 25;
                    c.Zoom     = 16;
                    c.Provider = GMapProviders.OpenStreetMap;
                    c.Position = new PointLatLng(54.6961334816182, 25.2985095977783);
                    c.OnMapSizeChanged(400, 400);

                    c.OnMapOpen();

                    Debug.WriteLine("Position: " + c.Position);
                    Debug.WriteLine("renderOffset: " + c.renderOffset);
                    Debug.WriteLine("compensationOffset: " + c.compensationOffset);

                    var l = c.FromLatLngToLocal(c.Position);
                    Debug.WriteLine("local: " + l);

                    var g = c.FromLocalToLatLng(l.X, l.Y);
                    Debug.WriteLine("geo: " + g);

                    //c.ReloadMap();

                    Console.ReadLine();

                    c.OnMapClose();
                }
            }

            if (false)
            {
                int i = 0;

                //while(true)
                {
                    Console.WriteLine(i + " start");
                    Debug.WriteLine(i + " start");

                    //using(Core c = new Core())
                    Core c = new Core();
                    {
                        var f = c.OnMapOpen();

                        Console.WriteLine("wait");
                        Console.ReadLine();

                        //c.OnMapClose();
                    }
                    c = null;

                    Debug.WriteLine("end");
                    Console.WriteLine("end");

                    Console.ReadLine();

                    GC.Collect();

                    //if(i++ > 10)
                    //{
                    //   GC.Collect();
                    //   i = 0;
                    //}
                }
            }
#endif

            if (false)
            {
                List <Placemark> plc = null;
                var st = GMapProviders.GoogleMap.GetPlacemarks(new PointLatLng(54.6961334816182, 25.2985095977782), out plc);
                if (st == GeoCoderStatusCode.G_GEO_SUCCESS && plc != null)
                {
                    foreach (var pl in plc)
                    {
                        if (!string.IsNullOrEmpty(pl.PostalCodeNumber))
                        {
                            Debug.WriteLine("Accuracy: " + pl.Accuracy + ", " + pl.Address + ", PostalCodeNumber: " + pl.PostalCodeNumber);
                        }
                    }
                }
            }

            if (false)
            {
                var p1 = new PointLatLng(54.6961334816182, 25.2985095977782);
                var p2 = new PointLatLng(54.7061334816182, 25.3085095977783);

                //GMaps.Instance.ImportFromGMDB(@"C:\Users\m.dambrauskas\AppData\Local\GMap.NET\TileDBv5\en\Data - Copy.gmdb");

                //var route = GMapProviders.OpenStreetMap.GetRoute(p1, p2, false, false, 10);
                //var route = GMapProviders.CloudMadeMap.GetRoute(p1, p2, false, false, 10);

                //Debug.WriteLine(GMapProviders.BingHybridMap.Name + ":" + GMapProviders.BingHybridMap.DbId);

                GDirections ss;
                var         xx = GMapProviders.GoogleMap.GetDirections(out ss, p1, p2, false, false, false, false, false);

                GeoCoderStatusCode status;
                var pp1 = GMapProviders.GoogleMap.GetPoint("Lithuania,Vilnius", out status);
                var pp2 = GMapProviders.GoogleMap.GetPoint("Lithuania,Kaunas", out status);
                if (pp1.HasValue && pp2.HasValue)
                {
                    GDirections s;
                    //var x = GMapProviders.GoogleMap.GetDirections(out s, "Lithuania,Vilnius", "Lithuania,Kaunas", false, false, false, true);
                    //if(x == DirectionsStatusCode.OK)
                    var x = GMapProviders.GoogleMap.GetDirections(out s, pp1.Value, pp2.Value, false, false, false, false, true);
                    {
                        Debug.WriteLine(s.Summary + ", " + s.Copyrights);
                        Debug.WriteLine(s.StartAddress + " -> " + s.EndAddress);
                        Debug.WriteLine(s.Distance);
                        Debug.WriteLine(s.Duration);
                        foreach (var step in s.Steps)
                        {
                            Debug.WriteLine(step);
                        }
                    }
                }
            }

            if (false)
            {
                //-34,8859309407532, Lng=-58,359375
                PointLatLng p1 = new PointLatLng(-34.608, -58.348);
                PointLatLng p2 = new PointLatLng(-34.608, -58.348);

                //Sets up a array to contain the x and y coordinates
                double[] xy = new double[4] {
                    p1.Lng, p1.Lat, p2.Lng, p2.Lat
                };

                //An array for the z coordinate
                double[] z = new double[1];
                z[0] = 1;

                ProjectionInfo pStart = KnownCoordinateSystems.Geographic.World.WGS1984;

                //ProjectionInfo pEnd = new ProjectionInfo("+proj=tmerc +lat_0=0 +lon_0=15 +k=0.9996 +x_0=4200000 +y_0=-1300000 +ellps=WGS84 +datum=WGS84 +to_meter=0.03125 +no_defs");
                ProjectionInfo pEnd = new ProjectionInfo("+proj=tmerc +lat_0=-34.629269 +lon_0=-58.4633 +k=0.9999980000000001 +x_0=100000 +y_0=100000 +ellps=intl +units=m +no_defs");

                Reproject.ReprojectPoints(xy, z, pStart, pEnd, 0, 2);

                Debug.WriteLine(" true1: " + (int)xy[0] + "; " + (int)xy[1]);

                //var prj = new MapyCZProjection();
                //{
                //   var p2 = prj.WGSToPP(y, x);

                //   Debug.WriteLine("false1: " + p2[0] + "; " + p2[1]);

                //   var p3 = prj.PPToWGS(p2[0], p2[1]);

                //   Reproject.ReprojectPoints(xy, z, pEnd, pStart, 0, 1);

                //   Debug.WriteLine("");
                //   Debug.WriteLine(" true2: " + xy[0] + "; " + xy[1]);
                //   Debug.WriteLine("false2: " + p3[1] + "; " + p3[0]);
                //}
                // 134400000],PARAMETER["false_northing",-41600000
            }

            // stop caching immediately
            GMaps.Instance.CancelTileCaching();

            //Console.ReadLine();
        }
Esempio n. 12
0
        public void TestSetViewExtents()
        {
            Map mainMap = new Map();

            mainMap.Projection = KnownCoordinateSystems.Projected.World.WebMercator;

            Extent defaultMapExtent = new Extent(-130, 5, -70, 60);

            string baseMapFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles");
            //SetDefaultMapExtents(mainMap);
            MapPolygonLayer layStates;

            MapGroup baseGroup = new MapGroup(mainMap.Layers, mainMap.MapFrame, mainMap.ProgressHandler);

            baseGroup.LegendText     = "Base Map Data";
            baseGroup.ParentMapFrame = mainMap.MapFrame;
            baseGroup.MapFrame       = mainMap.MapFrame;
            baseGroup.IsVisible      = true;

            //load the 'Countries of the world' layer
            try
            {
                string      fileName    = Path.Combine(baseMapFolder, "50m_admin_0_countries.shp");
                IFeatureSet fsCountries = FeatureSet.OpenFile(fileName);
                fsCountries.Reproject(mainMap.Projection);
                MapPolygonLayer layCountries = new MapPolygonLayer(fsCountries);
                layCountries.LegendText = "Countries";
                PolygonScheme schmCountries = new PolygonScheme();
                schmCountries.EditorSettings.StartColor         = Color.Orange;
                schmCountries.EditorSettings.EndColor           = Color.Silver;
                schmCountries.EditorSettings.ClassificationType =
                    ClassificationType.UniqueValues;
                schmCountries.EditorSettings.FieldName   = "NAME";
                schmCountries.EditorSettings.UseGradient = true;
                schmCountries.CreateCategories(layCountries.DataSet.DataTable);
                layCountries.Symbology = schmCountries;
                baseGroup.Layers.Add(layCountries);
                layCountries.MapFrame = mainMap.MapFrame;
            }
            catch { }
            //load U.S. states layer
            try
            {
                string      fileName = Path.Combine(baseMapFolder, "50mil_us_states.shp");
                IFeatureSet fsStates = FeatureSet.OpenFile(fileName);
                fsStates.Reproject(mainMap.Projection);
                layStates = new MapPolygonLayer(fsStates);
                PolygonScheme schmStates = new PolygonScheme();
                layStates.IsVisible  = true;
                layStates.LegendText = "U.S. States";
                schmStates.EditorSettings.StartColor         = Color.LemonChiffon;
                schmStates.EditorSettings.EndColor           = Color.LightPink;
                schmStates.EditorSettings.ClassificationType =
                    ClassificationType.UniqueValues;
                schmStates.EditorSettings.FieldName   = "NAME";
                schmStates.EditorSettings.UseGradient = true;
                schmStates.CreateCategories(layStates.DataSet.DataTable);
                layStates.Symbology = schmStates;
                baseGroup.Layers.Add(layStates);
                layStates.MapFrame = mainMap.MapFrame;
            }
            catch { }
            //load Canada Provinces layer
            try
            {
                string      fileName   = Path.Combine(baseMapFolder, "50mil_canada_provinces.shp");
                IFeatureSet fsProvince = FeatureSet.OpenFile(fileName);
                fsProvince.Reproject(mainMap.Projection);
                MapPolygonLayer layProvince  = new MapPolygonLayer(fsProvince);
                PolygonScheme   schmProvince = new PolygonScheme();
                layProvince.IsVisible  = true;
                layProvince.LegendText = "Canada Provinces";
                schmProvince.EditorSettings.StartColor         = Color.Green;
                schmProvince.EditorSettings.EndColor           = Color.Yellow;
                schmProvince.EditorSettings.ClassificationType =
                    ClassificationType.UniqueValues;
                schmProvince.EditorSettings.FieldName   = "NAME";
                schmProvince.EditorSettings.UseGradient = true;
                schmProvince.CreateCategories(layProvince.DataSet.DataTable);
                layProvince.Symbology = schmProvince;
                baseGroup.Layers.Add(layProvince);
                layProvince.MapFrame = mainMap.MapFrame;
            }
            catch { }



            //theme data group
            //create a new empty 'themes' data group
            try
            {
                MapGroup themeGroup = new MapGroup(mainMap.Layers,
                                                   mainMap.MapFrame, mainMap.ProgressHandler);
                themeGroup.ParentMapFrame = mainMap.MapFrame;
                themeGroup.MapFrame       = mainMap.MapFrame;
                themeGroup.LegendText     = "Themes";
            }
            catch { }

            double[] xy = new double[4];
            xy[0] = defaultMapExtent.MinX;
            xy[1] = defaultMapExtent.MinY;
            xy[2] = defaultMapExtent.MaxX;
            xy[3] = defaultMapExtent.MaxY;
            double[]       z     = new double[] { 0, 0 };
            string         esri  = "GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137,298.257223562997]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.0174532925199433]]";
            ProjectionInfo wgs84 = ProjectionInfo.FromEsriString(esri);

            Reproject.ReprojectPoints(xy, z, wgs84, mainMap.Projection, 0, 2);

            xy[0] = 1000000000000000;
            xy[1] = 2000000000000000;
            xy[2] = 3000000000000000;
            xy[3] = 4000000000000000;
            Extent ext = new Extent(xy);

            mainMap.ViewExtents = ext;
        }
Esempio n. 13
0
            public bool LoadFile(string filename)
            {
                FileName = filename;

                log.InfoFormat("GeoTiff {0}", filename);

                using (Tiff tiff = Tiff.Open(filename, "r"))
                {
                    width  = tiff.GetField(TiffTag.IMAGEWIDTH)[0].ToInt();
                    height = tiff.GetField(TiffTag.IMAGELENGTH)[0].ToInt();
                    bits   = tiff.GetField(TiffTag.BITSPERSAMPLE)[0].ToInt();
                    //https://www.awaresystems.be/imaging/tiff/tifftags/sampleformat.html
                    type = tiff.GetField(TiffTag.SAMPLEFORMAT)[0].ToInt();

                    modelscale = tiff.GetField(TiffTag.GEOTIFF_MODELPIXELSCALETAG);
                    tiepoint   = tiff.GetField(TiffTag.GEOTIFF_MODELTIEPOINTTAG);

                    for (int i = 0; i < tiff.GetTagListCount(); i += 1)
                    {
                        var tagno = tiff.GetTagListEntry(i);
                        var tag   = (TiffTag)tagno;
                        var info  = tiff.GetField((TiffTag)tagno);

                        log.InfoFormat("tiff ID={0} ? {1} len={2}", tag, (GKID)tagno, info.Length);
                    }

                    var GeoKeyDirectoryTag = tiff.GetField((TiffTag)34735);

                    var KeyDirectoryVersion = BitConverter.ToUInt16(GeoKeyDirectoryTag[1].ToByteArray(), 0);
                    var KeyRevision         = BitConverter.ToUInt16(GeoKeyDirectoryTag[1].ToByteArray(), 2);
                    var MinorRevision       = BitConverter.ToUInt16(GeoKeyDirectoryTag[1].ToByteArray(), 4);
                    var NumberOfKeys        = BitConverter.ToUInt16(GeoKeyDirectoryTag[1].ToByteArray(), 6);

                    ProjectedCSTypeGeoKey = 0;

                    for (int i = 8; i < 8 + NumberOfKeys * 8; i += 8)
                    {
                        var KeyID           = BitConverter.ToUInt16(GeoKeyDirectoryTag[1].ToByteArray(), i);
                        var TIFFTagLocation = BitConverter.ToUInt16(GeoKeyDirectoryTag[1].ToByteArray(), i + 2);
                        var Count           = BitConverter.ToUInt16(GeoKeyDirectoryTag[1].ToByteArray(), i + 4);
                        var Value_Offset    = BitConverter.ToUInt16(GeoKeyDirectoryTag[1].ToByteArray(), i + 6);

                        log.InfoFormat("GeoKeyDirectoryTag ID={0} TagLoc={1} Count={2} Value/offset={3}", (GKID)KeyID, TIFFTagLocation,
                                       Count, Value_Offset);

                        // save it
                        if (TIFFTagLocation == 0)
                        {
                            GeoKeys[(GKID)KeyID] = Value_Offset;
                        }
                        else if (TIFFTagLocation == 34737)
                        {
                            GeoKeys[(GKID)KeyID] = Encoding.ASCII.GetString(tiff.GetField((TiffTag)TIFFTagLocation)[1].ToByteArray().Skip(Value_Offset).Take(Count).ToArray());
                        }
                        else if (TIFFTagLocation == 34736)
                        {
                            GeoKeys[(GKID)KeyID] = BitConverter.ToDouble(tiff.GetField((TiffTag)TIFFTagLocation)[1].ToByteArray().Skip(Value_Offset * 8).Take(Count * 8).ToArray(), 0);
                        }
                        else
                        {
                            GeoKeys[(GKID)KeyID] = Value_Offset;
                        }


                        if (KeyID == (int)GKID.ProjectedCSTypeGeoKey)
                        {
                            ProjectedCSTypeGeoKey = Value_Offset;
                        }

                        if (KeyID == (int)GKID.GTRasterTypeGeoKey)
                        {
                            GTRasterTypeGeoKey = Value_Offset;
                        }

                        if (KeyID == (int)GKID.ProjCoordTransGeoKey)
                        {
                            ProjCoordTransGeoKey = Value_Offset;
                        }

                        if (TIFFTagLocation != 0)
                        {
                            if (TIFFTagLocation == 34737) //ascii
                            {
                                var value = tiff.GetField((TiffTag)TIFFTagLocation)[1].ToByteArray().Skip(Value_Offset)
                                            .Take(Count);
                                log.InfoFormat("GeoKeyDirectoryTag ID={0} Value={1}", (GKID)KeyID,
                                               Encoding.ASCII.GetString(value.ToArray()));
                            }
                            if (TIFFTagLocation == 34736) // double
                            {
                                var value = tiff.GetField((TiffTag)TIFFTagLocation)[1].ToByteArray().Skip(Value_Offset * 8).Take(Count * 8);
                                log.InfoFormat("GeoKeyDirectoryTag ID={0} Value={1}", (GKID)KeyID, BitConverter.ToDouble(value.ToArray(), 0));
                            }

                            if (KeyID == (int)GKID.PCSCitationGeoKey)
                            {
                                var value = tiff.GetField((TiffTag)TIFFTagLocation)[1].ToByteArray().Skip(Value_Offset).Take(Count);
                                PCSCitationGeoKey = Encoding.ASCII.GetString(value.ToArray());
                                log.InfoFormat("GeoKeyDirectoryTag ID={0} Value={1}", (GKID)KeyID, Encoding.ASCII.GetString(value.ToArray()));
                            }
                        }
                    }

                    GeoAsciiParamsTag = tiff.GetField((TiffTag)34737);
                    if (GeoAsciiParamsTag != null && GeoAsciiParamsTag.Length == 2)
                    {
                        log.InfoFormat("GeoAsciiParamsTag 34737 {0}", GeoAsciiParamsTag[1]);
                    }

                    i = BitConverter.ToDouble(tiepoint[1].ToByteArray(), 0);
                    j = BitConverter.ToDouble(tiepoint[1].ToByteArray(), 0 + 8);
                    k = BitConverter.ToDouble(tiepoint[1].ToByteArray(), 0 + 16);
                    x = BitConverter.ToDouble(tiepoint[1].ToByteArray(), 0 + 24);
                    y = BitConverter.ToDouble(tiepoint[1].ToByteArray(), 0 + 32);
                    z = BitConverter.ToDouble(tiepoint[1].ToByteArray(), 0 + 40);

                    log.InfoFormat("Tie Point ({0},{1},{2}) --> ({3},{4},{5})", i, j, k, x, y, z);

                    xscale = BitConverter.ToDouble(modelscale[1].ToByteArray(), 0);
                    yscale = BitConverter.ToDouble(modelscale[1].ToByteArray(), 0 + 8);
                    zscale = BitConverter.ToDouble(modelscale[1].ToByteArray(), 0 + 16);

                    log.InfoFormat("Scale ({0},{1},{2})", xscale, yscale, zscale);

                    if (GTRasterTypeGeoKey == 1)
                    {
                        // starts from top left so x + y -
                        x += xscale / 2.0;
                        y -= yscale / 2.0;
                    }

                    if (ProjectedCSTypeGeoKey == 32767 && ProjCoordTransGeoKey == 15)
                    { // user-defined
                        ProjectionInfo pStart   = ProjectionInfo.FromProj4String($"+proj=stere +lat_ts={GeoKeys[GKID.ProjOriginLatGeoKey].ToString()} +lat_0=90 +lon_0={GeoKeys[GKID.ProjStraightVertPoleLongGeoKey].ToString()} +x_0=0 +y_0=0 +ellps={GeoKeys[GKID.GeogCitationGeoKey].ToString().Replace(" ", "").Replace("|", "")} +datum={GeoKeys[GKID.GeogCitationGeoKey].ToString().Replace(" ", "").Replace("|", "")} +units=m +no_defs ");
                        ProjectionInfo pESRIEnd = KnownCoordinateSystems.Geographic.World.WGS1984;

                        srcProjection = pStart;

                        double[] xyarray = { x,                  y,
                                             x + width * xscale, y - height * yscale,
                                             x + width * xscale, y,
                                             x,                  y - height * yscale };
                        Reproject.ReprojectPoints(xyarray, null, pStart, pESRIEnd, 0, xyarray.Length / 2);

                        ymin = Math.Min(Math.Min(Math.Min(xyarray[1], xyarray[3]), xyarray[5]), xyarray[7]);
                        xmin = Math.Min(Math.Min(Math.Min(xyarray[0], xyarray[2]), xyarray[4]), xyarray[6]);
                        ymax = Math.Max(Math.Max(Math.Max(xyarray[1], xyarray[3]), xyarray[5]), xyarray[7]);
                        xmax = Math.Max(Math.Max(Math.Max(xyarray[0], xyarray[2]), xyarray[4]), xyarray[6]);
                    }
                    else if (ProjectedCSTypeGeoKey != 32767 && ProjectedCSTypeGeoKey != 0)
                    {
                        try
                        {
                            srcProjection = ProjectionInfo.FromEpsgCode(ProjectedCSTypeGeoKey);

                            ProjectionInfo pESRIEnd = KnownCoordinateSystems.Geographic.World.WGS1984;

                            double[] xyarray = { x,                  y,
                                                 x + width * xscale, y - height * yscale,
                                                 x + width * xscale, y,
                                                 x,                  y - height * yscale };
                            Reproject.ReprojectPoints(xyarray, null, srcProjection, pESRIEnd, 0, xyarray.Length / 2);

                            ymin = Math.Min(Math.Min(Math.Min(xyarray[1], xyarray[3]), xyarray[5]), xyarray[7]);
                            xmin = Math.Min(Math.Min(Math.Min(xyarray[0], xyarray[2]), xyarray[4]), xyarray[6]);
                            ymax = Math.Max(Math.Max(Math.Max(xyarray[1], xyarray[3]), xyarray[5]), xyarray[7]);
                            xmax = Math.Max(Math.Max(Math.Max(xyarray[0], xyarray[2]), xyarray[4]), xyarray[6]);
                        }
                        catch (Exception ex) { log.Error(ex); srcProjection = null; }
                    }
                    else
                    {
                        try
                        {
                            srcProjection = ProjectionInfo.FromEsriString(GeoKeys[GKID.PCSCitationGeoKey].ToString());

                            ProjectionInfo pESRIEnd = KnownCoordinateSystems.Geographic.World.WGS1984;

                            double[] xyarray = { x,                  y,
                                                 x + width * xscale, y - height * yscale,
                                                 x + width * xscale, y,
                                                 x,                  y - height * yscale };
                            Reproject.ReprojectPoints(xyarray, null, srcProjection, pESRIEnd, 0, xyarray.Length / 2);

                            ymin = Math.Min(Math.Min(Math.Min(xyarray[1], xyarray[3]), xyarray[5]), xyarray[7]);
                            xmin = Math.Min(Math.Min(Math.Min(xyarray[0], xyarray[2]), xyarray[4]), xyarray[6]);
                            ymax = Math.Max(Math.Max(Math.Max(xyarray[1], xyarray[3]), xyarray[5]), xyarray[7]);
                            xmax = Math.Max(Math.Max(Math.Max(xyarray[0], xyarray[2]), xyarray[4]), xyarray[6]);
                        }
                        catch (Exception ex) { log.Error(ex); srcProjection = null; }
                    }

                    if (srcProjection != null)
                    {
                    }
                    else
                    // wgs84 utm
                    if (ProjectedCSTypeGeoKey >= 32601 && ProjectedCSTypeGeoKey <= 32760)
                    {
                        if (ProjectedCSTypeGeoKey > 32700)
                        {
                            UTMZone       = (ProjectedCSTypeGeoKey - 32700) * -1;
                            srcProjection = ProjectionInfo.FromProj4String($"+proj=utm +zone={UTMZone} +ellps=WGS84 +datum=WGS84 +units=m +no_defs ");
                            //tl
                            var pnt = PointLatLngAlt.FromUTM(UTMZone, x, y);
                            //br
                            var pnt2 = PointLatLngAlt.FromUTM(UTMZone, x + width * xscale,
                                                              y - height * yscale);
                            //tr
                            var pnt3 = PointLatLngAlt.FromUTM(UTMZone, x + width * xscale, y);
                            //bl
                            var pnt4 = PointLatLngAlt.FromUTM(UTMZone, x, y - height * yscale);

                            ymin = Math.Min(Math.Min(Math.Min(pnt.Lat, pnt2.Lat), pnt3.Lat), pnt4.Lat);
                            xmin = Math.Min(Math.Min(Math.Min(pnt.Lng, pnt2.Lng), pnt3.Lng), pnt4.Lng);
                            ymax = Math.Max(Math.Max(Math.Max(pnt.Lat, pnt2.Lat), pnt3.Lat), pnt4.Lat);
                            xmax = Math.Max(Math.Max(Math.Max(pnt.Lng, pnt2.Lng), pnt3.Lng), pnt4.Lng);
                        }

                        if (ProjectedCSTypeGeoKey < 32700)
                        {
                            UTMZone       = ProjectedCSTypeGeoKey - 32600;
                            srcProjection = ProjectionInfo.FromProj4String($"+proj=utm +zone={UTMZone} +ellps=WGS84 +datum=WGS84 +units=m +no_defs ");
                            var pnt  = PointLatLngAlt.FromUTM(UTMZone, x, y);
                            var pnt2 = PointLatLngAlt.FromUTM(UTMZone, x + width * xscale,
                                                              y - height * yscale);
                            var pnt3 = PointLatLngAlt.FromUTM(UTMZone, x + width * xscale, y);
                            var pnt4 = PointLatLngAlt.FromUTM(UTMZone, x, y - height * yscale);

                            ymin = Math.Min(Math.Min(Math.Min(pnt.Lat, pnt2.Lat), pnt3.Lat), pnt4.Lat);
                            xmin = Math.Min(Math.Min(Math.Min(pnt.Lng, pnt2.Lng), pnt3.Lng), pnt4.Lng);
                            ymax = Math.Max(Math.Max(Math.Max(pnt.Lat, pnt2.Lat), pnt3.Lat), pnt4.Lat);
                            xmax = Math.Max(Math.Max(Math.Max(pnt.Lng, pnt2.Lng), pnt3.Lng), pnt4.Lng);
                        }
                    }
                    else
                    // etrs89 utm
                    if (ProjectedCSTypeGeoKey >= 3038 && ProjectedCSTypeGeoKey <= 3051)
                    {
                        UTMZone       = ProjectedCSTypeGeoKey - 3012;
                        srcProjection = ProjectionInfo.FromProj4String($"+proj=utm +zone={UTMZone} +ellps=GRS80 +units=m +no_defs ");
                        // 3038 - 26
                        var pnt  = PointLatLngAlt.FromUTM(UTMZone, x, y);
                        var pnt2 = PointLatLngAlt.FromUTM(UTMZone, x + width * xscale,
                                                          y - height * yscale);
                        var pnt3 = PointLatLngAlt.FromUTM(UTMZone, x + width * xscale, y);
                        var pnt4 = PointLatLngAlt.FromUTM(UTMZone, x, y - height * yscale);

                        ymin = Math.Min(Math.Min(Math.Min(pnt.Lat, pnt2.Lat), pnt3.Lat), pnt4.Lat);
                        xmin = Math.Min(Math.Min(Math.Min(pnt.Lng, pnt2.Lng), pnt3.Lng), pnt4.Lng);
                        ymax = Math.Max(Math.Max(Math.Max(pnt.Lat, pnt2.Lat), pnt3.Lat), pnt4.Lat);
                        xmax = Math.Max(Math.Max(Math.Max(pnt.Lng, pnt2.Lng), pnt3.Lng), pnt4.Lng);
                    }
                    else

                    if (ProjectedCSTypeGeoKey >= 25828 && ProjectedCSTypeGeoKey <= 25838)
                    {
                        UTMZone = ProjectedCSTypeGeoKey - 25800;
                        // 3038 - 26
                        var pnt  = PointLatLngAlt.FromUTM(UTMZone, x, y);
                        var pnt2 = PointLatLngAlt.FromUTM(UTMZone, x + width * xscale,
                                                          y - height * yscale);
                        var pnt3 = PointLatLngAlt.FromUTM(UTMZone, x + width * xscale, y);
                        var pnt4 = PointLatLngAlt.FromUTM(UTMZone, x, y - height * yscale);

                        ymin = Math.Min(Math.Min(Math.Min(pnt.Lat, pnt2.Lat), pnt3.Lat), pnt4.Lat);
                        xmin = Math.Min(Math.Min(Math.Min(pnt.Lng, pnt2.Lng), pnt3.Lng), pnt4.Lng);
                        ymax = Math.Max(Math.Max(Math.Max(pnt.Lat, pnt2.Lat), pnt3.Lat), pnt4.Lat);
                        xmax = Math.Max(Math.Max(Math.Max(pnt.Lng, pnt2.Lng), pnt3.Lng), pnt4.Lng);
                    }
                    else
                    /// gda94
                    if (ProjectedCSTypeGeoKey >= 28348 && ProjectedCSTypeGeoKey <= 28358)
                    {
                        UTMZone = (ProjectedCSTypeGeoKey - 28300) * -1;
                        var pnt  = PointLatLngAlt.FromUTM(UTMZone, x, y);
                        var pnt2 = PointLatLngAlt.FromUTM(UTMZone, x + width * xscale,
                                                          y - height * yscale);
                        var pnt3 = PointLatLngAlt.FromUTM(UTMZone, x + width * xscale, y);
                        var pnt4 = PointLatLngAlt.FromUTM(UTMZone, x, y - height * yscale);

                        ymin = Math.Min(Math.Min(Math.Min(pnt.Lat, pnt2.Lat), pnt3.Lat), pnt4.Lat);
                        xmin = Math.Min(Math.Min(Math.Min(pnt.Lng, pnt2.Lng), pnt3.Lng), pnt4.Lng);
                        ymax = Math.Max(Math.Max(Math.Max(pnt.Lat, pnt2.Lat), pnt3.Lat), pnt4.Lat);
                        xmax = Math.Max(Math.Max(Math.Max(pnt.Lng, pnt2.Lng), pnt3.Lng), pnt4.Lng);
                    }
                    else

                    // geo lat/lng
                    if (ProjectedCSTypeGeoKey == 0 || ProjectedCSTypeGeoKey == 4326)
                    {
                        var pnt  = new PointLatLngAlt(y, x);
                        var pnt2 = new PointLatLngAlt(y - height * yscale, x + width * xscale);
                        var pnt3 = new PointLatLngAlt(y, x + width * xscale);
                        var pnt4 = new PointLatLngAlt(y - height * yscale, x);

                        ymin = Math.Min(Math.Min(Math.Min(pnt.Lat, pnt2.Lat), pnt3.Lat), pnt4.Lat);
                        xmin = Math.Min(Math.Min(Math.Min(pnt.Lng, pnt2.Lng), pnt3.Lng), pnt4.Lng);
                        ymax = Math.Max(Math.Max(Math.Max(pnt.Lat, pnt2.Lat), pnt3.Lat), pnt4.Lat);
                        xmax = Math.Max(Math.Max(Math.Max(pnt.Lng, pnt2.Lng), pnt3.Lng), pnt4.Lng);
                    }

                    Area = new RectLatLng(ymax, xmin, xmax - xmin, ymax - ymin);

                    log.InfoFormat("Coverage {0}", Area.ToString());


                    log.InfoFormat("Start Point ({0},{1},{2}) --> ({3},{4},{5})", i, j, k, x, y, z);

                    lock (index)
                        GeoTiff.index.Add(this);

                    /*
                     *
                     * short numberOfDirectories = tiff.NumberOfDirectories();
                     * for (short d = 0; d < numberOfDirectories; ++d)
                     * {
                     * tiff.SetDirectory((short)d);
                     *
                     * for (ushort t = ushort.MinValue; t < ushort.MaxValue; ++t)
                     * {
                     *  TiffTag tag = (TiffTag)t;
                     *  FieldValue[] value = tiff.GetField(tag);
                     *  if (value != null)
                     *  {
                     *      for (int j2 = 0; j2 < value.Length; j2++)
                     *      {
                     *          Console.WriteLine("{0} : {1} : {2}", tag.ToString(), value[j2].Value.GetType().ToString(), value[j2].ToString());
                     *      }
                     *  }
                     * }
                     * }
                     */
                }

                return(true);
            }
Esempio n. 14
0
        /// <summary>
        /// Load base maps for World template project. The base shapefiles
        /// are loaded from the [Program Files]\[Cuahsi HIS]\HydroDesktop\maps\BaseData folder.
        /// </summary>
        public static Boolean LoadBaseMaps(AppManager applicationManager1, Map mainMap)
        {
            //set the projection of main map
            mainMap.Projection = projWorld.WebMercator;

            Extent defaultMapExtent = new Extent(-170, -50, 170, 50);

            string baseMapFolder = Settings.Instance.DefaultBaseMapDirectory;

            //MapGroup baseGroup = new MapGroup(mainMap.Layers, mainMap.MapFrame, mainMap.ProgressHandler);
            //baseGroup.LegendText = "Base Map Data";
            //baseGroup.ParentMapFrame = mainMap.MapFrame;
            //baseGroup.MapFrame = mainMap.MapFrame;
            //baseGroup.IsVisible = true;

            //load the 'Countries of the world' layer
            try
            {
                mainMap.BackColor = Color.LightBlue;

                string fileName = Path.Combine(baseMapFolder, "world_countries.shp");
                if (File.Exists(fileName))
                {
                    IFeatureSet     fsCountries  = FeatureSet.OpenFile(fileName);
                    MapPolygonLayer layCountries = new MapPolygonLayer(fsCountries);
                    layCountries.LegendText = "Countries";
                    layCountries.Symbolizer = new PolygonSymbolizer(Color.FromArgb(255, 239, 213), Color.LightGray);
                    //PolygonScheme schmCountries = new PolygonScheme();
                    //schmCountries.EditorSettings.StartColor = Color.Orange;
                    //schmCountries.EditorSettings.EndColor = Color.Silver;
                    //schmCountries.EditorSettings.ClassificationType =
                    //    ClassificationType.UniqueValues;
                    //schmCountries.EditorSettings.FieldName = "NAME";
                    //schmCountries.EditorSettings.UseGradient = true;
                    //schmCountries.CreateCategories(layCountries.DataSet.DataTable);
                    //layCountries.Symbology = schmCountries;
                    //baseGroup.Layers.Add(layCountries);
                    mainMap.Layers.Add(layCountries);
                    layCountries.MapFrame = mainMap.MapFrame;
                    layCountries.ProgressReportingEnabled = false;
                }
            }
            catch { }


            //load a rivers layer
            try
            {
                var fileName = Path.Combine(baseMapFolder, "world_rivers.shp");
                if (File.Exists(fileName))
                {
                    IFeatureSet fsRivers = FeatureSet.OpenFile(fileName);
                    //fsRivers.Reproject(mainMap.Projection);
                    MapLineLayer layRivers = new MapLineLayer(fsRivers);
                    layRivers.LegendText = "rivers";
                    LineSymbolizer symRivers = new LineSymbolizer(Color.Blue, 1.0);
                    layRivers.Symbolizer = symRivers;
                    mainMap.Layers.Add(layRivers);
                    layRivers.MapFrame = mainMap.MapFrame;
                }
            }
            catch { }

            //load a lakes layer
            try
            {
                var fileName = Path.Combine(baseMapFolder, "world_lakes.shp");
                if (File.Exists(fileName))
                {
                    IFeatureSet fsLakes = FeatureSet.OpenFile(fileName);
                    //fsLakes.Reproject(mainMap.Projection);
                    MapPolygonLayer layLakes = new MapPolygonLayer(fsLakes);
                    layLakes.LegendText = "lakes";
                    PolygonSymbolizer symLakes = new PolygonSymbolizer(Color.Blue,
                                                                       Color.Blue);
                    layLakes.Symbolizer = symLakes;
                    mainMap.Layers.Add(layLakes);
                    layLakes.MapFrame = mainMap.MapFrame;
                    layLakes.ProgressReportingEnabled = false;
                }
            }
            catch { }



            double[] xy = new double[4];
            xy[0] = defaultMapExtent.MinX;
            xy[1] = defaultMapExtent.MinY;
            xy[2] = defaultMapExtent.MaxX;
            xy[3] = defaultMapExtent.MaxY;
            double[] z     = new double[] { 0, 0 };
            var      wgs84 = ProjectionInfo.FromEsriString(Properties.Resources.wgs_84_esri_string);

            Reproject.ReprojectPoints(xy, z, wgs84, mainMap.Projection, 0, 2);

            mainMap.ViewExtents = new Extent(xy);

            return(true);
        }
Esempio n. 15
0
        double AnualEnergyProduction(int numPvPanel, string weatherFile, double tilt, double az)
        {
            double aunalProduction = 0;

            pvVerify();
            if (verify[0] == false)
            {
                return(0);
            }
            updateArea();
            float  system_size           = (float)Convert.ToDouble(txtSystem_size.Text);
            double panelW                = Convert.ToDouble(txtPvWidth.Text);
            double panelH                = Convert.ToDouble(txtPvLength.Text);
            double DCNamplatePerSqrMeter = 25.6 / 4 * Convert.ToDouble(system_size);
            double panelA                = panelW * panelH / DCNamplatePerSqrMeter; //AC factor per panel area
            float  derate                = (float)Convert.ToDouble(txtDerate.Text);
            int    track_mode            = cmbTrack_mode.SelectedIndex;

            #region "Multiple Sta"

            //----------------------------------------------------
            //MULTIPLE WEATHER STATION
            //----------------------------------------------------
            if (optMultiWeatherSta.Checked == true)
            {
                int      nIdwSta = Convert.ToInt16(txtNIdwSta.Text);
                double[] rX      = new double[nIdwSta];
                double[] rY      = new double[nIdwSta];
                double[] rR      = new double[nIdwSta];
                float[,] mAC = new float[nIdwSta, 12];
                float[,] dAC = new float[nIdwSta, 365];
                double SiteX   = Convert.ToDouble(txtUtmE.Text);
                double SiteY   = Convert.ToDouble(txtUtmN.Text);
                double SiteLng = Convert.ToDouble(txtLNG.Text);
                double SiteLat = Convert.ToDouble(txtLAT.Text);
                //----------------------------
                // time  shift
                int siteGMT = Convert.ToInt16(12 / 24 * SiteLng);
                //---------------------------


                for (int idwSta = 0; idwSta < nIdwSta; idwSta++)
                {
                    //---------------------------
                    double lat = wSta[wStaSel[idwSta]].LAT2;
                    double lng = wSta[wStaSel[idwSta]].LONG2;
                    //----------------------------
                    // time  shift
                    int staGMT = Convert.ToInt16(12 / 24 * lng);
                    //---------------------------
                    double[] StaCoord = new double[] { lng, lat };
                    Reproject.ReprojectPoints(StaCoord, new double[] { 0 }, KnownCoordinateSystems.Geographic.World.WGS1984, pvMap.Projection, 0, 1);
                    rR[idwSta] = Math.Sqrt(Math.Pow((SiteX - StaCoord[0]), 2) + Math.Pow((SiteY - StaCoord[1]), 2));
                    rX[idwSta] = Math.Abs(SiteX - StaCoord[0]);
                    rY[idwSta] = Math.Abs(SiteY - StaCoord[1]);
                    //---------------------------
                    SSC.Data data = new SSC.Data();
                    data.SetString("file_name", pvDir + "\\WeatherSta\\tm2\\" + wSta[wStaSel[idwSta]].FileName); //TM2 file
                    data.SetNumber("system_size", system_size);
                    data.SetNumber("derate", derate);
                    data.SetNumber("track_mode", track_mode);
                    data.SetNumber("tilt", (int)tilt);
                    data.SetNumber("azimuth", (int)az);

                    SSC.Module mod = new SSC.Module("pvwattsv1");
                    if (mod.Exec(data))
                    {
                        float   tot      = data.GetNumber("ac_annual");
                        float[] ac       = data.GetArray("ac_monthly");
                        float[] hourlyAc = data.GetArray("ac");
                        for (int m = 0; m < 12; m++)
                        {
                            mAC[idwSta, m] = ac[m];
                        }
                        //------ daily AC
                        int hh = 0;
                        for (int d = 0; d < 365; d++)
                        {
                            int   nHr    = 0;
                            float energy = 0;
                            for (int h = 0; h < 24; h++)
                            {
                                if (hourlyAc[h] > 0)
                                {
                                    nHr++;
                                }
                                energy += hourlyAc[hh];
                                hh++;
                            }
                            if (nHr > 0)
                            {
                                dAC[idwSta, d] = energy / 1000; //Change unit W to KW
                            }
                            else
                            {
                                dAC[idwSta, d] = 0;
                            }
                        }
                    }
                }
                //-------------------------------------------------------
                // IDW
                //-------------------------------------------------------
                double[] MonthlyProduct = new double[12];
                double[] DailyProduct   = new double[365];
                double   px             = Convert.ToDouble(txtPowX.Text);
                double   py             = Convert.ToDouble(txtPowY.Text);
                double   sumR           = 0;
                for (int idwSta = 0; idwSta < nIdwSta; idwSta++)
                {
                    double rPow = 1 / (Math.Pow(rX[idwSta] / 1000, px) * Math.Pow(rY[idwSta] / 1000, py));
                    sumR += rPow;
                }
                for (int m = 0; m < 12; m++)
                {
                    double sumRZ = 0;
                    for (int idwSta = 0; idwSta < nIdwSta; idwSta++)
                    {
                        double rPowZ = mAC[idwSta, m] / (Math.Pow(rX[idwSta] / 1000, px) * Math.Pow(rY[idwSta] / 1000, py));
                        sumRZ += rPowZ;
                    }
                    MonthlyProduct[m] = sumRZ / sumR;
                }
                for (int d = 0; d < 365; d++)
                {
                    double sumRZ = 0;
                    for (int idwSta = 0; idwSta < nIdwSta; idwSta++)
                    {
                        double rPowZ = dAC[idwSta, d] / (Math.Pow(rX[idwSta] / 1000, px) * Math.Pow(rY[idwSta] / 1000, py));
                        sumRZ += rPowZ;
                    }
                    DailyProduct[d] = sumRZ / sumR;
                }
                //-------------------------------------------------------
                // Reprot
                //-------------------------------------------------------
                for (int month = 1; month <= 12; month++)
                {
                    //---------------------------------------------
                    double MonthAc = 0;
                    //MonthAc = MonthAc / dOfMonth(month);
                    MonthAc = MonthlyProduct[month - 1];
                    //acProduction[month - 1] = MonthAc;
                    //---------------------------------------------
                    aunalProduction += Math.Round(MonthAc * panelA * numPvPanel, 0); // System AC
                }
                return(aunalProduction);
            }
            #endregion

            #region "Single Station"

            //----------------------------------------------------
            //SINGLE WEATHER STATION
            //----------------------------------------------------
            if (optSingleWeatherSta.Checked == true)
            {
                SSC.Data data = new SSC.Data();
                data.SetString("file_name", weatherFile); //TM2 file
                data.SetNumber("system_size", system_size);
                data.SetNumber("derate", derate);
                data.SetNumber("track_mode", track_mode);
                data.SetNumber("tilt", (int)tilt);
                data.SetNumber("azimuth", (int)az);

                SSC.Module mod = new SSC.Module("pvwattsv1");
                if (mod.Exec(data))
                {
                    float   tot          = data.GetNumber("ac_annual");
                    float[] ac           = data.GetArray("ac_monthly");
                    float[] hourlyAc     = data.GetArray("ac");
                    float[] DailyProduct = new float[365];
                    //------ daily AC
                    int hh = 0;
                    for (int d = 0; d < 365; d++)
                    {
                        int   nHr    = 0;
                        float energy = 0;
                        for (int h = 0; h < 24; h++)
                        {
                            if (hourlyAc[h] > 0)
                            {
                                nHr++;
                            }
                            energy += hourlyAc[hh];
                            hh++;
                        }
                        if (nHr > 0)
                        {
                            DailyProduct[d] = energy / 1000; //Change unit W to KW
                        }
                        else
                        {
                            DailyProduct[d] = 0;
                        }
                    }

                    for (int month = 1; month <= 12; month++)
                    {
                        aunalProduction += Math.Round(ac[month - 1] * panelA * numPvPanel, 0); // System Ac.
                    }
                    return(aunalProduction);
                }
                #endregion
            }
            return(0);
        }
Esempio n. 16
0
        public static srtm.altresponce getAltitude(double lat, double lng, double zoom = 16)
        {
            lock (index)
                if (index.Count == 0)
                {
                    return(srtm.altresponce.Invalid);
                }

            var answer = new srtm.altresponce();

            foreach (var geotiffdata in index.ToArray())
            {
                if (geotiffdata.Area.Contains(lat, lng))
                {
                    // get answer
                    var xf = map(lat, geotiffdata.Area.Top, geotiffdata.Area.Bottom, 0, geotiffdata.height - 1);
                    var yf = map(lng, geotiffdata.Area.Left, geotiffdata.Area.Right, 0, geotiffdata.width - 1);

                    if (geotiffdata.srcProjection != null)
                    {
                        ProjectionInfo pESRIEnd = KnownCoordinateSystems.Geographic.World.WGS1984;

                        double[] xyarray = { lng, lat };
                        Reproject.ReprojectPoints(xyarray, null, pESRIEnd, geotiffdata.srcProjection, 0, xyarray.Length / 2);

                        xf = map(xyarray[1], geotiffdata.y, geotiffdata.y - geotiffdata.height * geotiffdata.yscale, 0, geotiffdata.height - 1);
                        yf = map(xyarray[0], geotiffdata.x, geotiffdata.x + geotiffdata.width * geotiffdata.xscale, 0, geotiffdata.width - 1);
                    }
                    //wgs84 && etrs89
                    else if (geotiffdata.ProjectedCSTypeGeoKey >= 3038 && geotiffdata.ProjectedCSTypeGeoKey <= 3051 ||
                             geotiffdata.ProjectedCSTypeGeoKey >= 32601 && geotiffdata.ProjectedCSTypeGeoKey <= 32760 ||
                             geotiffdata.ProjectedCSTypeGeoKey >= 25828 && geotiffdata.ProjectedCSTypeGeoKey <= 25838 ||
                             geotiffdata.ProjectedCSTypeGeoKey >= 28348 && geotiffdata.ProjectedCSTypeGeoKey <= 28358)
                    {
                        var pnt = PointLatLngAlt.ToUTM((geotiffdata.UTMZone) * 1, lat, lng);

                        xf = map(pnt[1], geotiffdata.y, geotiffdata.y - geotiffdata.height * geotiffdata.yscale, 0,
                                 geotiffdata.height - 1);
                        yf = map(pnt[0], geotiffdata.x, geotiffdata.x + geotiffdata.width * geotiffdata.xscale, 0,
                                 geotiffdata.width - 1);
                    }

                    int    x_int  = (int)xf;
                    double x_frac = xf - x_int;

                    int    y_int  = (int)yf;
                    double y_frac = yf - y_int;


                    //could be on one of the other images
                    if (x_int < 0 || y_int < 0 || x_int >= geotiffdata.height - 1 || y_int >= geotiffdata.width - 1)
                    {
                        continue;
                    }

                    double alt00 = GetAlt(geotiffdata, x_int, y_int);
                    double alt10 = GetAlt(geotiffdata, x_int + 1, y_int);
                    double alt01 = GetAlt(geotiffdata, x_int, y_int + 1);
                    double alt11 = GetAlt(geotiffdata, x_int + 1, y_int + 1);

                    double v1 = avg(alt00, alt10, x_frac);
                    double v2 = avg(alt01, alt11, x_frac);
                    double v  = avg(v1, v2, y_frac);

                    if (v > -1000)
                    {
                        answer.currenttype = srtm.tiletype.valid;
                    }
                    if (alt00 < -1000 || alt10 < -1000 || alt01 < -1000 || alt11 < -1000)
                    {
                        answer.currenttype = srtm.tiletype.invalid;
                    }
                    answer.alt       = v;
                    answer.altsource = "GeoTiff";
                    return(answer);
                }
            }

            return(srtm.altresponce.Invalid);
        }
        /// <summary>
        /// Get X/Y coordinate array
        /// </summary>
        /// <param name="X">ref X array</param>
        /// <param name="Y">ref Y array</param>
        public void GetXYArray(ref double[] X, ref double[] Y)
        {
            ProjectionInfo aProjInfo = GetProjectionInfo();

            switch (aProjInfo.Transform.Proj4Name)
            {
            case "lonlat":
                switch (TemplateNum)
                {
                case 0:
                case 1:
                case 2:
                case 3:
                    X = GetXArray();
                    Y = GetYArray();
                    break;

                case 40:
                case 41:
                case 42:
                case 43:          // Gaussian latitude/longitude
                    X = GetXArray();
                    Y = GetGaussYArray();
                    break;
                }
                break;

            case "ortho":
            case "geos":
                //Get under satellite point X/Y
                ProjectionInfo fromProj = KnownCoordinateSystems.Geographic.World.WGS1984;
                double         s_X, s_Y;
                double[][]     points = new double[1][];
                points[0] = new double[] { lo1, la1 };
                Reproject.ReprojectPoints(points, fromProj, aProjInfo, 0, 1);
                s_X = points[0][0];
                s_Y = points[0][1];

                //Get integer sync X/Y
                int    i_XP, i_YP;
                double i_X, i_Y;
                i_XP = (int)xp;
                if (xp == i_XP)
                {
                    i_X = s_X;
                }
                else
                {
                    i_X = s_X - (xp - i_XP) * dx;
                }
                i_YP = (int)yp;
                if (yp == i_YP)
                {
                    i_Y = s_Y;
                }
                else
                {
                    i_Y = s_Y - (yp - i_YP) * dy;
                }

                //Get left bottom X/Y
                int nx, ny;
                nx = X.Length;
                ny = Y.Length;
                double xlb, ylb;
                xlb = i_X - (i_XP - 1) * dx;
                ylb = i_Y - (i_YP - 1) * dy;

                //Get X Y with orient 0
                int i;
                X = new double[NX];
                Y = new double[NY];
                for (i = 0; i < NX; i++)
                {
                    X[i] = xlb + i * dx;
                }
                for (i = 0; i < NY; i++)
                {
                    Y[i] = ylb + i * dy;
                }
                break;

            default:
                //Get start X/Y
                fromProj  = KnownCoordinateSystems.Geographic.World.WGS1984;
                points    = new double[1][];
                points[0] = new double[] { lo1, la1 };
                Reproject.ReprojectPoints(points, fromProj, aProjInfo, 0, 1);
                s_X = points[0][0];
                s_Y = points[0][1];

                //Get X/Y
                X = new double[NX];
                Y = new double[NY];
                for (i = 0; i < NX; i++)
                {
                    X[i] = s_X + dx * i;
                }

                for (i = 0; i < NY; i++)
                {
                    Y[i] = s_Y + dy * i;
                }
                break;
            }
        }
Esempio n. 18
0
        //Reads the data from data base file and stores in arrays...
        private void GetTerrainData()
        {
            //Loads data from SL terrain database...

            string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "University of Colombo/Hazard Prediction Model/Sl_Grid_Data.mdb");



            con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Persist Security Info=True;Jet OLEDB:Database Password=keevamalamute";
            con.Open();
            da = new OleDbDataAdapter("SELECT * FROM Sl_Grid_Data", con);
            da.Fill(ds, "Sl_Grid_Data");
            con.Close();

            int a = 0;

            for (int j = 0; j < 920; j++)
            {
                for (int i = 0; i < 510; i++)
                {
                    UTMX_SL[j, i]       = (double)ds.Tables[0].Rows[a].ItemArray[1];
                    UTMY_SL[j, i]       = (double)ds.Tables[0].Rows[a].ItemArray[2];
                    slGridHeights[j, i] = (double)ds.Tables[0].Rows[a].ItemArray[3];

                    a += 1;
                }
            }


            //Gets the array location of source point in SLDB...

            List <double> sourcePointUTMCoordX_TEMP = new List <double>();
            List <double> sourcePointUTMCoordY_TEMP = new List <double>();

            var xy = new List <double>();
            var z  = new List <double>();

            ProjectionInfo source = KnownCoordinateSystems.Geographic.World.WGS1984;
            ProjectionInfo dest   = KnownCoordinateSystems.Projected.UtmWgs1984.WGS1984UTMZone44N;

            foreach (PointLatLng p in frmMainHPCM.sourcePointList)
            {
                xy.Add(p.Lng);
                xy.Add(p.Lat);
                z.Add(0);

                var xyA = xy.ToArray();
                var zA  = z.ToArray();
                Reproject.ReprojectPoints(xyA, zA, source, dest, 0, z.Count);
                sourcePointUTMCoordX_TEMP.Add(xyA[0]);
                sourcePointUTMCoordY_TEMP.Add(xyA[1]);

                xy.Clear();
                z.Clear();
            }



            int xi = (Convert.ToInt32(sourcePointUTMCoordX_TEMP[0] - UTMX_SL[0, 0])) / 500;
            int yi = (Convert.ToInt32(sourcePointUTMCoordY_TEMP[0] - UTMY_SL[0, 0])) / 500;


            if (Meteorology.NumberOfMetCellsX % 2 == 0)
            {
                xi = xi - (Meteorology.NumberOfMetCellsX / 2);
            }
            else
            {
                xi = xi - ((Meteorology.NumberOfMetCellsX + 1) / 2);
            }

            if (Meteorology.NumberOfMetCellsY % 2 == 0)
            {
                yi = yi - (Meteorology.NumberOfMetCellsY / 2);
            }
            else
            {
                yi = yi - ((Meteorology.NumberOfMetCellsY + 1) / 2);
            }


            //Pics data from SLDB and loads populates terrain heights...



            dest   = KnownCoordinateSystems.Geographic.World.WGS1984;
            source = KnownCoordinateSystems.Projected.UtmWgs1984.WGS1984UTMZone44N;

            for (int j = 0; j < Meteorology.NumberOfMetCellsY; j++)
            {
                for (int i = 0; i < Meteorology.NumberOfMetCellsX; i++)
                {
                    xy.Clear();
                    z.Clear();

                    double y = UTMY_SL[yi + j, xi + i];
                    double x = UTMX_SL[yi + j, xi + i];

                    xy.Add(x);
                    xy.Add(y);
                    z.Add(0);

                    var xyA = xy.ToArray();
                    var zA  = z.ToArray();
                    Reproject.ReprojectPoints(xyA, zA, source, dest, 0, z.Count);


                    gridPoints[j, i] = new PointLatLng(xyA[1], xyA[0]);
                    Geography.terrainHeights[j, i] = Geography.slGridHeights[yi + j, xi + i];
                    UTMX[j, i] = UTMX_SL[yi + j, xi + i];
                    UTMY[j, i] = UTMY_SL[yi + j, xi + i];
                }
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Main method of this plugin: gets the tiles from the TileManager, stitches them together, and adds the layer to the map.
        /// </summary>
        /// <param name="e">The event args.</param>
        private void UpdateStichedBasemap(DoWorkEventArgs e)
        {
            var map = App.Map as Map;

            if (map == null)
            {
                return;
            }

            var bwProgress = (Func <int, bool>)(p =>
            {
                _bw.ReportProgress(p);
                if (_bw.CancellationPending)
                {
                    e.Cancel = true;
                    return(false);
                }

                return(true);
            });

            var rectangle     = map.Bounds;
            var webMercExtent = map.ViewExtents.Clone() as Extent;

            if (webMercExtent == null)
            {
                return;
            }

            // If ExtendBuffer, correct the displayed extent
            if (map.ExtendBuffer)
            {
                webMercExtent.ExpandBy(-webMercExtent.Width / _extendBufferCoeff, -webMercExtent.Height / _extendBufferCoeff);
            }

            // Clip the reported Web Merc Envelope to be within possible Web Merc extents
            //  This fixes an issue with Reproject returning bad results for very large (impossible) web merc extents reported from the Map
            var webMercTopLeftX  = TileCalculator.Clip(webMercExtent.MinX, TileCalculator.MinWebMercX, TileCalculator.MaxWebMercX);
            var webMercTopLeftY  = TileCalculator.Clip(webMercExtent.MaxY, TileCalculator.MinWebMercY, TileCalculator.MaxWebMercY);
            var webMercBtmRightX = TileCalculator.Clip(webMercExtent.MaxX, TileCalculator.MinWebMercX, TileCalculator.MaxWebMercX);
            var webMercBtmRightY = TileCalculator.Clip(webMercExtent.MinY, TileCalculator.MinWebMercY, TileCalculator.MaxWebMercY);

            if (!bwProgress(25))
            {
                return;
            }

            // Get the web mercator vertices of the current map view
            var mapVertices = new[] { webMercTopLeftX, webMercTopLeftY, webMercBtmRightX, webMercBtmRightY };

            double[] z = { 0, 0 };

            // Reproject from web mercator to WGS1984 geographic
            Reproject.ReprojectPoints(mapVertices, z, _webMercProj, _wgs84Proj, 0, mapVertices.Length / 2);
            var geogEnv = new Envelope(mapVertices[0], mapVertices[2], mapVertices[1], mapVertices[3]);

            if (!bwProgress(40))
            {
                return;
            }

            // Grab the tiles
            var tiles = _tileManager.GetTiles(geogEnv, rectangle, _bw);

            if (!bwProgress(50))
            {
                return;
            }

            // Stitch them into a single image
            var stitchedBasemap = TileCalculator.StitchTiles(tiles.Bitmaps, _opacity);
            var tileImage       = new InRamImageData(stitchedBasemap)
            {
                Projection = _baseMapLayer.Projection
            };

            // report progress and check for cancel
            if (!bwProgress(70))
            {
                return;
            }

            // Tiles will have often slightly different bounds from what we are displaying on screen
            // so we need to get the top left and bottom right tiles' bounds to get the proper extent
            // of the tiled image
            var tileVertices = new[] { tiles.TopLeftTile.MinX, tiles.TopLeftTile.MaxY, tiles.BottomRightTile.MaxX, tiles.BottomRightTile.MinY };

            // Reproject from WGS1984 geographic coordinates to web mercator so we can show on the map
            Reproject.ReprojectPoints(tileVertices, z, _wgs84Proj, _webMercProj, 0, tileVertices.Length / 2);

            tileImage.Bounds = new RasterBounds(stitchedBasemap.Height, stitchedBasemap.Width, new Extent(tileVertices[0], tileVertices[3], tileVertices[2], tileVertices[1]));

            // report progress and check for cancel
            if (!bwProgress(90))
            {
                return;
            }

            _baseMapLayer.Image = tileImage;

            // report progress and check for cancel
            bwProgress(99);
        }
Esempio n. 20
0
        public static QrTestResult TestQRCode(this string qrCode, string districtsShapefile, bool checkOnline = true, double xCoord = double.NaN, double yCoord = double.NaN, bool checkForDuplicates = false)
        {
            var qrTestResult = new QrTestResult();

            if (QRCodes == null && checkForDuplicates == true)
            {
                QRCodes = new List <string>();
            }

            if (String.IsNullOrEmpty(qrCode))
            {
                qrTestResult.AddMessage("No QR-code to test: " + qrCode);
                return(qrTestResult);
            }

            if (Districts == null)
            {
                qrTestResult.AddMessage("Loading districts from Shapefile (once per session): " + districtsShapefile);
                Districts = Shapefile.OpenFile(districtsShapefile);
            }

            string mBaseURL, mMunicipalityAbbreviation, mAreaAbbreviation = "", mRoadID, mSignType, mAUSNumber;

            qrTestResult.AddMessage("Decoded QR code content: " + qrCode);

            qrTestResult.QrCode = qrCode;

            var mRegex = Regex.Match(qrCode, @"http://([a-z\.]*)/([A-Za-z]*)/([A-Za-z]*)/([0-9]*)/([a-zA-Z0-9]*)/([0-9]*)$");

            if (mRegex.Groups.Count != 7)
            {
                qrTestResult.AddMessage("Error: QR code has wrong structure for ANS sign: " + (mRegex.Groups.Count - 1) + " parts, should be 6");
                qrTestResult.StructureOk = false;
                qrTestResult.HasIssue    = true;
                qrTestResult.SignType    = QrTestResult.TypeOfSign.Unknown;
            }
            else
            {
                qrTestResult.AddMessage("Info: QR code has correct structure for ANS sign");
                qrTestResult.StructureOk = true;
                qrTestResult.SignType    = QrTestResult.TypeOfSign.AddressUnitNumber;
                mBaseURL = mRegex.Groups[1].ToString();
                mMunicipalityAbbreviation = mRegex.Groups[2].ToString();
                mAreaAbbreviation         = mRegex.Groups[3].ToString();
                mRoadID    = mRegex.Groups[4].ToString();
                mSignType  = mRegex.Groups[5].ToString();
                mAUSNumber = mRegex.Groups[6].ToString();
            }

            // Check for existence of QR-code in processed batch
            if (checkForDuplicates == true && QRCodes.Contains(qrCode.Trim().ToLower()))
            {
                qrTestResult.AddMessage("QR-code already exists (duplicate): " + qrCode);
                qrTestResult.IsDuplicate = true;
                qrTestResult.HasIssue    = true;
            }
            else
            {
                QRCodes.Add(qrCode.Trim().ToLower());
                qrTestResult.IsDuplicate = false;
            }

            // Check for correct start of QR code
            if (!qrCode.StartsWith("http://myabudhabi.net/adm"))
            {
                qrTestResult.AddMessage("Error: base URL or municipality");
                qrTestResult.UriOk    = false;
                qrTestResult.HasIssue = true;
            }
            else
            {
                qrTestResult.AddMessage("Info: URL part is ok");
                qrTestResult.UriOk = true;
            }

            // Check if codes contains spaces
            if (qrCode.Contains(" "))
            {
                qrTestResult.AddMessage("Error: QR Code contains spaces");
                qrTestResult.SpacesOk = false;
                qrTestResult.HasIssue = true;
            }
            else
            {
                qrTestResult.AddMessage("Info: Contains no spaces");
                qrTestResult.SpacesOk = true;
            }

            // Check if code exists on myabudhabi.net
            MyAbuDhabiNetResponse mResponse = null;

            if (checkOnline)
            {
                if (HasInternetConnection())
                {
                    mResponse = qrCode.DownloadLandingPage().Data as MyAbuDhabiNetResponse;
                    if (mResponse == null || mResponse.status != "success")
                    {
                        qrTestResult.AddMessage("Notice: The QR-code does not exist on myabudhabi.net");
                        qrTestResult.IsOnline = QrTestResult.OnlineStatus.Unavailable;
                        qrTestResult.HasIssue = true;
                    }
                    else
                    {
                        qrTestResult.AddMessage(String.Format("Info: Exists on myabudhabi.net (Longitude: {0}/Latitude: {1}){2}",
                                                              mResponse.x,
                                                              mResponse.y,
                                                              Environment.NewLine));
                        qrTestResult.IsOnline = QrTestResult.OnlineStatus.Available;
                    }
                }
                else
                {
                    qrTestResult.AddMessage("Either the computer is not connected to the Internet or there is a problem with the connection");
                    qrTestResult.IsOnline = QrTestResult.OnlineStatus.Unknown;
                }
            }
            else
            {
                qrTestResult.IsOnline = QrTestResult.OnlineStatus.Unknown;
            }

            // Check if inside district
            Point mPointGeom = null;

            if (xCoord != double.NaN || yCoord != double.NaN)
            {
                mPointGeom = new Point(xCoord, yCoord);
                qrTestResult.HasCoordinates = true;
            }
            else if (mResponse != null)
            {
                double mX, mY;

                if (!double.TryParse(mResponse.x, out mX) || !double.TryParse(mResponse.y, out mY))
                {
                    qrTestResult.AddMessage("Notice: Coordinate values could not be parsed to a number or records on myabudhabi.net does not contain coordinates");
                    qrTestResult.HasCoordinates = false;
                    qrTestResult.HasIssue       = true;
                }
                else
                {
                    var            mPoints  = new double[] { mX, mY };
                    ProjectionInfo pSRSFrom = KnownCoordinateSystems.Geographic.World.WGS1984;
                    ProjectionInfo pSRSTo   = KnownCoordinateSystems.Projected.World.WebMercator;
                    Reproject.ReprojectPoints(mPoints, new double[] { 0 }, pSRSFrom, pSRSTo, 0, 1);
                    mPointGeom = new Point(mPoints[0], mPoints[1]);
                    qrTestResult.HasCoordinates = true;
                }
            }

            if (mPointGeom != null)
            {
                foreach (Feature mFeature in Districts.Features)
                {
                    if (mFeature.Contains(mPointGeom))
                    {
                        if (mFeature.DataRow["DISTRICTABB"].ToString().ToLower().Trim() == mAreaAbbreviation.ToLower())
                        {
                            qrTestResult.AddMessage(String.Format("Info: District abbreviation is correct according to coordinates: {0} ({1}){2}",
                                                                  mFeature.DataRow["NAMELATIN"].ToString(),
                                                                  mFeature.DataRow["DISTRICTABB"].ToString().ToLower(),
                                                                  Environment.NewLine));
                            qrTestResult.DistrictOk = true;
                        }
                        else
                        {
                            qrTestResult.AddMessage(String.Format("Error: District abbreviation is wrong according to coordinates; it is: {1} but should be {0}{2}",
                                                                  mFeature.DataRow["DISTRICTABB"].ToString().ToLower(),
                                                                  mAreaAbbreviation,
                                                                  Environment.NewLine));
                            qrTestResult.DistrictOk = false;
                            qrTestResult.HasIssue   = true;
                        }
                        break;
                    }
                }
            }

            return(qrTestResult);
        }
Esempio n. 21
0
        private void BUT_shptopoly_Click(object sender, EventArgs e)
        {
            using (var fd = new OpenFileDialog())
            {
                fd.Filter = "Shape file|*.shp";
                var result = fd.ShowDialog();
                var file   = fd.FileName;

                var pStart    = new ProjectionInfo();
                var pESRIEnd  = KnownCoordinateSystems.Geographic.World.WGS1984;
                var reproject = false;

                if (File.Exists(file))
                {
                    var prjfile = Path.GetDirectoryName(file) + Path.DirectorySeparatorChar +
                                  Path.GetFileNameWithoutExtension(file) + ".prj";
                    if (File.Exists(prjfile))
                    {
                        using (
                            var re =
                                File.OpenText(Path.GetDirectoryName(file) + Path.DirectorySeparatorChar +
                                              Path.GetFileNameWithoutExtension(file) + ".prj"))
                        {
                            pStart.ParseEsriString(re.ReadLine());

                            reproject = true;
                        }
                    }

                    var fs = FeatureSet.Open(file);

                    fs.FillAttributes();

                    var rows = fs.NumRows();

                    var dtOriginal = fs.DataTable;
                    for (var row = 0; row < dtOriginal.Rows.Count; row++)
                    {
                        var original = dtOriginal.Rows[row].ItemArray;
                    }

                    foreach (DataColumn col in dtOriginal.Columns)
                    {
                        Console.WriteLine(col.ColumnName + " " + col.DataType);
                    }

                    var a = 1;

                    var path = Path.GetDirectoryName(file);

                    foreach (var feature in fs.Features)
                    {
                        var sb = new StringBuilder();

                        sb.Append("#Shap to Poly - Mission Planner\r\n");
                        foreach (var point in feature.Coordinates)
                        {
                            if (reproject)
                            {
                                double[] xyarray = { point.X, point.Y };
                                double[] zarray  = { point.Z };

                                Reproject.ReprojectPoints(xyarray, zarray, pStart, pESRIEnd, 0, 1);

                                point.X = xyarray[0];
                                point.Y = xyarray[1];
                                point.Z = zarray[0];
                            }

                            sb.Append(point.Y.ToString(CultureInfo.InvariantCulture) + "\t" +
                                      point.X.ToString(CultureInfo.InvariantCulture) + "\r\n");
                        }

                        log.Info("writting poly to " + path + Path.DirectorySeparatorChar + "poly-" + a + ".poly");
                        File.WriteAllText(path + Path.DirectorySeparatorChar + "poly-" + a + ".poly", sb.ToString());

                        a++;
                    }
                }
            }
        }
Esempio n. 22
0
        static void Main(string[] args)
        {
            //var t = new test();
            //t.Go();

            //return;

            try
            {
                int c = 0;

                int type = GMapProviders.LithuaniaTOP50Map.DbId;

                //GMaps.Instance.PrimaryCache.DeleteOlderThan(DateTime.MaxValue, type);

                var import = Directory.GetFiles(@"T:\tiles\Layer_NewLayer\", "*.jpg", SearchOption.AllDirectories)
                             .Where(p => p.Contains("Layer_") && !p.Contains("black")).ToList();

                int total = import.Count;

                foreach (string i in import)
                {
                    //using (Bitmap pic = new Bitmap(i))
                    //{
                    //    for (int ii = 0; ii < pic.Width; ii++)
                    //    {
                    //        for (int j = 0; j < pic.Height; j++)
                    //        {
                    //            if (pic.GetPixel(ii, j) == Color.Black)
                    //            {

                    //            }
                    //        }
                    //    }
                    //}

                    string qk = Path.GetFileNameWithoutExtension(i);

                    int x = 0;
                    int y = 0;
                    int z = 0;
                    GMapProviders.BingMap.QuadKeyToTileXY(qk, out x, out y, out z);

                    Debug.WriteLine(c++ + " of " + total + ", x: " + x + ", y: " + y + ", z: " + z);

                    if (!GMaps.Instance.PrimaryCache.PutImageToCache(File.ReadAllBytes(i), type, new GPoint(x, y), z))
                    {
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("import: " + ex);
            }

            if (false)
            {
                var dirs = Directory.GetDirectories(@"D:\Temp\tmap\TOP50LKS");
                foreach (string dir in dirs)
                {
                    var jpg = Directory.GetFiles(dir, "*.jpg");

                    string files = Path.GetFileName(dir).Replace(" ", string.Empty) + " ";

                    if (File.Exists(@"D:\Temp\tmap\tmp\" + files.Replace(" ", string.Empty) + ".png"))
                    {
                        Debug.WriteLine("SKIP: " + dir);
                        continue;
                    }

                    foreach (string j in jpg)
                    {
                        files += "\"" + j + "\" ";
                    }

                    string ice = @"D:\Projektai\Test\ice\ice2\ICE\bin\x64\Debug\ICE.exe";
                    //string ice = @"C:\Program Files\Microsoft Research\Image Composite Editor\ICE.exe";

                    Debug.WriteLine("process: " + dir);

                    Process.Start(ice, files).WaitForExit();

                    //break;
                }
            }

            return;

            AppDomain.CurrentDomain.AssemblyLoad += CurrentDomain_AssemblyLoad;

            GMapProvider.WebProxy     = new WebProxy("127.0.0.1", 1080);
            GMapProvider.IsSocksProxy = true;

            //GMapProvider.WebProxy = WebRequest.DefaultWebProxy;

            //Debug.WriteLine("DbId: " + GMapProviders.YahooMap.DbId);

            if (false)
            {
                GMaps.Instance.EnableTileHost(8844);

                Console.ReadLine();

                GMaps.Instance.DisableTileHost();
                GMaps.Instance.CancelTileCaching();

                return;
            }

            if (false)
            {
                GeoCoderStatusCode status;
                var pp1 = GMapProviders.GoogleMap.GetPoint("Lithuania, Seda", out status);

                return;
            }

            if (false)
            {
                GeoCoderStatusCode status;
                var pp1 = GMapProviders.GoogleMap.GetPoint("Lithuania, vilnius, Antakalnio g. 67-35", out status);

                List <Placemark> plc = null;
                //var st = GMapProviders.GoogleMap.GetPlacemarks(new PointLatLng(54.6961334816182, 25.2985095977782), out plc);
                var st = GMapProviders.GoogleMap.GetPlacemarks(pp1.Value, out plc);

                if (st == GeoCoderStatusCode.OK && plc != null)
                {
                    foreach (var pl in plc)
                    {
                        if (!string.IsNullOrEmpty(pl.PostalCodeNumber))
                        {
                            Debug.WriteLine("Accuracy: " + pl.Accuracy + ", " + pl.Address + ", PostalCodeNumber: " +
                                            pl.PostalCodeNumber);
                        }
                    }
                }

                return;
            }

            if (false)
            {
                var p1 = new PointLatLng(54.6961334816182, 25.2985095977782);
                var p2 = new PointLatLng(54.7061334816182, 25.3085095977783);

                //GMaps.Instance.ImportFromGMDB(@"C:\Users\m.dambrauskas\AppData\Local\GMap.NET\TileDBv5\en\Data - Copy.gmdb");

                //var route = GMapProviders.OpenStreetMap.GetRoute(p1, p2, false, false, 10);
                //var route = GMapProviders.CloudMadeMap.GetRoute(p1, p2, false, false, 10);

                //Debug.WriteLine(GMapProviders.BingHybridMap.Name + ":" + GMapProviders.BingHybridMap.DbId);

                GeoCoderStatusCode status;
                var pp1 = GMapProviders.GoogleMap.GetPoint("Lithuania,Vilnius", out status);
                var pp2 = GMapProviders.GoogleMap.GetPoint("Lithuania,Kaunas", out status);
                if (pp1.HasValue && pp2.HasValue)
                {
                    GDirections s;
                    //var x = GMapProviders.GoogleMap.GetDirections(out s, "Lithuania,Vilnius", "Lithuania,Kaunas", false, false, false, true);
                    //if(x == DirectionsStatusCode.OK)
                    var x = GMapProviders.GoogleMap.GetDirections(out s,
                                                                  pp1.Value,
                                                                  pp2.Value,
                                                                  false,
                                                                  false,
                                                                  false,
                                                                  false,
                                                                  true);
                    {
                        Debug.WriteLine(s.Summary + ", " + s.Copyrights);
                        Debug.WriteLine(s.StartAddress + " -> " + s.EndAddress);
                        Debug.WriteLine(s.Distance);
                        Debug.WriteLine(s.Duration);
                        foreach (var step in s.Steps)
                        {
                            Debug.WriteLine(step);
                        }
                    }
                }
            }

            if (false)
            {
                var p = PlateCarreeProjectionDarbAe.Instance;

                var l = new PointLatLng(29.4052130085331, 41.522866508209);

                Debug.WriteLine("121 * 256: " + 121 * 256 + "px : Y");
                Debug.WriteLine("144 * 256: " + 144 * 256 + "px : X");

                Debug.WriteLine("l: " + l);

                var px = p.FromLatLngToPixel(l, 0);

                Debug.WriteLine("FromLatLngToPixel: " + px);

                var ll = p.FromPixelToLatLng(px, 0);
                Debug.WriteLine("FromPixelToLatLng: " + ll);


                var tl = p.FromPixelToTileXY(px);

                Debug.WriteLine("FromPixelToTileXY: " + tl);
            }

            /*
             * 0/1 = 2
             * 1/2 = 1,5
             * 2/3 = 2
             * 3/4 = 2
             * 4/5 = 2,5
             * 5/6 = 2
             * 6/7 = 2
             * 7/8 = 2
             * 8/9 = 2,5
             * 9/10 = 2
             * 10/11 = 2,5
             * 11/12 = 2
             */

            if (false)
            {
                var p = LKS94Projection.Instance;
                //var p = PlateCarreeProjection.Instance;

                var pos = new PointLatLng(54.6961334816182, 25.2985095977783);

                {
                    int       zoom = 4;
                    var       px   = p.FromPixelToTileXY(p.FromLatLngToPixel(pos, zoom));
                    Exception ex   = null;
                    var       img  = GMaps.Instance.GetImageFrom(GMapProviders.LithuaniaMap, px, zoom, out ex);
                    File.WriteAllBytes(zoom + "z-" + px + ".png", img.Data.ToArray());
                }

                for (int i = 0; i < 12; i++)
                {
                    double scale  = p.GetGroundResolution(i, pos.Lat);
                    double scale2 = p.GetGroundResolution(i + 1, pos.Lat);

                    double s = scale / scale2;

                    Debug.WriteLine(i + "/" + (i + 1) + " = " + s);
                }
            }

#if DEBUG
            if (false)
            {
                //GMaps.Instance.PrimaryCache.DeleteOlderThan(DateTime.Now, GMapProviders.GoogleMap.DbId);

                GMaps.Instance.Mode = AccessMode.CacheOnly;

                using (var c = new Core())
                {
                    //c.compensationOffset = new GPoint(200, 200);

                    c.minZoom  = 1;
                    c.maxZoom  = 25;
                    c.Zoom     = 16;
                    c.Provider = GMapProviders.OpenStreetMap;
                    c.Position = new PointLatLng(54.6961334816182, 25.2985095977783);
                    c.OnMapSizeChanged(400, 400);

                    c.OnMapOpen();

                    Debug.WriteLine("Position: " + c.Position);
                    Debug.WriteLine("renderOffset: " + c.renderOffset);
                    Debug.WriteLine("compensationOffset: " + c.compensationOffset);

                    var l = c.FromLatLngToLocal(c.Position);
                    Debug.WriteLine("local: " + l);

                    var g = c.FromLocalToLatLng(l.X, l.Y);
                    Debug.WriteLine("geo: " + g);

                    //c.ReloadMap();

                    Console.ReadLine();

                    c.OnMapClose();
                }
            }

            if (false)
            {
                int i = 0;

                //while(true)
                {
                    Console.WriteLine(i + " start");
                    Debug.WriteLine(i + " start");

                    //using(Core c = new Core())
                    var c = new Core();
                    {
                        var f = c.OnMapOpen();

                        Console.WriteLine("wait");
                        Console.ReadLine();

                        //c.OnMapClose();
                    }
                    c = null;

                    Debug.WriteLine("end");
                    Console.WriteLine("end");

                    Console.ReadLine();

                    GC.Collect();

                    //if(i++ > 10)
                    //{
                    //   GC.Collect();
                    //   i = 0;
                    //}
                }
            }
#endif

            if (false)
            {
                //-34,8859309407532, Lng=-58,359375
                var p1 = new PointLatLng(-34.608, -58.348);
                var p2 = new PointLatLng(-34.608, -58.348);

                //Sets up a array to contain the x and y coordinates
                var xy = new double[4] {
                    p1.Lng, p1.Lat, p2.Lng, p2.Lat
                };

                //An array for the z coordinate
                var z = new double[1];
                z[0] = 1;

                var pStart = KnownCoordinateSystems.Geographic.World.WGS1984;
                var pEnd   = new ProjectionInfo();

                //ProjectionInfo pEnd = new ProjectionInfo("+proj=tmerc +lat_0=0 +lon_0=15 +k=0.9996 +x_0=4200000 +y_0=-1300000 +ellps=WGS84 +datum=WGS84 +to_meter=0.03125 +no_defs");
                //ProjectionInfo pEnd = new ProjectionInfo("+proj=tmerc +lat_0=-34.629269 +lon_0=-58.4633 +k=0.9999980000000001 +x_0=100000 +y_0=100000 +ellps=intl +units=m +no_defs");

                Reproject.ReprojectPoints(xy, z, pStart, pEnd, 0, 2);

                Debug.WriteLine(" true1: " + (int)xy[0] + "; " + (int)xy[1]);

                //var prj = new MapyCZProjection();
                //{
                //   var p2 = prj.WGSToPP(y, x);

                //   Debug.WriteLine("false1: " + p2[0] + "; " + p2[1]);

                //   var p3 = prj.PPToWGS(p2[0], p2[1]);

                //   Reproject.ReprojectPoints(xy, z, pEnd, pStart, 0, 1);

                //   Debug.WriteLine("");
                //   Debug.WriteLine(" true2: " + xy[0] + "; " + xy[1]);
                //   Debug.WriteLine("false2: " + p3[1] + "; " + p3[0]);
                //}
                // 134400000],PARAMETER["false_northing",-41600000
            }

            // stop caching immediately
            GMaps.Instance.CancelTileCaching();

            //Console.ReadLine();
        }
        /// <summary>
        /// Read MICAPS 4 data info
        /// </summary>
        /// <param name="aFile"></param>
        public override void ReadDataInfo(string aFile)
        {
            StreamReader sr = new StreamReader(aFile, Encoding.Default);
            string       aLine;

            string[]      dataArray;
            int           i, j, n, LastNonEmpty;
            List <string> dataList    = new List <string>();
            List <string> disDataList = new List <string>();

            FileName     = aFile;
            aLine        = sr.ReadLine();
            Description  = aLine;
            aLine        = sr.ReadLine();
            dataArray    = aLine.Split();
            LastNonEmpty = -1;
            dataList.Clear();
            for (i = 0; i < dataArray.Length; i++)
            {
                if (dataArray[i] != string.Empty)
                {
                    LastNonEmpty++;
                    dataList.Add(dataArray[i]);
                }
            }
            for (n = 0; n <= 10; n++)
            {
                if (dataList.Count < 19)
                {
                    aLine        = sr.ReadLine();
                    dataArray    = aLine.Split();
                    LastNonEmpty = -1;
                    for (i = 0; i < dataArray.Length; i++)
                    {
                        if (dataArray[i] != string.Empty)
                        {
                            LastNonEmpty++;
                            dataList.Add(dataArray[i]);
                        }
                    }
                }
                else
                {
                    break;
                }
            }
            //DateTime = Convert.ToDateTime(dataList[0] + "-" + dataList[1] + "-" + dataList[2] +
            //    " " + dataList[3] + ":00");
            //DateTime = DateTime.ParseExact(dataList[0] + "-" + dataList[1] + "-" + dataList[2] +
            //    " " + dataList[3] + ":00", "yy-MM-dd HH:mm", null);
            int year = int.Parse(dataList[0]);

            if (year < 100)
            {
                if (year < 50)
                {
                    year = 2000 + year;
                }
                else
                {
                    year = 1900 + year;
                }
            }
            DateTime = new DateTime(year, int.Parse(dataList[1]), int.Parse(dataList[2]), int.Parse(dataList[3]), 0, 0);

            hours         = Convert.ToInt32(dataList[4]);
            level         = Convert.ToInt32(dataList[5]);
            XDelt         = Convert.ToSingle(dataList[6]);
            YDelt         = Convert.ToSingle(dataList[7]);
            XMin          = Convert.ToSingle(dataList[8]);
            XMax          = Convert.ToSingle(dataList[9]);
            YMin          = Convert.ToSingle(dataList[10]);
            YMax          = Convert.ToSingle(dataList[11]);
            XNum          = Convert.ToInt32(dataList[12]);
            YNum          = Convert.ToInt32(dataList[13]);
            contourDelt   = Convert.ToSingle(dataList[14]);
            contourSValue = Convert.ToSingle(dataList[15]);
            contourEValue = Convert.ToSingle(dataList[16]);
            smoothCo      = Convert.ToSingle(dataList[17]);
            boldValue     = Convert.ToSingle(dataList[18]);
            if ((string)dataList[16] == "-1" || (string)dataList[16] == "-2" || (string)dataList[16] == "-3")
            {
                isLonLat = false;
                if ((string)dataList[16] == "-1")  // 兰勃托投影
                {
                    ProjectionInfo = KnownCoordinateSystems.Projected.Asia.AsiaLambertConformalConic;
                    double[][] points = new double[3][];
                    points[0] = new double[] { XDelt, YDelt };  //第一行最后一个点
                    points[1] = new double[] { XMin, YMin };    //第一行第一个点
                    points[2] = new double[] { XMax, YMax };    //最后一行最后一个点
                    Reproject.ReprojectPoints(points, KnownCoordinateSystems.Geographic.World.WGS1984, ProjectionInfo, 0, 3);
                    XMin  = (float)points[1][0];
                    XMax  = (float)points[0][0];
                    YMin  = (float)points[0][1];
                    YMax  = (float)points[2][1];
                    XDelt = (XMax - XMin) / (XNum - 1);
                    YDelt = (YMax - YMin) / (YNum - 1);
                }
            }
            else
            {
                isLonLat = true;
            }
            X = new double[XNum];
            for (i = 0; i < XNum; i++)
            {
                X[i] = XMin + i * XDelt;
            }
            Y = new double[YNum];

            bool yReversed = false;

            if (YDelt < 0)
            {
                yReversed = true;
                YDelt     = -YDelt;
            }
            if (YMin > YMax)
            {
                float temp = YMin;
                YMin = YMax;
                YMax = temp;
            }
            for (i = 0; i < YNum; i++)
            {
                Y[i] = YMin + i * YDelt;
            }

            string dataStr = sr.ReadToEnd();

            sr.Close();
            dataArray    = dataStr.Split();
            LastNonEmpty = -1;
            dataList.Clear();
            for (i = 0; i < dataArray.Length; i++)
            {
                if (dataArray[i] != string.Empty)
                {
                    LastNonEmpty++;
                    dataList.Add(dataArray[i]);
                }
            }

            double[,] gridData = new double[YNum, XNum];
            for (i = 0; i < YNum; i++)
            {
                for (j = 0; j < XNum; j++)
                {
                    gridData[i, j] = Convert.ToDouble(dataList[i * XNum + j]);
                }
            }

            if (!yReversed)
            {
                GridData = gridData;
            }
            else
            {
                GridData = new double[YNum, XNum];
                for (i = 0; i < YNum; i++)
                {
                    for (j = 0; j < XNum; j++)
                    {
                        GridData[i, j] = gridData[YNum - i - 1, j];
                    }
                }
            }

            Dimension tdim = new Dimension(DimensionType.T);

            tdim.DimValue.Add(DataConvert.ToDouble(DateTime));
            tdim.DimLength     = 1;
            this.TimeDimension = tdim;
            Dimension zdim = new Dimension(DimensionType.Z);

            zdim.DimValue.Add(level);
            zdim.DimLength = 1;
            Dimension xdim = new Dimension(DimensionType.X);

            xdim.SetValues(X);
            Dimension ydim = new Dimension(DimensionType.Y);

            ydim.SetValues(Y);

            List <Variable> variables = new List <Variable>();
            Variable        var       = new Variable();

            var.Name      = "var";
            var.IsStation = true;
            var.SetDimension(tdim);
            var.SetDimension(zdim);
            var.SetDimension(ydim);
            var.SetDimension(xdim);
            variables.Add(var);
            this.Variables = variables;
        }
        private void mainMap_MouseMove(object sender, MouseEventArgs e)
        {
            if (!ShowCoordinates)
            {
                return;
            }

            var projCor        = new Coordinate();
            var _mouseLocation = new System.Drawing.Point();

            _mouseLocation.X = e.X;
            _mouseLocation.Y = e.Y;
            projCor          = mainMap.PixelToProj(_mouseLocation);

            var xy = new double[2];

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

            var z = new double[1];

            if (!isWgs84)
            {
                Reproject.ReprojectPoints(xy, z, currentMapProjection, wgs84Projection, 0, 1);
            }

            //Convert to Degrees Minutes Seconds
            double[] coord = new double[2];
            coord[0] = Math.Abs(xy[0]);
            coord[1] = Math.Abs(xy[1]);

            double[] d = new double[2];
            double[] m = new double[2];
            double[] s = new double[2];

            d[0]      = Math.Floor(coord[0]);
            coord[0] -= d[0];
            coord[0] *= 60;

            m[0]      = Math.Floor(coord[0]);
            coord[0] -= m[0];
            coord[0] *= 60;

            s[0] = Math.Floor(coord[0]);

            d[1]      = Math.Floor(coord[1]);
            coord[1] -= d[1];
            coord[1] *= 60;

            m[1]      = Math.Floor(coord[1]);
            coord[1] -= m[1];
            coord[1] *= 60;

            s[1] = Math.Floor(coord[1]);

            string Long;
            string Lat;

            if (projCor.X > 0)
            {
                Long = "E";
            }
            else if (projCor.X < 0)
            {
                Long = "W";
            }
            else
            {
                Long = " ";
            }

            if (projCor.Y > 0)
            {
                Lat = "N";
            }
            else if (projCor.Y < 0)
            {
                Lat = "S";
            }
            else
            {
                Lat = " ";
            }

            latLonStatusPanel.Caption = "Longitude: " + d[0].ToString() + "°" + m[0].ToString("00") + "'" + s[0].ToString("00") + "\"" + Long + ", Latitude: " + d[1].ToString() + "°" + m[1].ToString("00") + "'" + s[1].ToString("00") + "\"" + Lat;
        }
Esempio n. 25
0
        private static void TestWithSplittingLargeShapeFIle(ProgramOptions options, int z)
        {
            var helper = new OgrHelper(new DefaultEnvironmentVariableProvider(readOnlyValues:
                                                                              new Dictionary <string, string> {
                { "gdal", @"C:\python\WinPython-64bit-2.7.6.4-gdal\tools\gdal" },
                { "GDAL_DATA", @"C:\python\WinPython-64bit-2.7.6.4-gdal\tools\gdal-data" }
            }));

            var source = new OgrDataSource(helper, options.Source);

            source.CacheDir = options.CacheDir;



            var layer  = source.GetLayerContext("jordstykke") as OgrLayer <OgrEntity>;
            var extent = layer.ExtentAsync.Result;
            var from   = ProjectionInfo.FromProj4String(layer.Proj4TextAsync.Result);
            var to     = ProjectionInfo.FromEpsgCode(3857);

            Reproject.ReprojectPoints(extent, null, from, to, 0, 2);

            var grid = new XYZTileGrid(new TileGrid.TileGridOptions
            {
                MinZoom = 0,
            });


            TileRange range;

            do
            {
                range = grid.GetTileRangeForExtentAndZ(extent, z);
            } while (!(range.MinX == range.MaxX && range.MinY == range.MaxY) && z-- > 0);


            range = grid.GetTileCoordChildTileRange(new int[] { z, range.MinX, range.MinY });


            var createOriginalVectorBlock = grid.CreateCoordinateTreeWalker(extent, async(xyz, parent, tileExtent) =>
            {
                var targetPath = string.Format(@"C:\TestCacheDir\{0}\{1}\{2}.shp", xyz[0], xyz[1], xyz[2]);
                var sourcePath = string.Format(@"C:\TestCacheDir\{0}\{1}\{2}.shp", parent[0], parent[1], parent[2]);

                if (!File.Exists(targetPath))
                {
                    if (!File.Exists(sourcePath))
                    {
                        sourcePath = @"C:\dev\DK_SHAPE_UTM32-EUREF89\MINIMAKS\BASIS\JORDSTYKKE.shp";
                        Reproject.ReprojectPoints(tileExtent, null, to, from, 0, 2);
                    }

                    Directory.CreateDirectory(Path.GetDirectoryName(targetPath));
                    try
                    {
                        var exitcode = await helper.Ogr2OgrClipAsync(
                            sourcePath, targetPath, "epsg:" + to.AuthorityCode,
                            tileExtent);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                }
            }, z, 5);

            createOriginalVectorBlock.LinkTo(new ActionBlock <TileRange>((r) => { }));
            createOriginalVectorBlock.Post(range);
            createOriginalVectorBlock.Complete();
            createOriginalVectorBlock.Completion.Wait();
        }
Esempio n. 26
0
        private void EnableBasemapFetching(string tileServerName, string tileServerUrl)
        {
            ProjectionInfo webMerc = KnownCoordinateSystems.Projected.World.WebMercator;

            // Zoom out as much as possible if there are no other layers.
            //reproject any existing layer in non-webMercator projection.
            //if (App.Map.Layers.Count == 0 || App.Map.Projection != webMerc)
            if (App.Map.Layers.Count == 0)
            {
                ForceMaxExtentZoom();
            }
            else if (!App.Map.Projection.Equals(webMerc))
            {
                //get original view extents
                App.ProgressHandler.Progress(String.Empty, 0, "Reprojecting Map Layers...");
                double[] viewExtentXY = new[] { App.Map.ViewExtents.MinX, App.Map.ViewExtents.MinY, App.Map.ViewExtents.MaxX, App.Map.ViewExtents.MaxY };
                double[] viewExtentZ  = new[] { 0.0, 0.0 };

                //reproject view extents
                Reproject.ReprojectPoints(viewExtentXY, viewExtentZ, App.Map.Projection, webMerc, 0, 2);

                //set the new map extents
                App.Map.ViewExtents = new Extent(viewExtentXY);

                //if projection is not WebMercator - reproject all layers:
                MapFrameProjectionHelper.ReprojectMapFrame(App.Map.MapFrame, webMerc.ToEsriString());

                App.ProgressHandler.Progress(String.Empty, 0, "Loading Basemap...");
            }

            // Special case for WMS
            if (tileServerName.Equals(Properties.Resources.WMSMap, StringComparison.InvariantCultureIgnoreCase))
            {
                using (var wmsDialog = new WMSServerParameters())
                {
                    if (wmsDialog.ShowDialog() != DialogResult.OK)
                    {
                        return;
                    }
                    _tileManager.WmsServerInfo = wmsDialog.WmsServerInfo;
                }
            }

            // Other is a custom service
            if (tileServerName.Equals(Other, StringComparison.InvariantCultureIgnoreCase))
            {
                tileServerUrl = Interaction.InputBox("Please provide the Url for the service.",
                                                     DefaultResponse: "http://tiles.virtualearth.net/tiles/h{key}.jpeg?g=461&mkt=en-us&n=z");

                // Let the user cancel...
                if (String.IsNullOrWhiteSpace(tileServerUrl))
                {
                    return;
                }
            }

            EnableBasemapLayer();

            _tileManager.ChangeService(tileServerName, tileServerUrl);

            if (_bw.IsBusy != true)
            {
                _bw.RunWorkerAsync();
            }
        }
Esempio n. 27
0
        //  [HttpGet]
        //   [Route("tiles/{layer}/{z}/{x}/{y}.{format}")]
        public IHttpActionResult Tile(int z, int x, int y, string format)
        {
            //    var vectorlayerProvider = db.GetOrCreateLayerProvider(layer);
            // using (var db = _datasources.GetDataSourceForLayer(layer))
            // {
            int nwX;
            int nwY;

            _tilesystem.TileXYToPixelXY(x, y, out nwX, out nwY);

            double[] nw = new double[2] {
                0, 0
            };
            double[] se = new double[2] {
                0, 0
            };


            _tilesystem.PixelsToMeters(nwX, nwY, z, out nw[0], out nw[1]);
            _tilesystem.PixelsToMeters(nwX + 256, nwY - 256, z, out se[0], out se[1]);

            var from = ProjectionInfo.FromEpsgCode(3857);
            var to   = ProjectionInfo.FromEpsgCode(25832);

            double[] zo = new double[] { 0 };
            Reproject.ReprojectPoints(nw, null, from, to, 0, 1);
            Reproject.ReprojectPoints(se, null, from, to, 0, 1);
            var boundingBox = GetBoundingBox(nw[0], nw[1], se[0], se[1], 25832);    //4326,25832

            //"POLYGON ((549096.184052115 6091165.87690635, 549096.184052115 6090471.7759259, 549807.355168824 6090471.7759259 0, 549807.355168824 6091165.87690635 0, 549096.184052115 6091165.87690635 0))"
            //549096.184052115 6091165.87690635 549807.355168824 6090471.7759259
            var path = Path.Combine(_cacheDir, string.Format("{0}/{1}/{2}/{3}.{4}", _layer.LayerName, z, x, y, format));

            if (File.Exists(path))
            {
                return(new FileResult(path, "application/json"));
            }

            // using (var test = db.GetLayerContext<TEntity>(layer))
            // {
            var resolution = _tilesystem.Resolution(z);
            var arealLimit = resolution * resolution;
            //  var query = test.GetRegion(boundingBox).Where(t => t.Areal > arealLimit);
            var query = _layer.GetRegion(boundingBox);

            Console.WriteLine("Getting Tile at Resolution {0}", resolution);

            var result = query.ToArray();         //.Reduce(resolution).ToArray(); ;

            Directory.CreateDirectory(Path.GetDirectoryName(path));

            using (FileStream fs = File.Open(Path.ChangeExtension(path, "geojson"), FileMode.Create))
                using (StreamWriter sw = new StreamWriter(fs))
                    using (JsonWriter jw = new JsonTextWriter(sw))
                    {
                        jw.Formatting = Formatting.Indented;

                        JsonSerializer serializer = new JsonSerializer();
                        serializer.Converters.Add(new OgrEntityConverter());
                        serializer.Converters.Add(new DbGeographyGeoJsonConverter());
                        serializer.Serialize(jw, result);
                    }

            var p = new ProcessStartInfo("cmd",
                                         string.Format("/C topojson -p -o {0}.topojson {0}.geojson", Path.GetFileNameWithoutExtension(path)));

            p.WorkingDirectory = Path.GetDirectoryName(path);

            var pro = Process.Start(p);

            pro.WaitForExit();


            return(new FileResult(path, "application/json"));

            //  }
            //  }
        }
        public void ExportGeoJSON()
        {
            //select the objects that want to export as geojson
            List <BaseC3dObject> featureCollection = GetObjects("Export etmek istediğin objeleri seç");

            //defining the variables for coordinate transformation
            string src1 = "+proj=tmerc +lat_0=0 +lon_0=30 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs";

            DotSpatial.Projections.ProjectionInfo info  = ProjectionInfo.FromProj4String(src1);
            DotSpatial.Projections.ProjectionInfo info2 = ProjectionInfo.FromEpsgCode(4326);
            double[]      zet = new double[] { 0, 0 };
            StringBuilder vertexCoordinates = new StringBuilder();
            string        center            = "";

            //seperating the object type of selected objects for specific action
            using (Transaction ts = Dwg.TransactionManager.StartTransaction())
            {
                foreach (BaseC3dObject item in featureCollection)
                {
                    List <double[]> pnts = new List <double[]>();
                    if (item.Name == "LWPOLYLINE")
                    {
                        Autodesk.AutoCAD.DatabaseServices.Polyline lwp = ts.GetObject(item.Id, OpenMode.ForWrite)
                                                                         as Autodesk.AutoCAD.DatabaseServices.Polyline;

                        int      vn        = lwp.NumberOfVertices;
                        double[] fromPoint = new double[vn * 2];
                        int      syc       = 0;
                        for (int i = 0; i < vn; i++)
                        {
                            double east = lwp.GetPoint2dAt(i).X;
                            double nort = lwp.GetPoint2dAt(i).Y;
                            fromPoint[syc]     = east;
                            fromPoint[syc + 1] = nort;
                            syc += 2;
                        }
                        syc = 0;
                        Reproject.ReprojectPoints(fromPoint, zet, info, info2, 0, vn);

                        for (int i = 0; i < vn; i++)
                        {
                            string str = string.Format("[{0},{1}]", fromPoint[syc + 1], fromPoint[syc]);
                            vertexCoordinates.Append(str);
                            syc += 2;
                            if (i != vn - 1)
                            {
                                vertexCoordinates.Append(",");
                            }
                            center = str;
                        }

                        // polyline kapalı ise son kısmına ilk noktayı tekrar atmamız gerekiyor.
                        if (lwp.Closed)
                        {
                            vertexCoordinates.Append(",");
                            string str = string.Format("[{0},{1}]", fromPoint[1], fromPoint[0]);
                            vertexCoordinates.Append(str);
                        }
                    }
                    string geo = GeoObject("LineString", vertexCoordinates.ToString());

                    //WritingToHTML(geo, center);
                }
            }
        }
Esempio n. 29
0
        public void HandleRow(string textline)
        {
            Hashtable rs = _aisParser.Parse(textline);

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

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

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

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

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

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

                        break;

                    case 5:
                        break;

                    default:
                        break;
                    }
                }
            }
        }