コード例 #1
0
        static void Main(string[] args)
        {
            MgdPlatform.Initialize("Platform.ini");

            string currentDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            //Test mapguide-api-base
            MgCoordinateSystemFactory csFact = new MgCoordinateSystemFactory();

            Console.WriteLine("Testing coordinate system categories");
            MgStringCollection csCategories = csFact.EnumerateCategories();

            for (int i = 0; i < csCategories.GetCount(); i++)
            {
                Console.WriteLine(csCategories.GetItem(i));
            }

            //Test mg-desktop
            MgdServiceFactory serviceFact = new MgdServiceFactory();

            Console.Write("Can we create a MgdFeatureService? ");
            MgdFeatureService featSvc = (MgdFeatureService)serviceFact.CreateService(MgServiceType.FeatureService);

            Console.WriteLine("yes");
            Console.Write("Can we create a MgdResourceService? ");
            MgdResourceService resSvc = (MgdResourceService)serviceFact.CreateService(MgServiceType.ResourceService);

            Console.WriteLine("yes");

            MgdPlatform.Terminate();
            Console.WriteLine("Things look all good :) Press any key to continue");
            Console.Read();
        }
コード例 #2
0
        private void OnLineDigitized(double x1, double y1, double x2, double y2)
        {
            MgMapBase map = mgMapViewer1.GetMap();
            //Create a coordiante system from the map's SRS
            MgCoordinateSystemFactory csFactory = new MgCoordinateSystemFactory();
            MgCoordinateSystem        mapCs     = csFactory.Create(map.GetMapSRS());

            //Invoke the appropriate measure method depending on the type
            //of coordinate system
            double dist = 0.0;

            if (mapCs.GetType() == MgCoordinateSystemType.Geographic)
            {
                dist = mapCs.MeasureGreatCircleDistance(x1, y1, x2, y2);
            }
            else
            {
                dist = mapCs.MeasureEuclideanDistance(x1, y1, x2, y2);
            }

            //Convert this distance to meters
            dist = mapCs.ConvertCoordinateSystemUnitsToMeters(dist);

            MessageBox.Show("Distance is: " + dist + " meters");
        }
コード例 #3
0
        /// <summary>
        /// Node GetListOfMAPCSLIBRAR for export to LSP file naming of coordinate systems (all library)
        /// </summary>
        /// <param name="CS_value">Name of type "CoordinateSystem"</param>
        /// <param name="CS_Agree">Permit to add other associated definitions</param>
        /// <param name="Folder_Path">Directory path to save LSP file</param>
        public static void GetAllOfMAPCSLIBRARY(string Folder_Path, string CS_value, string CS_Agree)
        {
            StringBuilder sb        = new StringBuilder();
            var           guid      = Guid.NewGuid();
            string        writePath = $@"{Folder_Path}\{guid}.lsp";

            MgCoordinateSystemFactory    coordSysFactory = new MgCoordinateSystemFactory();
            MgCoordinateSystemCatalog    csCatalog       = coordSysFactory.GetCatalog();
            MgCoordinateSystemDictionary csDict          = csCatalog.GetCoordinateSystemDictionary();

            MgCoordinateSystemEnum csDictEnum = csDict.GetEnum();
            int csCount = csDict.GetSize();

            sb.AppendLine(@"(command ""MAPCSLIBRARYEXPORT""");

            MgStringCollection csNames = csDictEnum.NextName(csCount);
            string             csName  = null;

            for (int i = 0; i < csCount; i++)
            {
                csName = csNames.GetItem(i);
                sb.AppendLine($@"""{csName.ToString()}""" + " " + $"\"{CS_value}\"");
            }
            string space = " ";

            sb.AppendLine(" " + $@"""{space}""" + " " + $@"""{CS_Agree}""" + " " + @"""""" + ")");
            using (StreamWriter export_file = new StreamWriter(writePath, true, Encoding.UTF8))
            {
                export_file.Write(sb.ToString());
            }
        }
コード例 #4
0
        /// <summary>
        /// Coordinate transformation between two world coordinate systems
        /// This Version works with coordinates as X, Y doubles
        /// </summary>
        /// <param name="wkTextSource">The wk text source.</param>
        /// <param name="wkTextTarget">The wk text target.</param>
        /// <param name="inputPointX">The input point X.</param>
        /// <param name="inputPointY">The input point Y.</param>
        /// <param name="transformedPointX">The transformed point X.</param>
        /// <param name="transformedPointY">The transformed point Y.</param>
        /// <returns></returns>
        public static bool TransformPoint2d(string wkTextSource, string wkTextTarget, double inputPointX, double inputPointY, ref double transformedPointX, ref double transformedPointY)
        {
            bool RetVal = false;

            //_logger.Debug("Start TransformPoint2d");
            try
            {
                //Creating coordinate system factory
                MgCoordinateSystemFactory CSFactory = new MgCoordinateSystemFactory();
                //Creating coordinate system objects
                MgCoordinateSystem SourceCS = CSFactory.Create(wkTextSource);
                MgCoordinateSystem TargetCS = CSFactory.Create(wkTextTarget);
                //Creating geometry factory
                MgGeometryFactory GeomFactory = new MgGeometryFactory();
                //Populating geometry factory CreateCoordinateXY
                MgCoordinate SourceCoord = GeomFactory.CreateCoordinateXY(inputPointX, inputPointY);
                //Getting transformation definition
                MgCoordinateSystemTransform CSTransform = CSFactory.GetTransform(SourceCS, TargetCS);
                //Transforming coordinate
                MgCoordinate TargetCoord = CSTransform.Transform(SourceCoord);
                //Populating return coordinate objects
                transformedPointX = TargetCoord.X;
                transformedPointY = TargetCoord.Y;
                RetVal            = true;
            }
            catch (System.Exception ex)
            {
                //_logger.Error("Error in TransformPoint2d", ex);
                throw;
            }
            //_logger.Debug("End TransformPoint2d");
            return(RetVal);
        }
コード例 #5
0
        public static Dictionary <string, object> GetListAndCountOfCategories()        //Работает!
        {
            var guid = Guid.NewGuid();
            MgCoordinateSystemFactory            coordSysFactory = new MgCoordinateSystemFactory();
            MgCoordinateSystemCatalog            csCatalog       = coordSysFactory.GetCatalog();
            MgCoordinateSystemCategoryDictionary csDictCat       = csCatalog.GetCategoryDictionary();

            MgCoordinateSystemEnum csDictCatEnum = csDictCat.GetEnum();
            int csCatCount = csDictCat.GetSize();
            MgStringCollection csCatNames     = csDictCatEnum.NextName(csCatCount);
            string             csCategoryName = null;

            List <string> csCatNamesL = new List <string>();

            for (int i3 = 0; i3 < csCatCount; i3++)
            {
                csCategoryName = csCatNames.GetItem(i3);
                csCatNamesL.Add(csCategoryName);
            }
            return(new Dictionary <string, object>
            {
                { "CatCount", csCatCount },
                { "CatList", csCatNamesL },
            });
        }
コード例 #6
0
ファイル: Program.cs プロジェクト: kanbang/Colt
        static void Main(string[] args)
        {
            MgdPlatform.Initialize("Platform.ini");

            string currentDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            //Test mapguide-api-base
            MgCoordinateSystemFactory csFact = new MgCoordinateSystemFactory();

            Console.WriteLine("Testing coordinate system categories");
            MgStringCollection csCategories = csFact.EnumerateCategories();
            for (int i = 0; i < csCategories.GetCount(); i++)
            {
                Console.WriteLine(csCategories.GetItem(i));
            }

            //Test mg-desktop
            MgdServiceFactory serviceFact = new MgdServiceFactory();
            Console.Write("Can we create a MgdFeatureService? ");
            MgdFeatureService featSvc = (MgdFeatureService)serviceFact.CreateService(MgServiceType.FeatureService);
            Console.WriteLine("yes");
            Console.Write("Can we create a MgdResourceService? ");
            MgdResourceService resSvc = (MgdResourceService)serviceFact.CreateService(MgServiceType.ResourceService);
            Console.WriteLine("yes");

            MgdPlatform.Terminate();
            Console.WriteLine("Things look all good :) Press any key to continue");
            Console.Read();
        }
コード例 #7
0
        internal LocalNativeSimpleTransform(string sourceWkt, string targetWkt)
        {
            var fact   = new MgCoordinateSystemFactory();
            var source = fact.Create(sourceWkt);
            var target = fact.Create(targetWkt);

            _trans = fact.GetTransform(source, target);
        }
コード例 #8
0
        /// <summary>
        /// Node RenameCurrentCategory rename Category form MapCSLibrary
        /// </summary>
        /// <param name="new_cat_name"></param>
        /// <param name="old_cat_name"></param>
        public static void RenameCurrentCategory(string new_cat_name, string old_cat_name)         //Работает!
        {
            MgCoordinateSystemFactory            coordSysFactory = new MgCoordinateSystemFactory();
            MgCoordinateSystemCatalog            csCatalog       = coordSysFactory.GetCatalog();
            MgCoordinateSystemCategoryDictionary csDictCat       = csCatalog.GetCategoryDictionary();

            csDictCat.Rename(old_cat_name, new_cat_name);
        }
コード例 #9
0
        internal LocalNativeSimpleTransform(string sourceWkt, string targetWkt)
        {
            var fact = new MgCoordinateSystemFactory();
            var source = fact.Create(sourceWkt);
            var target = fact.Create(targetWkt);

            _trans = fact.GetTransform(source, target);
        }
コード例 #10
0
    string pointTransformAndWriteZ(string geom, MgMap map)
    {
        double[] x = new double[1];
        double[] y = new double[1];
        double[] z = new double[1];

        MgWktReaderWriter wktrwdmr = new MgWktReaderWriter();
        MgPoint           cntr     = wktrwdmr.Read(geom).Centroid;

        x[0] = cntr.Coordinate.X;
        y[0] = cntr.Coordinate.Y;
        z[0] = 0;

        StringBuilder output = new StringBuilder();

        output.Append("<table width=\"100%\" class=\"results\">");

        //WGS preko MG API
        MgCoordinateSystemFactory fact = new MgCoordinateSystemFactory();
        string wktFrom = map.GetMapSRS();

        string wktTo = "GEOGCS[\"LL84\",DATUM[\"WGS84\",SPHEROID[\"WGS84\",6378137.000,298.25722293]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.01745329251994]]";

        MgCoordinateSystem          CSSource       = fact.Create(wktFrom);
        MgCoordinateSystem          CSTarget       = fact.Create(wktTo);
        MgCoordinateSystemTransform coordTransform = fact.GetTransform(CSSource, CSTarget);

        MgGeometryFactory geomFact = new MgGeometryFactory();

        // GK
        //samo prvo višino zaenkrat, dokler ni enačbe za Z
        output.Append(String.Format("<tr><td class='header'><b>Map koordinates:</b></td><td class=\"results\"><table><tr><td><b>Y:</b></td><td>{0}</td></tr><tr><td><b>X:</b></td><td>{1}</td></tr></table></td></tr>", string.Format("{0:0.0}", x[0]), string.Format("{0:0.0}", y[0])));

        int i = 0;

        //transformacija preko MG koordinatnega sistema
        foreach (double pointX in x)
        {
            MgCoordinate coord = geomFact.CreateCoordinateXY(x[i], y[i]);
            coord = coordTransform.Transform(coord);

            x[i] = coord.X;
            y[i] = coord.Y;

            i++;
        }

        double[] xwgs = x;
        double[] ywgs = y;
        output.Append(String.Format("<tr><td class='header'><b>WGS84:</b></td><td class=\"results\"><table><tr><td><b>Lon:</b></td><td>{0}</td></tr><tr><td><b>Lat:</b></td><td>{1}</td></tr></table></td></tr>", string.Format("{0:0.000000}", xwgs[0]), string.Format("{0:0.000000}", ywgs[0])));

        output.Append("</table>");

        return(output.ToString());
    }
コード例 #11
0
ファイル: Program.cs プロジェクト: kanbang/Colt
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            MgCoordinateSystemFactory fact = new MgCoordinateSystemFactory();
            MgCoordinateSystemCatalog cat = fact.GetCatalog();
            cat.SetDictionaryDir(Path.Combine(Application.StartupPath, "Dictionaries"));

            Application.Run(new MainForm(fact));
        }
コード例 #12
0
        public void Preview(IResource res, IEditorService edSvc, string locale)
        {
            IMapDefinition mapDef = null;
            var            conn   = edSvc.CurrentConnection;

            if (res.ResourceType == ResourceTypes.LayerDefinition.ToString())
            {
                var    ldf = (ILayerDefinition)res;
                string wkt;
                var    env = ldf.GetSpatialExtent(conn, true, out wkt);
                if (env == null)
                {
                    throw new ApplicationException(Strings.CouldNotComputeExtentsForPreview);
                }
                mapDef = Utility.CreateMapDefinition(conn, "Preview");
                mapDef.CoordinateSystem = wkt;
                mapDef.SetExtents(env.MinX, env.MinY, env.MaxX, env.MaxY);
                string resId = "Session:" + edSvc.SessionID + "//" + Guid.NewGuid() + "." + res.ResourceType.ToString();
                conn.ResourceService.SetResourceXmlData(resId, ObjectFactory.Serialize(res));
                mapDef.AddLayer(null, "PreviewLayer", resId);
            }
            else if (res.ResourceType == ResourceTypes.MapDefinition.ToString())
            {
                mapDef = (IMapDefinition)res;
            }
            else if (res.ResourceType == ResourceTypes.WatermarkDefinition.ToString())
            {
                string resId = "Session:" + edSvc.SessionID + "//" + Guid.NewGuid() + "." + res.ResourceType.ToString();
                conn.ResourceService.SetResourceXmlData(resId, ObjectFactory.Serialize(res));

                var csFact = new MgCoordinateSystemFactory();
                var arbXY  = csFact.ConvertCoordinateSystemCodeToWkt("XY-M");
                mapDef = ObjectFactory.CreateMapDefinition(new Version(2, 3, 0), "Preview");
                mapDef.CoordinateSystem = arbXY;
                mapDef.SetExtents(-100000, -100000, 100000, 100000);
                var wm = ((IMapDefinition2)mapDef).AddWatermark(((IWatermarkDefinition)res));
                wm.ResourceId = resId;
            }

            var mapResId = new MgResourceIdentifier("Session:" + edSvc.SessionID + "//" + mapDef.ResourceType.ToString() + "Preview" + Guid.NewGuid() + "." + mapDef.ResourceType.ToString());

            conn.ResourceService.SetResourceXmlData(mapResId.ToString(), ObjectFactory.Serialize(mapDef));

            //MgdMap map = new MgdMap(mapResId);

            //var diag = new MapPreviewWindow(map, conn);
            //diag.ShowDialog();

            var diag = new UI.MapPreviewWindow(conn);

            diag.Init(mapResId);
            diag.ShowDialog();
        }
コード例 #13
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            MgCoordinateSystemFactory fact = new MgCoordinateSystemFactory();
            MgCoordinateSystemCatalog cat  = fact.GetCatalog();

            cat.SetDictionaryDir(Path.Combine(Application.StartupPath, "Dictionaries"));

            Application.Run(new MainForm(fact));
        }
コード例 #14
0
        private static void Main(string[] args)
        {
            if (args.Length == 1)
            {
                if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("MENTOR_DICTIONARY_PATH")))
                {
                    var currentDir    = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);
                    var dictionaryDir = Path.Combine(currentDir, "Dictionaries");
                    if (Directory.Exists(dictionaryDir))
                    {
                        Environment.SetEnvironmentVariable("MENTOR_DICTIONARY_PATH", dictionaryDir, EnvironmentVariableTarget.Process);
                    }
                    else
                    {
                        Console.WriteLine("Error: Could not find CS-Map dictionary path");
                    }
                }

                MgCoordinateSystemFactory csFact = null;
                MgCoordinateSystem        cs     = null;
                try
                {
                    csFact = new MgCoordinateSystemFactory();
                    cs     = csFact.Create(args[0]);
                    double mpu = cs.ConvertCoordinateSystemUnitsToMeters(1.0);
                    Console.WriteLine(mpu);
                    cs.Dispose();
                    csFact.Dispose();
                }
                catch (MgException ex)
                {
                    Console.WriteLine(ex.Message);
                    ex.Dispose();
                }
                finally
                {
                    if (cs != null)
                    {
                        cs.Dispose();
                    }
                    if (csFact != null)
                    {
                        csFact.Dispose();
                    }
                }
            }
            else
            {
                Console.WriteLine("Error: Insufficient arguments. Usage: MpuCalc.exe [Coord sys WKT]");
            }
        }
コード例 #15
0
    // Create a temporary Feature Source to store geocode results.
    public void CreateLocationMarkerFeatureSource(MgFeatureService featureService, MgResourceIdentifier locationMarkerDataResId, MgMap map)
    {
        //String ll84Wkt = "GEOGCS[\"LL84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.25722293287],TOWGS84[0,0,0,0,0,0,0]],PRIMEM[\"Greenwich\",0],UNIT[\"Degrees\",1]]";
        //string ll84Wkt = "LOCAL_CS[\"*XY-MT*\",LOCAL_DATUM[\"*X-Y*\",10000],UNIT[\"Meter\", 1],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH]] ";
        MgCoordinateSystemFactory sysCoordsFactory = new MgCoordinateSystemFactory();
        string srsDefMap = map.GetMapSRS();
        string mapSrsUnits = string.Empty;

        srsDefMap = !string.IsNullOrEmpty(srsDefMap) ? srsDefMap : "LOCAL_CS[\"*XY-MT*\",LOCAL_DATUM[\"*X-Y*\",10000],UNIT[\"Meter\", 1],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH]] ";

        MgCoordinateSystem srsMap = sysCoordsFactory.Create(srsDefMap);
        MgClassDefinition locationClass = new MgClassDefinition();
        locationClass.SetName("LocationMarker");
        MgPropertyDefinitionCollection properties = locationClass.GetProperties();

        MgDataPropertyDefinition idProperty = new MgDataPropertyDefinition("ID");
        idProperty.SetDataType(MgPropertyType.Int32);
        idProperty.SetReadOnly(true);
        idProperty.SetNullable(false);
        idProperty.SetAutoGeneration(true);
        properties.Add(idProperty);

        MgDataPropertyDefinition addressProperty = new MgDataPropertyDefinition("Address");
        addressProperty.SetDataType(MgPropertyType.String);
        addressProperty.SetLength(512);
        properties.Add(addressProperty);

        MgGeometricPropertyDefinition locationProperty = new MgGeometricPropertyDefinition("Location");
        locationProperty.SetGeometryTypes(MgGeometryType.Point);
        locationProperty.SetHasElevation(false);
        locationProperty.SetHasMeasure(false);
        locationProperty.SetReadOnly(false);
        locationProperty.SetSpatialContextAssociation(srsMap.GetCsCode());
        properties.Add(locationProperty);

        MgPropertyDefinitionCollection idProperties = locationClass.GetIdentityProperties();
        idProperties.Add(idProperty);

        locationClass.SetDefaultGeometryPropertyName("Location");

        MgFeatureSchema locationSchema = new MgFeatureSchema();
        locationSchema.SetName("LocationMarkerSchema");
        locationSchema.GetClasses().Add(locationClass);

        MgCreateSdfParams sdfParams = new MgCreateSdfParams(srsMap.GetCsCode(), srsDefMap, locationSchema);

        featureService.CreateFeatureSource(locationMarkerDataResId, sdfParams);
    }
コード例 #16
0
        public void Execute(IPlatformFactory factory, ITestLogger logger)
        {
            MgCoordinateSystemFactory csFactory = new MgCoordinateSystemFactory();
            MgCoordinateSystem        coordSys  = csFactory.CreateFromCode("LL84");

            Assert.AreEqual(MgCoordinateSystemType.Geographic, coordSys.Type);
            Assert.AreEqual("DEGREE", coordSys.Units);
            Assert.AreEqual(-180, coordSys.MinX);
            Assert.AreEqual(-90, coordSys.MinY);
            Assert.AreEqual(180, coordSys.MaxX);
            Assert.AreEqual(90, coordSys.MaxY);
            Assert.AreEqual("LL84", coordSys.CsCode);
            Assert.AreEqual("WGS84 datum, Latitude-Longitude; Degrees", coordSys.Description);
            Assert.AreEqual("LL", coordSys.Projection);
            Assert.AreEqual("Null Projection, produces/processes Latitude & Longitude", coordSys.ProjectionDescription);
            Assert.AreEqual("WGS84", coordSys.Datum);
            Assert.AreEqual("World Geodetic System of 1984", coordSys.DatumDescription);
            Assert.AreEqual("WGS84", coordSys.Ellipsoid);
            Assert.AreEqual("World Geodetic System of 1984, GEM 10C", coordSys.EllipsoidDescription);
        }
コード例 #17
0
    public static string TransformGK2Wgs(double x, double y, string ss, string mpN)
    {
        MgMap map = new MgMap();
        MgResourceService resourceSrvc = GetMgResurceService(ss);
        map.Open(resourceSrvc, mpN);

        //Create coordinate system factory
        MgCoordinateSystemFactory fact = new MgCoordinateSystemFactory();
        string wktFrom = map.GetMapSRS();
        string wktTo = "GEOGCS[\"LL84\",DATUM[\"WGS84\",SPHEROID[\"WGS84\",6378137.000,298.25722293]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.01745329251994]]";

        MgCoordinateSystem coordinateSystemSource = fact.Create(wktFrom);
        MgCoordinateSystem coordinateSystemTarget = fact.Create(wktTo);

        MgGeometryFactory geomFact = new MgGeometryFactory();

        MgCoordinateSystemTransform coordTransform = fact.GetTransform(coordinateSystemSource, coordinateSystemTarget);

        MgCoordinate coord = coordTransform.Transform(x, y);

        return coord.X.ToString().Replace(',', '.') + ";" + coord.Y.ToString().Replace(',', '.');
    }
コード例 #18
0
    public static string TransformGK2Wgs(double x, double y, string ss, string mpN) //Transform from Map to WGS 84 Coordtnate System
    {
        MgMap             map          = new MgMap();
        MgResourceService resourceSrvc = GetMgResurceService(ss);

        map.Open(resourceSrvc, mpN);

        //Create coordinate system factory
        MgCoordinateSystemFactory fact = new MgCoordinateSystemFactory();
        string wktFrom = map.GetMapSRS();
        string wktTo   = "GEOGCS[\"LL84\",DATUM[\"WGS84\",SPHEROID[\"WGS84\",6378137.000,298.25722293]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.01745329251994]]";

        MgCoordinateSystem coordinateSystemSource = fact.Create(wktFrom);
        MgCoordinateSystem coordinateSystemTarget = fact.Create(wktTo);

        MgGeometryFactory geomFact = new MgGeometryFactory();

        MgCoordinateSystemTransform coordTransform = fact.GetTransform(coordinateSystemSource, coordinateSystemTarget);

        MgCoordinate coord = coordTransform.Transform(x, y);

        return(coord.X.ToString().Replace(',', '.') + ";" + coord.Y.ToString().Replace(',', '.'));
    }
コード例 #19
0
        /// <summary>
        /// Node GetCSList returns an external txt file that Contains strings with CS's names
        /// </summary>
        /// <param name="Folder_Path">Directory path to save TXT file</param>
        /// <param name="selection">If = true, export all CS in Library, if false - only Users collection</param>
        public static string GetCSList(string Folder_Path, bool selection)
        {
            StringBuilder sb        = new StringBuilder();
            var           guid      = Guid.NewGuid();
            string        writePath = $@"{Folder_Path}\{guid}CS_List.txt";

            MgCoordinateSystemFactory    coordSysFactory = new MgCoordinateSystemFactory();
            MgCoordinateSystemCatalog    csCatalog       = coordSysFactory.GetCatalog();
            MgCoordinateSystemDictionary csDict          = csCatalog.GetCoordinateSystemDictionary();

            MgCoordinateSystemEnum csDictEnum = csDict.GetEnum();
            int csCount = csDict.GetSize();


            MgStringCollection csNames = csDictEnum.NextName(csCount);
            string             csName  = null;

            MgCoordinateSystem cs = null;
            bool csProtect;

            for (int i = 0; i < csCount; i++)
            {
                csName    = csNames.GetItem(i);
                cs        = csDict.GetCoordinateSystem(csName);
                csProtect = cs.IsProtected();

                if (csProtect == selection)
                {
                    sb.AppendLine(csName.ToString());
                }
            }
            using (StreamWriter export_file = new StreamWriter(writePath, true, Encoding.UTF8))
            {
                export_file.Write(sb.ToString());
            }
            return(writePath);
        }
コード例 #20
0
 public LocalNativeMpuCalculator()
 {
     _csFact = new MgCoordinateSystemFactory();
 }
コード例 #21
0
ファイル: MgBufferControlImpl.cs プロジェクト: achilex/MgDev
        private void btnCreate_Click(object sender, EventArgs e)
        {
            btnCreate.Enabled = false;
            try
            {
                var layerName = txtBufferLayer.Text.Trim();
                if (string.IsNullOrEmpty(layerName))
                {
                    MessageBox.Show(Strings.MsgEnterNameForLayer);
                    return;
                }

                if (lstLayers.SelectedItems.Count == 0)
                {
                    MessageBox.Show(Strings.MsgIncludeLayersToBuffer);
                    return;
                }

                var map      = _viewer.GetMap();
                var layers   = map.GetLayers();
                var provider = _viewer.GetProvider();

                //From here, it's the same logic as buffer.aspx in .net MapGuide AJAX viewer
                MgResourceIdentifier fsId  = new MgResourceIdentifier("Session:" + _sessionId + "//" + txtBufferLayer.Text + "_Buffer.FeatureSource");   //NOXLATE
                MgResourceIdentifier ldfId = new MgResourceIdentifier("Session:" + _sessionId + "//" + txtBufferLayer.Text + "_Buffer.LayerDefinition"); //NOXLATE

                MgLayerBase layer      = Util.FindLayer(layers, txtBufferLayer.Text);
                string[]    layerNames = GetLayerNames();

                double          distance = Convert.ToDouble(numBufferDistance.Value);
                MeasurementUnit bUnits   = (MeasurementUnit)cmbUnits.SelectedItem;
                switch (bUnits)
                {
                case MeasurementUnit.Feet:
                    distance *= 0.30480;
                    break;

                case MeasurementUnit.Kilometers:
                    distance *= 1000;
                    break;

                case MeasurementUnit.Miles:
                    distance *= 1609.35;
                    break;
                }

                String             srsDefMap   = Util.GetMapSrs(map);
                MgCoordinateSystem srsMap      = provider.GetMapCoordinateSystem();
                string             mapSrsUnits = "";
                bool arbitraryMapSrs           = (srsMap.GetType() == MgCoordinateSystemType.Arbitrary);
                if (arbitraryMapSrs)
                {
                    mapSrsUnits = srsMap.GetUnits();
                }

                String xtrans     = String.Format("{0:x2}", ((int)(255 * Convert.ToInt32(numFillTransparency.Value) / 100))); //NOXLATE
                var    lineColor  = Util.ToHtmlColor(pnlBorderColor.BackColor);
                var    foreColor  = Util.ToHtmlColor(pnlFillColor.BackColor);
                var    backColor  = Util.ToHtmlColor(pnlFillBackColor.BackColor);
                String layerTempl = string.Format(Properties.Resources.AreaLayerDef,
                                                  fsId.ToString(),
                                                  "BufferSchema:Buffer", //NOXLATE
                                                  "GEOM",                //NOXLATE
                                                  cmbFillPattern.SelectedItem,
                                                  xtrans + foreColor,
                                                  ((0 != 1 /*transparent*/) ? "ff" : "00") + backColor, //NOXLATE
                                                  cmbBorderPattern.SelectedItem,
                                                  numLineThickness.Value.ToString(NumberFormatInfo.InvariantInfo),
                                                  lineColor
                                                  );
                byte[]       bytes           = Encoding.UTF8.GetBytes(layerTempl);
                MgByteSource src             = new MgByteSource(bytes, bytes.Length);
                MgByteReader layerDefContent = src.GetReader();
                _resSvc.SetResource(ldfId, layerDefContent, null);

                bool newBuffer = false;
                if (layer == null)
                {
                    newBuffer = true;

                    //Targetting a new layer. create a data source for it
                    //
                    MgClassDefinition classDef = new MgClassDefinition();

                    classDef.SetName("Buffer");                                //NOXLATE
                    classDef.SetDescription("Feature class for buffer layer"); //NOXLATE
                    classDef.SetDefaultGeometryPropertyName("GEOM");           //NOXLATE

                    //Set KEY property
                    MgDataPropertyDefinition prop = new MgDataPropertyDefinition("KEY"); //NOXLATE
                    prop.SetDataType(MgPropertyType.Int32);
                    prop.SetAutoGeneration(true);
                    prop.SetReadOnly(true);
                    classDef.GetIdentityProperties().Add(prop);
                    classDef.GetProperties().Add(prop);

                    //Set ID property. Hold this segment ID
                    prop = new MgDataPropertyDefinition("ID"); //NOXLATE
                    prop.SetDataType(MgPropertyType.Int32);
                    classDef.GetProperties().Add(prop);

                    //Set geometry property
                    MgGeometricPropertyDefinition geomProp = new MgGeometricPropertyDefinition("GEOM"); //NOXLATE
                    //prop.SetGeometryTypes(MgFeatureGeometricType.mfgtSurface); //TODO use the constant when exposed
                    geomProp.SetGeometryTypes(4);
                    classDef.GetProperties().Add(geomProp);

                    //Create the schema
                    MgFeatureSchema schema = new MgFeatureSchema("BufferSchema", "Temporary buffer schema"); //NOXLATE
                    schema.GetClasses().Add(classDef);

                    //finally, creation of the feature source
                    MgFileFeatureSourceParams sdfParams = new MgFileFeatureSourceParams("OSGeo.SDF", "LatLong", map.GetMapSRS(), schema); //NOXLATE
                    _featSvc.CreateFeatureSource(fsId, sdfParams);

                    //Add layer to map
                    layer = provider.CreateLayer(ldfId);
                    layer.SetName(txtBufferLayer.Text);
                    layer.SetLegendLabel(txtBufferLayer.Text);
                    layer.SetDisplayInLegend(true);
                    layer.SetSelectable(true);
                    layers.Insert(0, layer);
                }
                else
                {
                    //data source already exist. clear its content
                    //
                    Util.ClearDataSource(_featSvc, fsId, "BufferSchema:Buffer"); //NOXLATE
                }

                var sel       = _viewer.GetSelection();
                var selLayers = sel.GetLayers();

                MgAgfReaderWriter    agfRW            = new MgAgfReaderWriter();
                MgGeometryCollection bufferGeometries = new MgGeometryCollection();
                MgGeometry           geomBuffer;

                MgFeatureCommandCollection commands = new MgFeatureCommandCollection();
                int featId = 0;

                MgBatchPropertyCollection propCollection = new MgBatchPropertyCollection();

                int excludedLayers                   = 0;
                MgCoordinateSystem   srsDs           = null;
                MgGeometryCollection inputGeometries = new MgGeometryCollection();

                int bufferFeatures = 0;
                for (int li = 0; li < selLayers.GetCount(); li++)
                {
                    MgLayerBase selLayer     = selLayers.GetItem(li);
                    bool        inputLayer   = false;
                    String      selLayerName = selLayer.GetName();
                    for (int il = 0; il < layerNames.Length; il++)
                    {
                        if (layerNames[il].Equals(selLayerName))
                        {
                            inputLayer = true;
                            break;
                        }
                    }
                    if (inputLayer == false)
                    {
                        continue;
                    }

                    // get the data source SRS
                    //
                    MgResourceIdentifier   featSourceId = new MgResourceIdentifier(selLayer.GetFeatureSourceId());
                    MgSpatialContextReader ctxs         = _featSvc.GetSpatialContexts(featSourceId, false);
                    String srsDefDs = string.Empty;
                    if (ctxs != null && ctxs.ReadNext())
                    {
                        srsDefDs = ctxs.GetCoordinateSystemWkt();
                    }

                    if (srsDefDs == null || srsDefDs.Length == 0)
                    {
                        excludedLayers++;
                        continue;
                    }

                    var srsFactory = new MgCoordinateSystemFactory();
                    srsDs = srsFactory.Create(srsDefDs);
                    bool   arbitraryDsSrs = (srsDs.GetType() == MgCoordinateSystemType.Arbitrary);
                    String dsSrsUnits     = string.Empty;

                    if (arbitraryDsSrs)
                    {
                        dsSrsUnits = srsDs.GetUnits();
                    }

                    // exclude layer if:
                    //  the map is non-arbitrary and the layer is arbitrary or vice-versa
                    //     or
                    //  layer and map are both arbitrary but have different units
                    //
                    if ((arbitraryDsSrs != arbitraryMapSrs) || (arbitraryDsSrs && (dsSrsUnits != mapSrsUnits)))
                    {
                        excludedLayers++;
                        continue;
                    }

                    // calculate distance in the data source SRS units
                    //
                    double dist = srsDs.ConvertMetersToCoordinateSystemUnits(distance);

                    // calculate great circle unless data source srs is arbitrary
                    MgCoordinateSystemMeasure measure;
                    if (!arbitraryDsSrs)
                    {
                        measure = srsDs.GetMeasure();
                    }
                    else
                    {
                        measure = null;
                    }

                    // create a SRS transformer if necessary
                    MgCoordinateSystemTransform srsXform;
                    if (!srsDefDs.Equals(srsDefMap))
                    {
                        srsXform = srsFactory.GetTransform(srsDs, srsMap);
                    }
                    else
                    {
                        srsXform = null;
                    }

                    String featureClassName = selLayer.GetFeatureClassName();
                    String filter           = sel.GenerateFilter(selLayer, featureClassName);
                    if (filter == null || filter.Length == 0)
                    {
                        continue;
                    }

                    MgFeatureQueryOptions query = new MgFeatureQueryOptions();
                    query.SetFilter(filter);

                    MgResourceIdentifier featureSource = new MgResourceIdentifier(selLayer.GetFeatureSourceId());

                    MgFeatureReader features = _featSvc.SelectFeatures(featureSource, featureClassName, query);

                    if (features.ReadNext())
                    {
                        MgClassDefinition classDef     = features.GetClassDefinition();
                        String            geomPropName = classDef.GetDefaultGeometryPropertyName();

                        do
                        {
                            MgByteReader geomReader = features.GetGeometry(geomPropName);
                            MgGeometry   geom       = agfRW.Read(geomReader);

                            if (!chkMergeBuffers.Checked)
                            {
                                geomBuffer = geom.Buffer(dist, measure);
                                if (geomBuffer != null)
                                {
                                    if (srsXform != null)
                                    {
                                        geomBuffer = (MgGeometry)geomBuffer.Transform(srsXform);
                                    }
                                    Util.AddFeatureToCollection(propCollection, agfRW, featId++, geomBuffer);
                                    bufferFeatures++;
                                }
                            }
                            else
                            {
                                if (srsXform != null)
                                {
                                    geom = (MgGeometry)geom.Transform(srsXform);
                                }
                                inputGeometries.Add(geom);
                            }
                        }while (features.ReadNext());

                        features.Close();
                    }
                }

                if (chkMergeBuffers.Checked)
                {
                    if (inputGeometries.GetCount() > 0)
                    {
                        double dist = srsMap.ConvertMetersToCoordinateSystemUnits(distance);
                        MgCoordinateSystemMeasure measure;
                        if (!arbitraryMapSrs)
                        {
                            measure = srsMap.GetMeasure();
                        }
                        else
                        {
                            measure = null;
                        }

                        MgGeometryFactory geomFactory = new MgGeometryFactory();
                        geomBuffer = geomFactory.CreateMultiGeometry(inputGeometries).Buffer(dist, measure);
                        if (geomBuffer != null)
                        {
                            Util.AddFeatureToCollection(propCollection, agfRW, featId, geomBuffer);
                            bufferFeatures = 1;
                        }
                    }
                }

                if (propCollection.GetCount() > 0)
                {
                    commands.Add(new MgInsertFeatures("BufferSchema:Buffer", propCollection)); //NOXLATE

                    //Insert the features in the temporary data source
                    //
                    Util.ReleaseReader(_featSvc.UpdateFeatures(fsId, commands, false), commands);
                }

                // Save the new map state
                //
                layer.ForceRefresh();
                _viewer.RefreshMap();

                //build report message
                if (newBuffer)
                {
                    MessageBox.Show(string.Format(Strings.MsgBufferLayerCreated, txtBufferLayer.Text));
                }
                else
                {
                    MessageBox.Show(string.Format(Strings.MsgBufferLayerUpdated, txtBufferLayer.Text));
                }
            }
            finally
            {
                btnCreate.Enabled = true;
            }
        }
コード例 #22
0
ファイル: MainForm.cs プロジェクト: kanbang/Colt
        private void OnLineDigitized(double x1, double y1, double x2, double y2)
        {
            MgMapBase map = mgMapViewer1.GetMap();
            //Create a coordiante system from the map's SRS
            MgCoordinateSystemFactory csFactory = new MgCoordinateSystemFactory();
            MgCoordinateSystem mapCs = csFactory.Create(map.GetMapSRS());

            //Invoke the appropriate measure method depending on the type
            //of coordinate system
            double dist = 0.0;
            if (mapCs.GetType() == MgCoordinateSystemType.Geographic)
                dist = mapCs.MeasureGreatCircleDistance(x1, y1, x2, y2);
            else
                dist = mapCs.MeasureEuclideanDistance(x1, y1, x2, y2);

            //Convert this distance to meters
            dist = mapCs.ConvertCoordinateSystemUnitsToMeters(dist);

            MessageBox.Show("Distance is: " + dist + " meters");
        }
コード例 #23
0
ファイル: LocalPreviewer.cs プロジェクト: kanbang/Colt
        public void Preview(IResource res, IEditorService edSvc, string locale)
        {
            IMapDefinition mapDef = null;
            var conn = res.CurrentConnection;

            if (res.ResourceType == ResourceTypes.LayerDefinition)
            {
                var ldf = (ILayerDefinition)res;
                string wkt;
                var env = ldf.GetSpatialExtent(true, out wkt);
                if (env == null)
                    throw new ApplicationException(Strings.CouldNotComputeExtentsForPreview);
                mapDef = ObjectFactory.CreateMapDefinition(conn, "Preview");
                mapDef.CoordinateSystem = wkt;
                mapDef.SetExtents(env.MinX, env.MinY, env.MaxX, env.MaxY);
                string resId = "Session:" + edSvc.SessionID + "//" + Guid.NewGuid() + "." + res.ResourceType.ToString();
                edSvc.ResourceService.SetResourceXmlData(resId, ResourceTypeRegistry.Serialize(res));
                mapDef.AddLayer(null, "PreviewLayer", resId);
            }
            else if (res.ResourceType == ResourceTypes.MapDefinition)
            {
                mapDef = (IMapDefinition)res;
            }
            else if (res.ResourceType == ResourceTypes.WatermarkDefinition)
            {
                string resId = "Session:" + edSvc.SessionID + "//" + Guid.NewGuid() + "." + res.ResourceType.ToString();
                edSvc.ResourceService.SetResourceXmlData(resId, ResourceTypeRegistry.Serialize(res));

                var csFact = new MgCoordinateSystemFactory();
                var arbXY = csFact.ConvertCoordinateSystemCodeToWkt("XY-M");
                mapDef = ObjectFactory.CreateMapDefinition(conn, new Version(2, 3, 0), "Preview");
                mapDef.CoordinateSystem = arbXY;
                mapDef.SetExtents(-100000, -100000, 100000, 100000);
                var wm = ((IMapDefinition2)mapDef).AddWatermark(((IWatermarkDefinition)res));
                wm.ResourceId = resId;
            }

            var mapResId = new MgResourceIdentifier("Session:" + edSvc.SessionID + "//" + mapDef.ResourceType.ToString() + "Preview" + Guid.NewGuid() + "." + mapDef.ResourceType.ToString());
            edSvc.ResourceService.SetResourceXmlData(mapResId.ToString(), ResourceTypeRegistry.Serialize(mapDef));

            //MgdMap map = new MgdMap(mapResId);

            //var diag = new MapPreviewWindow(map, conn);
            //diag.ShowDialog();

            var diag = new UI.MapPreviewWindow(conn);
            diag.Init(mapResId);
            diag.ShowDialog();
        }
コード例 #24
0
    string pointTransformAndWriteZ(string geom, MgMap map)
    {
        double[] x = new double[1];
        double[] y = new double[1];
        double[] z = new double[1];

        MgWktReaderWriter wktrwdmr = new MgWktReaderWriter();
        MgPoint cntr = wktrwdmr.Read(geom).Centroid;

        x[0] = cntr.Coordinate.X;
        y[0] = cntr.Coordinate.Y;
        z[0] = 0;

        StringBuilder output = new StringBuilder();
        output.Append("<table width=\"100%\" class=\"results\">");

        //WGS preko MG API
        MgCoordinateSystemFactory fact = new MgCoordinateSystemFactory();
        string wktFrom = map.GetMapSRS();

        string wktTo = "GEOGCS[\"LL84\",DATUM[\"WGS84\",SPHEROID[\"WGS84\",6378137.000,298.25722293]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.01745329251994]]";

        MgCoordinateSystem CSSource = fact.Create(wktFrom);
        MgCoordinateSystem CSTarget = fact.Create(wktTo);
        MgCoordinateSystemTransform coordTransform = fact.GetTransform(CSSource, CSTarget);

        MgGeometryFactory geomFact = new MgGeometryFactory();

        // GK
        //samo prvo višino zaenkrat, dokler ni enačbe za Z
        output.Append(String.Format("<tr><td class='header'><b>Map koordinates:</b></td><td class=\"results\"><table><tr><td><b>Y:</b></td><td>{0}</td></tr><tr><td><b>X:</b></td><td>{1}</td></tr></table></td></tr>", string.Format("{0:0.0}", x[0]), string.Format("{0:0.0}", y[0])));

        int i = 0;

        //transformacija preko MG koordinatnega sistema
        foreach (double pointX in x)
        {
            MgCoordinate coord = geomFact.CreateCoordinateXY(x[i], y[i]);
            coord = coordTransform.Transform(coord);

            x[i] = coord.X;
            y[i] = coord.Y;

            i++;
        }

        double[] xwgs = x;
        double[] ywgs = y;
        output.Append(String.Format("<tr><td class='header'><b>WGS84:</b></td><td class=\"results\"><table><tr><td><b>Lon:</b></td><td>{0}</td></tr><tr><td><b>Lat:</b></td><td>{1}</td></tr></table></td></tr>", string.Format("{0:0.000000}", xwgs[0]), string.Format("{0:0.000000}", ywgs[0])));

        output.Append("</table>");

        return output.ToString();
    }
コード例 #25
0
ファイル: AnalyzingFeatures.cs プロジェクト: achilex/MgDev
        private void btnCreateBuffer_Click(object sender, EventArgs e)
        {
            MgSelectionBase           selection = _viewer.GetSelection();
            MgReadOnlyLayerCollection layers    = selection.GetLayers();

            if (layers == null)
            {
                MessageBox.Show("Select a parcel");
                return;
            }
            MgLayerBase parcels = null;

            for (int i = 0; i < layers.GetCount(); i++)
            {
                MgLayerBase layer = layers.GetItem(i);
                if (layer.Name == "Parcels")
                {
                    parcels = layer;
                    break;
                }
            }
            if (parcels == null)
            {
                MessageBox.Show("Select a parcel");
                return;
            }

            int bufferRingSize  = 100; // measured in metres
            int bufferRingCount = 5;

            // Set up some objects for coordinate conversion
            MgMapBase           map             = _viewer.GetMap();
            MgLayerCollection   mapLayers       = map.GetLayers();
            MgMapViewerProvider provider        = _viewer.GetProvider();
            MgResourceService   resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService);
            //Casting to MgdFeatureService because we want to use convenience APIs
            MgFeatureService featureService = (MgdFeatureService)provider.CreateService(MgServiceType.FeatureService);

            String                    mapWktSrs               = map.GetMapSRS();
            MgAgfReaderWriter         agfReaderWriter         = new MgAgfReaderWriter();
            MgWktReaderWriter         wktReaderWriter         = new MgWktReaderWriter();
            MgCoordinateSystemFactory coordinateSystemFactory = new MgCoordinateSystemFactory();
            MgCoordinateSystem        srs        = coordinateSystemFactory.Create(mapWktSrs);
            MgMeasure                 srsMeasure = srs.GetMeasure();
            string                    sessionId  = Guid.NewGuid().ToString();

            BufferHelper helper = new BufferHelper();

            // Check for a buffer layer. If it exists, delete
            // the current features.
            // If it does not exist, create a feature source and
            // a layer to hold the buffer.

            MgdLayer bufferLayer = null;
            int      layerIndex  = mapLayers.IndexOf("Buffer");

            if (layerIndex < 0)
            {
                // The layer does not exist and must be created.

                MgResourceIdentifier bufferFeatureResId = new MgResourceIdentifier("Session:" + sessionId + "//Buffer.FeatureSource");
                helper.CreateBufferFeatureSource(featureService, mapWktSrs, bufferFeatureResId);
                bufferLayer = helper.CreateBufferLayer(resourceService, bufferFeatureResId, sessionId);
                mapLayers.Insert(0, bufferLayer);
            }
            else
            {
                bufferLayer = (MgdLayer)map.GetLayers().GetItem(layerIndex);
                bufferLayer.DeleteFeatures("ID like '%'");
            }

            // Get the selected features from the MgSelection object
            MgFeatureReader featureReader = selection.GetSelectedFeatures(parcels, parcels.GetFeatureClassName(), false);

            // Process each item in the MgFeatureReader. Get the
            // geometries from all the selected features and
            // merge them into a single geometry.

            MgGeometryCollection inputGeometries = new MgGeometryCollection();

            while (featureReader.ReadNext())
            {
                MgByteReader featureGeometryData = featureReader.GetGeometry(parcels.GetFeatureGeometryName());
                MgGeometry   featureGeometry     = agfReaderWriter.Read(featureGeometryData);

                inputGeometries.Add(featureGeometry);
            }

            MgGeometryFactory geometryFactory  = new MgGeometryFactory();
            MgGeometry        mergedGeometries = geometryFactory.CreateMultiGeometry(inputGeometries);

            // Add buffer features to the temporary feature source.
            // Create multiple concentric buffers to show area.
            // If the stylization for the layer draws the features
            // partially transparent, the concentric rings will be
            // progressively darker towards the center.
            // The stylization is set in the layer template file, which
            // is used in function CreateBufferLayer().

            for (int bufferRing = 0; bufferRing < bufferRingCount; bufferRing++)
            {
                double     bufferDist     = srs.ConvertMetersToCoordinateSystemUnits(bufferRingSize * (bufferRing + 1));
                MgGeometry bufferGeometry = mergedGeometries.Buffer(bufferDist, srsMeasure);

                MgPropertyCollection properties = new MgPropertyCollection();
                properties.Add(new MgGeometryProperty("BufferGeometry", agfReaderWriter.Write(bufferGeometry)));

                MgFeatureReader fr = bufferLayer.InsertFeatures(properties);
                fr.Close();
            }

            bufferLayer.SetVisible(true);
            bufferLayer.ForceRefresh();
            bufferLayer.SetDisplayInLegend(true);

            MessageBox.Show("Buffer created");
            _viewer.RefreshMap();
            IMapLegend legend = Shell.Instance.Legend;

            if (legend != null)
            {
                legend.RefreshLegend();
            }
        }
コード例 #26
0
 public LocalNativeMpuCalculator()
 {
     _csFact = new MgCoordinateSystemFactory();
 }
コード例 #27
0
ファイル: MarkupEditor.cs プロジェクト: ranyaof/Meuhedet
        public void AddBuffer()
        {
            MgMap map = new MgMap();
            map.Open(_resourceService, GetParameter(this.args, "MAPNAME"));

            MgSelection selection = new MgSelection(map);
            selection.Open(_resourceService, map.Name);

            MgReadOnlyLayerCollection layers = selection.GetLayers();
            if (layers != null && layers.Count == 1)
            {
                MgFeatureQueryOptions opt = new MgFeatureQueryOptions();
                opt.SetFilter(selection.GenerateFilter(layers[0], layers[0].FeatureClassName));
                MgFeatureReader featureReader = _featureService.SelectFeatures(new MgResourceIdentifier(layers[0].FeatureSourceId), layers[0].FeatureClassName, opt);
                MgAgfReaderWriter agfRW = new MgAgfReaderWriter();

                MgGeometryCollection inputGeometries = new MgGeometryCollection();

                MgClassDefinition classDef = _featureService.GetClassDefinition(
                    new MgResourceIdentifier(layers[0].FeatureSourceId),
                    layers[0].FeatureClassName.Split(':')[0],
                    layers[0].FeatureClassName.Split(':')[1]);

                while (featureReader.ReadNext())
                {
                    MgByteReader byteReader = featureReader.GetGeometry(classDef.DefaultGeometryPropertyName);
                    MgGeometry geom = agfRW.Read(byteReader);
                    inputGeometries.Add(geom);
                }

                if (inputGeometries.Count > 0)
                {
                    MgCoordinateSystemFactory coordSysFactory = new MgCoordinateSystemFactory();

                    MgCoordinateSystem mapSrs = coordSysFactory.Create(map.MapSRS);
                    double distance = mapSrs.ConvertMetersToCoordinateSystemUnits(7.0);
                    MgCoordinateSystemMeasure measure = mapSrs.GetMeasure();

                    MgGeometryFactory geomFactory = new MgGeometryFactory();
                    MgGeometry buffer = geomFactory.CreateMultiGeometry(inputGeometries).Buffer(distance, measure);

                    if (buffer != null)
                    {
                        MgByteReader byteReader = agfRW.Write(buffer);

                        MgGeometryFactory geometryFactory = new MgGeometryFactory();
                        MgAgfReaderWriter agfWriter = new MgAgfReaderWriter();

                        MgPropertyCollection propertyValues = CreatePropertyCollection(byteReader);

                        this.InsertMarkupFeature(propertyValues);
                    }
                }
            }
        }
コード例 #28
0
 public MainForm(MgCoordinateSystemFactory fact) : this()
 {
     _fact = fact;
 }
コード例 #29
0
ファイル: AnalyzingFeatures.cs プロジェクト: kanbang/Colt
        private void btnCreateBuffer_Click(object sender, EventArgs e)
        {
            MgSelectionBase selection = _viewer.GetSelection();
            MgReadOnlyLayerCollection layers = selection.GetLayers();
            if (layers == null)
            {
                MessageBox.Show("Select a parcel");
                return;
            }
            MgLayerBase parcels = null;
            for (int i = 0; i < layers.GetCount(); i++)
            {
                MgLayerBase layer = layers.GetItem(i);
                if (layer.Name == "Parcels")
                {
                    parcels = layer;
                    break;
                }
            }
            if (parcels == null)
            {
                MessageBox.Show("Select a parcel");
                return;
            }

            int bufferRingSize = 100; // measured in metres
            int bufferRingCount = 5;

            // Set up some objects for coordinate conversion
            MgMapBase map = _viewer.GetMap();
            MgLayerCollection mapLayers = map.GetLayers();
            MgMapViewerProvider provider = _viewer.GetProvider();
            MgResourceService resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService);
            //Casting to MgdFeatureService because we want to use convenience APIs
            MgFeatureService featureService = (MgdFeatureService)provider.CreateService(MgServiceType.FeatureService);

            String mapWktSrs = map.GetMapSRS();
            MgAgfReaderWriter agfReaderWriter = new MgAgfReaderWriter();
            MgWktReaderWriter wktReaderWriter = new MgWktReaderWriter();
            MgCoordinateSystemFactory coordinateSystemFactory = new MgCoordinateSystemFactory();
            MgCoordinateSystem srs = coordinateSystemFactory.Create(mapWktSrs);
            MgMeasure srsMeasure = srs.GetMeasure();
            string sessionId = Guid.NewGuid().ToString();

            BufferHelper helper = new BufferHelper();

            // Check for a buffer layer. If it exists, delete
            // the current features.
            // If it does not exist, create a feature source and
            // a layer to hold the buffer.

            MgdLayer bufferLayer = null;
            int layerIndex = mapLayers.IndexOf("Buffer");
            if (layerIndex < 0)
            {
                // The layer does not exist and must be created.

                MgResourceIdentifier bufferFeatureResId = new MgResourceIdentifier("Session:" + sessionId + "//Buffer.FeatureSource");
                helper.CreateBufferFeatureSource(featureService, mapWktSrs, bufferFeatureResId);
                bufferLayer = helper.CreateBufferLayer(resourceService, bufferFeatureResId, sessionId);
                mapLayers.Insert(0, bufferLayer);
            }
            else
            {
                bufferLayer = (MgdLayer)map.GetLayers().GetItem(layerIndex);
                bufferLayer.DeleteFeatures("ID like '%'");
            }

            // Get the selected features from the MgSelection object
            MgFeatureReader featureReader = selection.GetSelectedFeatures(parcels, parcels.GetFeatureClassName(), false);

            // Process each item in the MgFeatureReader. Get the
            // geometries from all the selected features and
            // merge them into a single geometry.

            MgGeometryCollection inputGeometries = new MgGeometryCollection();
            while (featureReader.ReadNext())
            {
                MgByteReader featureGeometryData = featureReader.GetGeometry(parcels.GetFeatureGeometryName());
                MgGeometry featureGeometry = agfReaderWriter.Read(featureGeometryData);

                inputGeometries.Add(featureGeometry);
            }

            MgGeometryFactory geometryFactory = new MgGeometryFactory();
            MgGeometry mergedGeometries = geometryFactory.CreateMultiGeometry(inputGeometries);

            // Add buffer features to the temporary feature source.
            // Create multiple concentric buffers to show area.
            // If the stylization for the layer draws the features
            // partially transparent, the concentric rings will be
            // progressively darker towards the center.
            // The stylization is set in the layer template file, which
            // is used in function CreateBufferLayer().

            for (int bufferRing = 0; bufferRing < bufferRingCount; bufferRing++)
            {
                double bufferDist = srs.ConvertMetersToCoordinateSystemUnits(bufferRingSize * (bufferRing + 1));
                MgGeometry bufferGeometry = mergedGeometries.Buffer(bufferDist, srsMeasure);

                MgPropertyCollection properties = new MgPropertyCollection();
                properties.Add(new MgGeometryProperty("BufferGeometry", agfReaderWriter.Write(bufferGeometry)));

                MgFeatureReader fr = bufferLayer.InsertFeatures(properties);
                fr.Close();
            }

            bufferLayer.SetVisible(true);
            bufferLayer.ForceRefresh();
            bufferLayer.SetDisplayInLegend(true);

            MessageBox.Show("Buffer created");
            _viewer.RefreshMap();
            IMapLegend legend = Shell.Instance.Legend;
            if (legend != null)
                legend.RefreshLegend();
        }
コード例 #30
0
        public override void Execute(IPlatformFactory factory, ITestLogger logger)
        {
            //For a map definition that links to a default provider tile set and both have the same coordinate
            //system, it should be using the map definition's extents and we should not have null extents or view
            //center

            MgCoordinateSystemFactory csFactory = new MgCoordinateSystemFactory();
            string csWkt = csFactory.ConvertCoordinateSystemCodeToWkt("LL84");

            MgResourceService resSvc = (MgResourceService)factory.CreateService(MgServiceType.ResourceService);

            var root = "../../TestData/TileService/";

            LoadResource(resSvc, "Library://UnitTests/Data/RoadCenterLines.FeatureSource", root + "UT_RoadCenterLines.fs");
            LoadResourceData(resSvc, "Library://UnitTests/Data/RoadCenterLines.FeatureSource", "UT_RoadCenterLines.sdf", MgResourceDataType.File, root + "UT_RoadCenterLines.sdf");
            LoadResource(resSvc, "Library://UnitTests/Layers/RoadCenterLines.LayerDefinition", root + "UT_RoadCenterLines.ldf");

            LoadResource(resSvc, "Library://UnitTests/Data/VotingDistricts.FeatureSource", root + "UT_VotingDistricts.fs");
            LoadResourceData(resSvc, "Library://UnitTests/Data/VotingDistricts.FeatureSource", "UT_VotingDistricts.sdf", MgResourceDataType.File, root + "UT_VotingDistricts.sdf");
            LoadResource(resSvc, "Library://UnitTests/Layers/VotingDistricts.LayerDefinition", root + "UT_VotingDistricts.ldf");

            LoadResource(resSvc, "Library://UnitTests/Data/Parcels.FeatureSource", root + "UT_Parcels.fs");
            LoadResourceData(resSvc, "Library://UnitTests/Data/Parcels.FeatureSource", "UT_Parcels.sdf", MgResourceDataType.File, root + "UT_Parcels.sdf");
            LoadResource(resSvc, "Library://UnitTests/Layers/Parcels.LayerDefinition", root + "UT_Parcels.ldf");

            string tsd = Encoding.UTF8.GetString(Properties.Resources.UT_BaseMapTileSet);

            tsd = string.Format(tsd, csWkt, -87.5, 43.5, -86.5, 44.5);
            byte[]               tsdBytes   = Encoding.UTF8.GetBytes(tsd);
            MgByteSource         sourceTSD  = new MgByteSource(tsdBytes, tsdBytes.Length);
            MgByteReader         contentTSD = sourceTSD.GetReader();
            MgResourceIdentifier resTSD     = new MgResourceIdentifier("Library://UnitTests/TileSets/Test.TileSetDefinition");

            resSvc.SetResource(resTSD, contentTSD, null);

            string mdf = Encoding.UTF8.GetString(Properties.Resources.UT_LinkedTileSet);

            mdf = string.Format(mdf, csWkt, -87.0, 43.0, -86.0, 44.0, resTSD.ToString());
            byte[]               mdfBytes   = Encoding.UTF8.GetBytes(mdf);
            MgByteSource         sourceMDF  = new MgByteSource(mdfBytes, mdfBytes.Length);
            MgByteReader         contentMDF = sourceMDF.GetReader();
            MgResourceIdentifier resMDF     = new MgResourceIdentifier("Library://UnitTests/Maps/LinkedTileSet.MapDefinition");

            resSvc.SetResource(resMDF, contentMDF, null);

            MgMapBase  map    = factory.CreateMap(resMDF);
            MgEnvelope extent = map.GetMapExtent();

            Assert.IsNotNull(extent);
            Assert.IsNotNull(map.MapExtent);
            MgPoint center = map.GetViewCenter();

            Assert.IsNotNull(center);
            Assert.IsNotNull(map.ViewCenter);

            MgCoordinate ll = extent.GetLowerLeftCoordinate();
            MgCoordinate ur = extent.GetUpperRightCoordinate();

            Assert.IsNotNull(ll);
            Assert.IsNotNull(ur);

            Assert.AreEqual(-87.0, ll.X);
            Assert.AreEqual(43.0, ll.Y);
            Assert.AreEqual(-86.0, ur.X);
            Assert.AreEqual(44.0, ur.Y);
        }
コード例 #31
0
ファイル: AnalyzingFeatures.cs プロジェクト: achilex/MgDev
        private void btnFindFeaturesInBuffer_Click(object sender, EventArgs e)
        {
            MgSelectionBase           selection      = _viewer.GetSelection();
            MgReadOnlyLayerCollection selectedLayers = selection.GetLayers();

            if (selectedLayers == null)
            {
                MessageBox.Show("Select a parcel");
                return;
            }
            MgLayerBase parcels = null;

            for (int i = 0; i < selectedLayers.GetCount(); i++)
            {
                MgLayerBase layer = selectedLayers.GetItem(i);
                if (layer.Name == "Parcels")
                {
                    parcels = layer;
                    break;
                }
            }
            if (parcels == null)
            {
                MessageBox.Show("Select a parcel");
                return;
            }

            int bufferRingSize = 500; // measured in metres

            // Set up some objects for coordinate conversion

            MgMapBase           map             = _viewer.GetMap();
            MgLayerCollection   mapLayers       = map.GetLayers();
            MgMapViewerProvider provider        = _viewer.GetProvider();
            MgResourceService   resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService);
            //Casting to MgdFeatureService because we want to use convenience APIs
            MgFeatureService featureService = (MgdFeatureService)provider.CreateService(MgServiceType.FeatureService);
            string           sessionId      = Guid.NewGuid().ToString();

            String                    mapWktSrs               = map.GetMapSRS();
            MgAgfReaderWriter         agfReaderWriter         = new MgAgfReaderWriter();
            MgWktReaderWriter         wktReaderWriter         = new MgWktReaderWriter();
            MgCoordinateSystemFactory coordinateSystemFactory = new MgCoordinateSystemFactory();
            MgCoordinateSystem        srs        = coordinateSystemFactory.Create(mapWktSrs);
            MgMeasure                 srsMeasure = srs.GetMeasure();

            // Check for a buffer layer. If it exists, delete
            // the current features.
            // If it does not exist, create a feature source and
            // a layer to hold the buffer.

            BufferHelper helper      = new BufferHelper();
            MgdLayer     bufferLayer = null;
            int          layerIndex  = map.GetLayers().IndexOf("Buffer");

            if (layerIndex < 0)
            {
                // The layer does not exist and must be created.

                MgResourceIdentifier bufferFeatureResId = new MgResourceIdentifier("Session:" + sessionId + "//Buffer.FeatureSource");
                helper.CreateBufferFeatureSource(featureService, mapWktSrs, bufferFeatureResId);
                bufferLayer = helper.CreateBufferLayer(resourceService, bufferFeatureResId, sessionId);
                map.GetLayers().Insert(0, bufferLayer);
            }
            else
            {
                bufferLayer = (MgdLayer)map.GetLayers().GetItem(layerIndex);
                bufferLayer.DeleteFeatures("ID like '%'");
            }

            // Check for a parcel marker layer. If it exists, delete
            // the current features.
            // If it does not exist, create a feature source and
            // a layer to hold the parcel markers.

            MgdLayer parcelMarkerLayer = null;

            layerIndex = map.GetLayers().IndexOf("ParcelMarker");
            if (layerIndex < 0)
            {
                MgResourceIdentifier parcelFeatureResId = new MgResourceIdentifier("Session:" + sessionId + "//ParcelMarker.FeatureSource");
                helper.CreateParcelMarkerFeatureSource(featureService, mapWktSrs, parcelFeatureResId);
                parcelMarkerLayer = helper.CreateParcelMarkerLayer(resourceService, parcelFeatureResId, sessionId);
                map.GetLayers().Insert(0, parcelMarkerLayer);
            }
            else
            {
                parcelMarkerLayer = (MgdLayer)map.GetLayers().GetItem(layerIndex);
                parcelMarkerLayer.DeleteFeatures("ID like '%'");
            }

            // Check each layer in the selection.

            for (int i = 0; i < selectedLayers.GetCount(); i++)
            {
                // Only check selected features in the Parcels layer.

                MgdLayer layer = (MgdLayer)selectedLayers.GetItem(i);

                if (layer.GetName() == "Parcels")
                {
                    string geomName = layer.GetFeatureGeometryName();
                    System.Diagnostics.Trace.TraceInformation("Marking all parcels inside the buffer that are of type 'MFG'");

                    MgFeatureReader featureReader = selection.GetSelectedFeatures(layer, layer.GetFeatureClassName(), false);


                    // Process each item in the MgFeatureReader. Get the
                    // geometries from all the selected features and
                    // merge them into a single geometry.

                    MgGeometryCollection inputGeometries = new MgGeometryCollection();
                    while (featureReader.ReadNext())
                    {
                        MgByteReader featureGeometryData = featureReader.GetGeometry(geomName);
                        MgGeometry   featureGeometry     = agfReaderWriter.Read(featureGeometryData);

                        inputGeometries.Add(featureGeometry);
                    }

                    MgGeometryFactory geometryFactory  = new MgGeometryFactory();
                    MgGeometry        mergedGeometries = geometryFactory.CreateMultiGeometry(inputGeometries);

                    // Create a buffer from the merged geometries

                    double     bufferDist     = srs.ConvertMetersToCoordinateSystemUnits(bufferRingSize);
                    MgGeometry bufferGeometry = mergedGeometries.Buffer(bufferDist, srsMeasure);

                    // Create a filter to select parcels within the buffer. Combine
                    // a basic filter and a spatial filter to select all parcels
                    // within the buffer that are of type "MFG".

                    MgFeatureQueryOptions queryOptions = new MgFeatureQueryOptions();
                    queryOptions.SetFilter("RTYPE = 'MFG'");
                    queryOptions.SetSpatialFilter(geomName, bufferGeometry, MgFeatureSpatialOperations.Inside);

                    featureReader = layer.SelectFeatures(queryOptions);

                    // Get the features from the feature source,
                    // determine the centroid of each selected feature, and
                    // add a point to the ParcelMarker layer to mark the
                    // centroid.
                    // Collect all the points into an MgFeatureCommandCollection,
                    // so they can all be added in one operation.

                    MgFeatureCommandCollection parcelMarkerCommands = new MgFeatureCommandCollection();
                    int inserted = 0;
                    while (featureReader.ReadNext())
                    {
                        MgByteReader byteReader = featureReader.GetGeometry(geomName);
                        MgGeometry   geometry   = agfReaderWriter.Read(byteReader);
                        MgPoint      point      = geometry.GetCentroid();

                        // Create an insert command for this parcel.
                        MgPropertyCollection properties = new MgPropertyCollection();
                        properties.Add(new MgGeometryProperty("ParcelLocation", agfReaderWriter.Write(point)));
                        //parcelMarkerCommands.Add(new MgInsertFeatures("ParcelMarkerClass", properties));
                        MgFeatureReader fr = parcelMarkerLayer.InsertFeatures(properties);
                        fr.Close();
                        inserted++;
                    }
                    featureReader.Close();

                    if (inserted == 0)
                    {
                        MessageBox.Show("No parcels within the buffer area match.");
                        return;
                    }

                    // Create a feature in the buffer feature source to show the area covered by the buffer.

                    MgPropertyCollection props = new MgPropertyCollection();
                    props.Add(new MgGeometryProperty("BufferGeometry", agfReaderWriter.Write(bufferGeometry)));
                    bufferLayer.InsertFeatures(props);

                    // Ensure that the buffer layer is visible and in the legend.

                    bufferLayer.SetVisible(true);
                    bufferLayer.ForceRefresh();
                    bufferLayer.SetDisplayInLegend(true);
                    parcelMarkerLayer.SetVisible(true);
                    parcelMarkerLayer.ForceRefresh();

                    MessageBox.Show("Done");
                    _viewer.RefreshMap();
                    IMapLegend legend = Shell.Instance.Legend;
                    if (legend != null)
                    {
                        legend.RefreshLegend();
                    }
                }
            }
        }
コード例 #32
0
ファイル: PropertiesTest.cs プロジェクト: kanbang/Colt
 public void CoordinateSystem()
 {
     MgCoordinateSystemFactory factory = new MgCoordinateSystemFactory();
     String wkt = "GEOGCS[\"LL84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.25722293287],TOWGS84[0,0,0,0,0,0,0]],PRIMEM[\"Greenwich\",0],UNIT[\"Degrees\",0.0174532925199433]]";
     MgCoordinateSystem coordSys = factory.Create(wkt);
     Assert.AreEqual(MgCoordinateSystemType.Geographic, coordSys.Type);
     Assert.AreEqual("Degrees", coordSys.Units);
     Assert.AreEqual(-180, coordSys.MinX);
     Assert.AreEqual(-90, coordSys.MinY);
     Assert.AreEqual(180, coordSys.MaxX);
     Assert.AreEqual(90, coordSys.MaxY);
     Assert.AreEqual("", coordSys.Code);
     Assert.AreEqual("", coordSys.Description);
     Assert.AreEqual("Unknown", coordSys.Projection);
     Assert.AreEqual("Unknown", coordSys.ProjectionDescription);
     Assert.AreEqual("WGS_1984", coordSys.Datum);
     Assert.AreEqual("WGS_1984", coordSys.DatumDescription);
     Assert.AreEqual("WGS 84", coordSys.Ellipsoid);
     Assert.AreEqual("WGS 84", coordSys.EllipsoidDescription);
 }
コード例 #33
0
ファイル: MgBufferControlImpl.cs プロジェクト: kanbang/Colt
        private void btnCreate_Click(object sender, EventArgs e)
        {
            btnCreate.Enabled = false;
            try
            {
                var layerName = txtBufferLayer.Text.Trim();
                if (string.IsNullOrEmpty(layerName))
                {
                    MessageBox.Show(Strings.MsgEnterNameForLayer);
                    return;
                }

                if (lstLayers.SelectedItems.Count == 0)
                {
                    MessageBox.Show(Strings.MsgIncludeLayersToBuffer);
                    return;
                }

                var map = _viewer.GetMap();
                var layers = map.GetLayers();
                var provider = _viewer.GetProvider();

                //From here, it's the same logic as buffer.aspx in .net MapGuide AJAX viewer
                MgResourceIdentifier fsId = new MgResourceIdentifier("Session:" + _sessionId + "//" + txtBufferLayer.Text + "_Buffer.FeatureSource"); //NOXLATE
                MgResourceIdentifier ldfId = new MgResourceIdentifier("Session:" + _sessionId + "//" + txtBufferLayer.Text + "_Buffer.LayerDefinition"); //NOXLATE

                MgLayerBase layer = Util.FindLayer(layers, txtBufferLayer.Text);
                string[] layerNames = GetLayerNames();

                double distance = Convert.ToDouble(numBufferDistance.Value);
                MeasurementUnit bUnits = (MeasurementUnit)cmbUnits.SelectedItem;
                switch (bUnits)
                {
                    case MeasurementUnit.Feet:
                        distance *= 0.30480;
                        break;
                    case MeasurementUnit.Kilometers:
                        distance *= 1000;
                        break;
                    case MeasurementUnit.Miles:
                        distance *= 1609.35;
                        break;
                }

                String srsDefMap = Util.GetMapSrs(map);
                MgCoordinateSystem srsMap = provider.GetMapCoordinateSystem();
                string mapSrsUnits = "";
                bool arbitraryMapSrs = (srsMap.GetType() == MgCoordinateSystemType.Arbitrary);
                if (arbitraryMapSrs)
                    mapSrsUnits = srsMap.GetUnits();

                String xtrans = String.Format("{0:x2}", ((int)(255 * Convert.ToInt32(numFillTransparency.Value) / 100))); //NOXLATE
                var lineColor = Util.ToHtmlColor(pnlBorderColor.BackColor);
                var foreColor = Util.ToHtmlColor(pnlFillColor.BackColor);
                var backColor = Util.ToHtmlColor(pnlFillBackColor.BackColor);
                String layerTempl = string.Format(Properties.Resources.AreaLayerDef,
                        fsId.ToString(),
                        "BufferSchema:Buffer", //NOXLATE
                        "GEOM", //NOXLATE
                        cmbFillPattern.SelectedItem,
                        xtrans + foreColor,
                        ((0 != 1/*transparent*/) ? "ff" : "00") + backColor, //NOXLATE
                        cmbBorderPattern.SelectedItem,
                        numLineThickness.Value.ToString(NumberFormatInfo.InvariantInfo),
                        lineColor
                );
                byte[] bytes = Encoding.UTF8.GetBytes(layerTempl);
                MgByteSource src = new MgByteSource(bytes, bytes.Length);
                MgByteReader layerDefContent = src.GetReader();
                _resSvc.SetResource(ldfId, layerDefContent, null);

                bool newBuffer = false;
                if (layer == null)
                {
                    newBuffer = true;

                    //Targetting a new layer. create a data source for it
                    //
                    MgClassDefinition classDef = new MgClassDefinition();

                    classDef.SetName("Buffer"); //NOXLATE
                    classDef.SetDescription("Feature class for buffer layer"); //NOXLATE
                    classDef.SetDefaultGeometryPropertyName("GEOM"); //NOXLATE

                    //Set KEY property
                    MgDataPropertyDefinition prop = new MgDataPropertyDefinition("KEY"); //NOXLATE
                    prop.SetDataType(MgPropertyType.Int32);
                    prop.SetAutoGeneration(true);
                    prop.SetReadOnly(true);
                    classDef.GetIdentityProperties().Add(prop);
                    classDef.GetProperties().Add(prop);

                    //Set ID property. Hold this segment ID
                    prop = new MgDataPropertyDefinition("ID"); //NOXLATE
                    prop.SetDataType(MgPropertyType.Int32);
                    classDef.GetProperties().Add(prop);

                    //Set geometry property
                    MgGeometricPropertyDefinition geomProp = new MgGeometricPropertyDefinition("GEOM"); //NOXLATE
                    //prop.SetGeometryTypes(MgFeatureGeometricType.mfgtSurface); //TODO use the constant when exposed
                    geomProp.SetGeometryTypes(4);
                    classDef.GetProperties().Add(geomProp);

                    //Create the schema
                    MgFeatureSchema schema = new MgFeatureSchema("BufferSchema", "Temporary buffer schema"); //NOXLATE
                    schema.GetClasses().Add(classDef);

                    //finally, creation of the feature source
                    MgFileFeatureSourceParams sdfParams = new MgFileFeatureSourceParams("OSGeo.SDF", "LatLong", map.GetMapSRS(), schema); //NOXLATE
                    _featSvc.CreateFeatureSource(fsId, sdfParams);

                    //Add layer to map
                    layer = provider.CreateLayer(ldfId);
                    layer.SetName(txtBufferLayer.Text);
                    layer.SetLegendLabel(txtBufferLayer.Text);
                    layer.SetDisplayInLegend(true);
                    layer.SetSelectable(true);
                    layers.Insert(0, layer);
                }
                else
                {
                    //data source already exist. clear its content
                    //
                    Util.ClearDataSource(_featSvc, fsId, "BufferSchema:Buffer"); //NOXLATE
                }

                var sel = _viewer.GetSelection();
                var selLayers = sel.GetLayers();

                MgAgfReaderWriter agfRW = new MgAgfReaderWriter();
                MgGeometryCollection bufferGeometries = new MgGeometryCollection();
                MgGeometry geomBuffer;

                MgFeatureCommandCollection commands = new MgFeatureCommandCollection();
                int featId = 0;

                MgBatchPropertyCollection propCollection = new MgBatchPropertyCollection();

                int excludedLayers = 0;
                MgCoordinateSystem srsDs = null;
                MgGeometryCollection inputGeometries = new MgGeometryCollection();

                int bufferFeatures = 0;
                for (int li = 0; li < selLayers.GetCount(); li++)
                {
                    MgLayerBase selLayer = selLayers.GetItem(li);
                    bool inputLayer = false;
                    String selLayerName = selLayer.GetName();
                    for (int il = 0; il < layerNames.Length; il++)
                    {
                        if (layerNames[il].Equals(selLayerName))
                        {
                            inputLayer = true;
                            break;
                        }
                    }
                    if (inputLayer == false)
                    {
                        continue;
                    }

                    // get the data source SRS
                    //
                    MgResourceIdentifier featSourceId = new MgResourceIdentifier(selLayer.GetFeatureSourceId());
                    MgSpatialContextReader ctxs = _featSvc.GetSpatialContexts(featSourceId, false);
                    String srsDefDs = string.Empty;
                    if (ctxs != null && ctxs.ReadNext())
                        srsDefDs = ctxs.GetCoordinateSystemWkt();

                    if (srsDefDs == null || srsDefDs.Length == 0)
                    {
                        excludedLayers++;
                        continue;
                    }

                    var srsFactory = new MgCoordinateSystemFactory();
                    srsDs = srsFactory.Create(srsDefDs);
                    bool arbitraryDsSrs = (srsDs.GetType() == MgCoordinateSystemType.Arbitrary);
                    String dsSrsUnits = string.Empty;

                    if (arbitraryDsSrs)
                        dsSrsUnits = srsDs.GetUnits();

                    // exclude layer if:
                    //  the map is non-arbitrary and the layer is arbitrary or vice-versa
                    //     or
                    //  layer and map are both arbitrary but have different units
                    //
                    if ((arbitraryDsSrs != arbitraryMapSrs) || (arbitraryDsSrs && (dsSrsUnits != mapSrsUnits)))
                    {
                        excludedLayers++;
                        continue;
                    }

                    // calculate distance in the data source SRS units
                    //
                    double dist = srsDs.ConvertMetersToCoordinateSystemUnits(distance);

                    // calculate great circle unless data source srs is arbitrary
                    MgCoordinateSystemMeasure measure;
                    if (!arbitraryDsSrs)
                        measure = srsDs.GetMeasure();
                    else
                        measure = null;

                    // create a SRS transformer if necessary
                    MgCoordinateSystemTransform srsXform;
                    if (!srsDefDs.Equals(srsDefMap))
                        srsXform = srsFactory.GetTransform(srsDs, srsMap);
                    else
                        srsXform = null;

                    String featureClassName = selLayer.GetFeatureClassName();
                    String filter = sel.GenerateFilter(selLayer, featureClassName);
                    if (filter == null || filter.Length == 0)
                        continue;

                    MgFeatureQueryOptions query = new MgFeatureQueryOptions();
                    query.SetFilter(filter);

                    MgResourceIdentifier featureSource = new MgResourceIdentifier(selLayer.GetFeatureSourceId());

                    MgFeatureReader features = _featSvc.SelectFeatures(featureSource, featureClassName, query);

                    if (features.ReadNext())
                    {
                        MgClassDefinition classDef = features.GetClassDefinition();
                        String geomPropName = classDef.GetDefaultGeometryPropertyName();

                        do
                        {
                            MgByteReader geomReader = features.GetGeometry(geomPropName);
                            MgGeometry geom = agfRW.Read(geomReader);

                            if (!chkMergeBuffers.Checked)
                            {
                                geomBuffer = geom.Buffer(dist, measure);
                                if (geomBuffer != null)
                                {
                                    if (srsXform != null)
                                        geomBuffer = (MgGeometry)geomBuffer.Transform(srsXform);
                                    Util.AddFeatureToCollection(propCollection, agfRW, featId++, geomBuffer);
                                    bufferFeatures++;
                                }
                            }
                            else
                            {
                                if (srsXform != null)
                                    geom = (MgGeometry)geom.Transform(srsXform);
                                inputGeometries.Add(geom);
                            }
                        }
                        while (features.ReadNext());

                        features.Close();
                    }
                }

                if (chkMergeBuffers.Checked)
                {
                    if (inputGeometries.GetCount() > 0)
                    {
                        double dist = srsMap.ConvertMetersToCoordinateSystemUnits(distance);
                        MgCoordinateSystemMeasure measure;
                        if (!arbitraryMapSrs)
                            measure = srsMap.GetMeasure();
                        else
                            measure = null;

                        MgGeometryFactory geomFactory = new MgGeometryFactory();
                        geomBuffer = geomFactory.CreateMultiGeometry(inputGeometries).Buffer(dist, measure);
                        if (geomBuffer != null)
                        {
                            Util.AddFeatureToCollection(propCollection, agfRW, featId, geomBuffer);
                            bufferFeatures = 1;
                        }
                    }
                }

                if (propCollection.GetCount() > 0)
                {
                    commands.Add(new MgInsertFeatures("BufferSchema:Buffer", propCollection)); //NOXLATE

                    //Insert the features in the temporary data source
                    //
                    Util.ReleaseReader(_featSvc.UpdateFeatures(fsId, commands, false), commands);
                }

                // Save the new map state
                //
                layer.ForceRefresh();
                _viewer.RefreshMap();

                //build report message
                if (newBuffer)
                    MessageBox.Show(string.Format(Strings.MsgBufferLayerCreated, txtBufferLayer.Text));
                else
                    MessageBox.Show(string.Format(Strings.MsgBufferLayerUpdated, txtBufferLayer.Text));
            }
            finally
            {
                btnCreate.Enabled = true;
            }
        }
コード例 #34
0
ファイル: MgMapViewer.cs プロジェクト: kanbang/Colt
        /// <summary>
        /// Releases the unmanaged resources used by the <see cref="T:System.Windows.Forms.Control"/> and its child controls and optionally releases the managed resources.
        /// </summary>
        /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                base.MouseUp -= OnMapMouseUp;
                base.MouseMove -= OnMapMouseMove;
                base.MouseDown -= OnMapMouseDown;
                base.MouseClick -= OnMapMouseClick;
                base.MouseDoubleClick -= OnMapMouseDoubleClick;
                base.MouseHover -= OnMapMouseHover;
                base.MouseEnter -= OnMouseEnter;
                base.MouseLeave -= OnMapMouseLeave;

                if (renderWorker != null)
                {
                    renderWorker.DoWork -= renderWorker_DoWork;
                    renderWorker.RunWorkerCompleted -= renderWorker_RunWorkerCompleted;
                }

                if (_csFact != null)
                {
                    _csFact.Dispose();
                    _csFact = null;
                }

                if (_resSvc != null)
                {
                    _resSvc.Dispose();
                    _resSvc = null;
                }

                if (_selection != null)
                {
                    _selection.Dispose();
                    _selection = null;
                }

                if (_mapCs != null)
                {
                    _mapCs.Dispose();
                    _mapCs = null;
                }

                if (_agfRW != null)
                {
                    _agfRW.Dispose();
                    _agfRW = null;
                }

                if (_wktRW != null)
                {
                    _wktRW.Dispose();
                    _wktRW = null;
                }

                if (_geomFact != null)
                {
                    _geomFact.Dispose();
                    _geomFact = null;
                }

                if (_mapMeasure != null)
                {
                    _mapMeasure.Dispose();
                    _mapMeasure = null;
                }
            }
            base.Dispose(disposing);
        }
コード例 #35
0
ファイル: AnalyzingFeatures.cs プロジェクト: kanbang/Colt
        private void btnFindFeaturesInBuffer_Click(object sender, EventArgs e)
        {
            MgSelectionBase selection = _viewer.GetSelection();
            MgReadOnlyLayerCollection selectedLayers = selection.GetLayers();
            if (selectedLayers == null)
            {
                MessageBox.Show("Select a parcel");
                return;
            }
            MgLayerBase parcels = null;
            for (int i = 0; i < selectedLayers.GetCount(); i++)
            {
                MgLayerBase layer = selectedLayers.GetItem(i);
                if (layer.Name == "Parcels")
                {
                    parcels = layer;
                    break;
                }
            }
            if (parcels == null)
            {
                MessageBox.Show("Select a parcel");
                return;
            }

            int bufferRingSize = 500; // measured in metres

            // Set up some objects for coordinate conversion

            MgMapBase map = _viewer.GetMap();
            MgLayerCollection mapLayers = map.GetLayers();
            MgMapViewerProvider provider = _viewer.GetProvider();
            MgResourceService resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService);
            //Casting to MgdFeatureService because we want to use convenience APIs
            MgFeatureService featureService = (MgdFeatureService)provider.CreateService(MgServiceType.FeatureService);
            string sessionId = Guid.NewGuid().ToString();

            String mapWktSrs = map.GetMapSRS();
            MgAgfReaderWriter agfReaderWriter = new MgAgfReaderWriter();
            MgWktReaderWriter wktReaderWriter = new MgWktReaderWriter();
            MgCoordinateSystemFactory coordinateSystemFactory = new MgCoordinateSystemFactory();
            MgCoordinateSystem srs = coordinateSystemFactory.Create(mapWktSrs);
            MgMeasure srsMeasure = srs.GetMeasure();

            // Check for a buffer layer. If it exists, delete
            // the current features.
            // If it does not exist, create a feature source and
            // a layer to hold the buffer.

            BufferHelper helper = new BufferHelper();
            MgdLayer bufferLayer = null;
            int layerIndex = map.GetLayers().IndexOf("Buffer");
            if (layerIndex < 0)
            {
                // The layer does not exist and must be created.

                MgResourceIdentifier bufferFeatureResId = new MgResourceIdentifier("Session:" + sessionId + "//Buffer.FeatureSource");
                helper.CreateBufferFeatureSource(featureService, mapWktSrs, bufferFeatureResId);
                bufferLayer = helper.CreateBufferLayer(resourceService, bufferFeatureResId, sessionId);
                map.GetLayers().Insert(0, bufferLayer);
            }
            else
            {
                bufferLayer = (MgdLayer)map.GetLayers().GetItem(layerIndex);
                bufferLayer.DeleteFeatures("ID like '%'");
            }

            // Check for a parcel marker layer. If it exists, delete
            // the current features.
            // If it does not exist, create a feature source and
            // a layer to hold the parcel markers.

            MgdLayer parcelMarkerLayer = null;
            layerIndex = map.GetLayers().IndexOf("ParcelMarker");
            if (layerIndex < 0)
            {
                MgResourceIdentifier parcelFeatureResId = new MgResourceIdentifier("Session:" + sessionId + "//ParcelMarker.FeatureSource");
                helper.CreateParcelMarkerFeatureSource(featureService, mapWktSrs, parcelFeatureResId);
                parcelMarkerLayer = helper.CreateParcelMarkerLayer(resourceService, parcelFeatureResId, sessionId);
                map.GetLayers().Insert(0, parcelMarkerLayer);
            }
            else
            {
                parcelMarkerLayer = (MgdLayer)map.GetLayers().GetItem(layerIndex);
                parcelMarkerLayer.DeleteFeatures("ID like '%'");
            }

            // Check each layer in the selection.

            for (int i = 0; i < selectedLayers.GetCount(); i++)
            {
                // Only check selected features in the Parcels layer.

                MgdLayer layer = (MgdLayer)selectedLayers.GetItem(i);

                if (layer.GetName() == "Parcels")
                {
                    string geomName = layer.GetFeatureGeometryName();
                    System.Diagnostics.Trace.TraceInformation("Marking all parcels inside the buffer that are of type 'MFG'");

                    MgFeatureReader featureReader = selection.GetSelectedFeatures(layer, layer.GetFeatureClassName(), false);


                    // Process each item in the MgFeatureReader. Get the
                    // geometries from all the selected features and
                    // merge them into a single geometry.

                    MgGeometryCollection inputGeometries = new MgGeometryCollection();
                    while (featureReader.ReadNext())
                    {
                        MgByteReader featureGeometryData = featureReader.GetGeometry(geomName);
                        MgGeometry featureGeometry = agfReaderWriter.Read(featureGeometryData);

                        inputGeometries.Add(featureGeometry);
                    }

                    MgGeometryFactory geometryFactory = new MgGeometryFactory();
                    MgGeometry mergedGeometries = geometryFactory.CreateMultiGeometry(inputGeometries);

                    // Create a buffer from the merged geometries

                    double bufferDist = srs.ConvertMetersToCoordinateSystemUnits(bufferRingSize);
                    MgGeometry bufferGeometry = mergedGeometries.Buffer(bufferDist, srsMeasure);

                    // Create a filter to select parcels within the buffer. Combine
                    // a basic filter and a spatial filter to select all parcels
                    // within the buffer that are of type "MFG".

                    MgFeatureQueryOptions queryOptions = new MgFeatureQueryOptions();
                    queryOptions.SetFilter("RTYPE = 'MFG'");
                    queryOptions.SetSpatialFilter(geomName, bufferGeometry, MgFeatureSpatialOperations.Inside);

                    featureReader = layer.SelectFeatures(queryOptions);

                    // Get the features from the feature source,
                    // determine the centroid of each selected feature, and
                    // add a point to the ParcelMarker layer to mark the
                    // centroid.
                    // Collect all the points into an MgFeatureCommandCollection,
                    // so they can all be added in one operation.

                    MgFeatureCommandCollection parcelMarkerCommands = new MgFeatureCommandCollection();
                    int inserted = 0;
                    while (featureReader.ReadNext())
                    {
                        MgByteReader byteReader = featureReader.GetGeometry(geomName);
                        MgGeometry geometry = agfReaderWriter.Read(byteReader);
                        MgPoint point = geometry.GetCentroid();

                        // Create an insert command for this parcel.
                        MgPropertyCollection properties = new MgPropertyCollection();
                        properties.Add(new MgGeometryProperty("ParcelLocation", agfReaderWriter.Write(point)));
                        //parcelMarkerCommands.Add(new MgInsertFeatures("ParcelMarkerClass", properties));
                        MgFeatureReader fr = parcelMarkerLayer.InsertFeatures(properties);
                        fr.Close();
                        inserted++;
                    }
                    featureReader.Close();

                    if (inserted == 0)
                    {
                        MessageBox.Show("No parcels within the buffer area match.");
                        return;
                    }

                    // Create a feature in the buffer feature source to show the area covered by the buffer.

                    MgPropertyCollection props = new MgPropertyCollection();
                    props.Add(new MgGeometryProperty("BufferGeometry", agfReaderWriter.Write(bufferGeometry)));
                    bufferLayer.InsertFeatures(props);

                    // Ensure that the buffer layer is visible and in the legend.

                    bufferLayer.SetVisible(true);
                    bufferLayer.ForceRefresh();
                    bufferLayer.SetDisplayInLegend(true);
                    parcelMarkerLayer.SetVisible(true);
                    parcelMarkerLayer.ForceRefresh();

                    MessageBox.Show("Done");
                    _viewer.RefreshMap();
                    IMapLegend legend = Shell.Instance.Legend;
                    if (legend != null)
                        legend.RefreshLegend();
                }
            }
        }
コード例 #36
0
ファイル: MarkupEditor.cs プロジェクト: ranyaof/Meuhedet
        public MgCoordinateSystemTransform GetTransform()
        {
            MgCoordinateSystemFactory coordSysFactory = new MgCoordinateSystemFactory();
            _resourceService = (MgResourceService)this.site.CreateService(MgServiceType.ResourceService);

            MgMap map = new MgMap();
            map.Open(_resourceService, GetParameter(this.args, "MAPNAME"));

            MgCoordinateSystem source = coordSysFactory.Create(map.GetMapSRS());
            //MgCoordinateSystem target = coordSysFactory.Create(MarkupManager.LL84WKT);
            MgCoordinateSystem target = coordSysFactory.Create(map.GetMapSRS());

            return coordSysFactory.GetTransform(source, target);
        }
コード例 #37
0
 public LocalNativeCoordinateSystemCatalog()
 {
     m_cf = new MgCoordinateSystemFactory();
 }
コード例 #38
0
ファイル: MainForm.cs プロジェクト: kanbang/Colt
 public MainForm(MgCoordinateSystemFactory fact)
     : this()
 {
     _fact = fact;
 }