예제 #1
0
        private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
        {
            checkedListBox1.Items.Clear();
            comboBox2.Items.Clear();
            IMapDocument mdoc = new MapDocumentClass();

            mdoc.Open(textBox1.Text, "");

            for (int i = 0; i < comboBox1.Items.Count; i++)
            {
                if (mdoc.get_Map(i).Name == comboBox1.SelectedItem.ToString())
                {
                    map = mdoc.get_Map(i);
                    axMapControl1.Map = map;
                    axMapControl1.Refresh();

                    IEnumLayer allLayers = map.get_Layers();
                    ILayer     layer     = allLayers.Next();//chosen layer
                    while (layer != null)
                    {
                        checkedListBox1.Items.Add(layer.Name); //to choose layer
                        comboBox2.Items.Add(layer.Name);       //to remove layer or definition query
                        layer = allLayers.Next();
                    }
                }
                //check true for all layers
                for (int d = 0; d < checkedListBox1.Items.Count; d++)
                {
                    checkedListBox1.SetItemChecked(d, true);
                }
            }
        }
        /// <summary>
        /// Occurs when this command is clicked
        /// </summary>
        public override void OnClick()
        {
            // TODO: Add OpenNewMapDocument.OnClick implementation
            //launch a new OpenFile dialog
            System.Windows.Forms.OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter      = "Map Documents (*.mxd)|*.mxd";
            dlg.Multiselect = false;
            dlg.Title       = "Open Map Document";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                string       docName = dlg.FileName;
                IMapDocument pMapDoc = new MapDocumentClass();
                if (pMapDoc.get_IsPresent(docName) && !pMapDoc.get_IsPasswordProtected(docName))
                {
                    // 以下3.3.3.1代码

                    /* pMapControl.LoadMxFile(dlg.FileName, null, null);
                     * pMapControl.ActiveView.Refresh();
                     * pMapDoc.Close();                     */
                    // 以下3.3.3.5代码
                    pMapDoc.Open(docName, string.Empty);
                    IMap map = pMapDoc.get_Map(0);
                    pMapDoc.SetActiveView((IActiveView)map);
                    pControlsSynchronizer.PageLayoutControl.PageLayout = pMapDoc.PageLayout;
                    pControlsSynchronizer.ReplaceMap(map);
                    pMapDoc.Close();
                }
            }
        }
예제 #3
0
        /// <summary>
        /// Occurs when this command is clicked
        /// </summary>
        public override void OnClick()
        {
            //launch a new OpenFile dialog
            OpenFileDialog dlg = new OpenFileDialog();

            dlg.Filter      = "Map Documents (*.mxd)|*.mxd";
            dlg.Multiselect = false;
            dlg.Title       = "Open Map Document";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                string docName = dlg.FileName;

                IMapDocument mapDoc = new MapDocumentClass();
                if (mapDoc.get_IsPresent(docName) && !mapDoc.get_IsPasswordProtected(docName))
                {
                    mapDoc.Open(docName, string.Empty);

                    // set the first map as the active view
                    IMap map = mapDoc.get_Map(0);
                    mapDoc.SetActiveView((IActiveView)map);

                    m_controlsSynchronizer.PageLayoutControl.PageLayout = mapDoc.PageLayout;

                    m_controlsSynchronizer.ReplaceMap(map);

                    mapDoc.Close();

                    m_sDocumentPath = docName;
                }
            }
        }
 private void btnWebMap_Click(object sender, EventArgs e)
 {
     if (!(IsConnected()))
     {
         // Since Web Maps require and internet connection anyways
         // just fail if there isn't one.
         MessageBox.Show("Cannot Connect to ArcGIS.com!", "Failed to open Web Map.", MessageBoxButtons.OK, MessageBoxIcon.Error);
         return;
     }
     try
     {
         IMapDocument mapDocument = new MapDocumentClass();
         string       webMapMxd   = webMapLocation + @"\" + myWebMapName + @"\" + myWebMapName + ".mxd";
         if (File.Exists(webMapMxd))
         {
             mapDocument.Open(webMapMxd, "");
         }
         else
         {
             mapDocument.Open(txtWebMap.Text, "");
         }
         axMapControl1.Map = mapDocument.get_Map(0);
     }
     catch (Exception ex)
     {
         MessageBox.Show("Failed to open Web Map!", ex.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
        /// <summary>
        /// Occurs when this command is clicked
        /// </summary>
        public override void OnClick()
        {
            // TODO: Add OpenDocument.OnClick implementation
            OpenFileDialog dlg = new OpenFileDialog();

            dlg.Title  = "选择地图文档";
            dlg.Filter = "地图文档(*.mxd)|*.mxd";
            string docName = null;

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                docName = dlg.FileName;
                IMapDocument mapDoc = new MapDocumentClass();
                if (mapDoc.get_IsMapDocument(docName))
                {
                    mapDoc.Open(docName, string.Empty);
                    IMap map = mapDoc.get_Map(0);
                    m_ControlsSynchronizer.ReplaceMap(map);
                    mapDoc.Close();

                    RecnetFilesList.Add(docName);
                }
                else
                {
                    MessageBox.Show("不可用的地图文档", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    RecnetFilesList.Remove(docName);
                }
            }
        }
예제 #6
0
        /// <summary>
        /// 工程另存为
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void iSaveProjectAs_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //ESRI.ArcGIS.SystemUI.ICommand saveCommand = new ControlsSaveAsDocCommand();
            //saveCommand.OnCreate(m_mapControl.Object);
            //saveCommand.OnClick();

            IMapDocument   pMapDocument = new MapDocumentClass();
            SaveFileDialog opensavemxd  = new SaveFileDialog();

            opensavemxd.Filter = "地图文档(*.mxd)|*.mxd"; //对话框的过滤器
            if (opensavemxd.ShowDialog() == DialogResult.OK)
            {
                string filePath = opensavemxd.FileName; //获取文件全路径
                pMapDocument.New(filePath);
                IMxdContents pMxdC = m_mapControl.Map as IMxdContents;
                pMapDocument.ReplaceContents(pMxdC);
                pMapDocument.Save(true, false);
                m_mapControl.LoadMxFile(filePath, 0, Type.Missing);
                //循环遍历所有的地图
                for (int i = 0; i < pMapDocument.MapCount; i++)
                {
                    m_mapControl.Map = pMapDocument.get_Map(i); //绑定地图控件
                }
                pMapDocument.Close();
            }
        }
예제 #7
0
        /// <summary>
        /// Opens mxd document.
        /// </summary>
        /// <param name="sMxdFilePath">The  MXD file path.</param>
        public static void OpenDocument(string sMxdFilePath)
        {
            IMapDocument mapDocument = new MapDocumentClass();

            if (mapDocument.get_IsPresent(sMxdFilePath) && !mapDocument.get_IsPasswordProtected(sMxdFilePath))
            {
                mapDocument.Open(sMxdFilePath, "");
                try
                {
                    IMap map = mapDocument.get_Map(0);
                    mapDocument.SetActiveView((IActiveView)map);
                    //EnviVars.instance.Synchronizer.PageLayoutControl.PageLayout = mapDocument.PageLayout;
                    //EnviVars.instance.Synchronizer.ReplaceMap(map);
                    EnviVars.instance.MapControl.Map = map;
                    EnviVars.instance.MainForm.Text  = sMxdFilePath;
                }
                catch (Exception ex)
                {
                    //_logger.Log(LogLevel.Error, EventType.UserManagement, null, ex);
                    Log.WriteLog(typeof(MapAPI), ex);
                }
                finally
                {
                    mapDocument.Close();
                }
            }
        }
예제 #8
0
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Save_Click(object sender, EventArgs e)
        {
            try
            {
                //空白文档不保存
                if (String.IsNullOrEmpty(m_mapControl.DocumentFilename))
                {
                    return;
                }

                //创建地图文档,调用open方法,调用ReplaceContents方法
                IMapDocument mapDocument = new MapDocumentClass();
                mapDocument.Open(m_mapControl.DocumentFilename);
                mapDocument.ReplaceContents(m_mapControl as IMxdContents);

                IObjectCopy objCopy = new ObjectCopyClass(); //使用Copy,避免共享引用
                m_mapControl.Map = (IMap)objCopy.Copy(mapDocument.get_Map(0));
                objCopy          = null;

                mapDocument.Save(mapDocument.UsesRelativePaths, false);
                mapDocument.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("请联系管理员,错误原因是:" + ex.Message);
            }
        }
예제 #9
0
        /// <summary>
        /// 打开本地地图
        /// </summary>
        /// <param name="mapFileName"></param>
        /// <returns></returns>
        public static IMap OpenMap(string mapFileName)
        {
            IMapDocument mapDoc = new MapDocumentClass();

            mapDoc.Open(mapFileName, "");
            return(mapDoc.get_Map(0));
        }
예제 #10
0
        /// <summary>
        /// 运用MapDocument对象中的Open方法的函数加载mxd文档
        /// </summary>
        private void loadMapDoc2()
        {
            IMapDocument mapDocument = new MapDocumentClass();

            try
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Title  = "打开地图文档";
                ofd.Filter = "map documents(*.mxd)|*.mxd";
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    string pFileName = ofd.FileName;
                    //filePath——地图文档的路径, ""——赋予默认密码
                    mapDocument.Open(pFileName, "");
                    for (int i = 0; i < mapDocument.MapCount; i++)
                    {
                        //通过get_Map(i)方法逐个加载
                        axMapControl1.Map = mapDocument.get_Map(i);
                    }
                    axMapControl1.Refresh();
                }
                else
                {
                    mapDocument = null;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
예제 #11
0
        public static void CreateNewMapDocument()
        {
            IMapDocument pMapDocument   = new MapDocumentClass();
            string       sDefaultMxFile = @"D:\untitled.mxd"; pMapDocument.New(sDefaultMxFile);

            pMapDocument.Open(sDefaultMxFile);
            Form1.form1.axMapControl1.Map      = pMapDocument.get_Map(0);
            Form1.form1.axMapControl1.Map.Name = "Map";
            Form1.form1.axTOCControl1.Update();
        }
        /// <summary>
        /// Occurs when this command is clicked
        /// </summary>
        public void OnClickAutomatic(string docName)
        {
            IMapDocument mapDoc = new MapDocumentClass();

            if (mapDoc.get_IsPresent(docName) && !mapDoc.get_IsPasswordProtected(docName))
            {
                mapDoc.Open(docName, string.Empty);
                IMap map = mapDoc.get_Map(0);
                m_controlsSynchronizer.ReplaceMap(map);
                mapDoc.Close();
            }
        }
예제 #13
0
        /// <summary>
        /// Occurs when this command is clicked
        /// </summary>
        public void OnClickAutomatic(string docName)
        {
            IMapDocument mapDoc = new MapDocumentClass();

            if (mapDoc.get_IsPresent(docName) && !mapDoc.get_IsPasswordProtected(docName))
            {
                mapDoc.Open(docName, string.Empty);
                IMap map = mapDoc.get_Map(0);
                m_controlsSynchronizer.ReplaceMap(map);
                mapDoc.Close();
            }


            //"C:\\Study\\Data\\Morphing Data\\Administrative Boundary\\Hunan\\Hunan.mxd"
        }
예제 #14
0
        /// <summary>
        /// Generates the report.
        /// </summary>
        public void GenerateReport()
        {
            this.ReportFileStream = new StreamWriter(this.ReportFilePath, true);

            Console.WriteLine("Report Path=" + this.ReportFilePath);

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            FileInfo mxdfileinfo = new FileInfo(this.MXDFilePath);

            try
            {
                IMapDocument mapDocument = new MapDocumentClass();
                mapDocument.Open(this.MXDFilePath, string.Empty);

                for (int m = 0; m < mapDocument.MapCount; m++)
                {
                    IMap map = mapDocument.get_Map(m);

                    IMapLayers mapLayers = (IMapLayers)map;

                    IEnumLayer rootLayers = (IEnumLayer)map.get_Layers(null, false);

                    ILayer rootLayer = null;

                    while ((rootLayer = rootLayers.Next()) != null)
                    {
                        ReadLayer(rootLayer, null);
                    }
                }

                // mapDocument.Save(mapDocument.UsesRelativePaths, false);
                mapDocument.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            this.ReportFileStream.Close();

            Console.WriteLine("Report File Stream Closed: " + this.ReportFilePath);
        }
예제 #15
0
        private void newMxdFile_Click(object sender, EventArgs e)
        {
            MapDocument    pMapDocument = new MapDocumentClass();
            SaveFileDialog opfd         = new SaveFileDialog();

            opfd.Title  = "新建Mxd文件";
            opfd.Filter = "MapDocuments(*.mxd|*.mxd";
            opfd.ShowDialog();
            string sFilePath = opfd.FileName;

            //   MessageBox.Show("Go Here!  sFilePath=  " + sFilePath, "yahooo");
            if (sFilePath != "")  //如果不判断,不想创建退出时会异常
            {
                pMapDocument.New(sFilePath);
                pMapDocument.Open(sFilePath, "");
                mainMapControl.Map = pMapDocument.get_Map(0);
            }
        }
예제 #16
0
파일: BaseFuncs.cs 프로젝트: hehao1999/GIS
        public static void NewMapDoc(Control.ControlCollection controls, ESRI.ArcGIS.Controls.AxMapControl mainMapControl)
        {
            try
            {
                //实例化AxMapControl控件,并加入Form的Controls
                ESRI.ArcGIS.Controls.AxMapControl axMapControl = new ESRI.ArcGIS.Controls.AxMapControl();
                ((System.ComponentModel.ISupportInitialize)(axMapControl)).BeginInit();
                controls.Add(axMapControl);
                ((System.ComponentModel.ISupportInitialize)(axMapControl)).EndInit();

                //实例化SaveFileDialog控件
                SaveFileDialog pSaveFileDialog = new SaveFileDialog();
                pSaveFileDialog.Title            = "输入需要新建地图文档的名称";
                pSaveFileDialog.Filter           = "地图文件(*.mxd)|*.mxd";
                pSaveFileDialog.OverwritePrompt  = true;
                pSaveFileDialog.RestoreDirectory = true;

                if (pSaveFileDialog.ShowDialog() == DialogResult.OK)
                {//保存地图文档
                    string       filename     = pSaveFileDialog.FileName;
                    IMapDocument pMapDocument = new MapDocumentClass();
                    pMapDocument.New(filename);
                    axMapControl.Map = pMapDocument.get_Map(0);
                    axMapControl.DocumentFilename = pMapDocument.DocumentFilename;
                    pMapDocument.Close();
                    mainMapControl.LoadMxFile(filename);
                    mainMapControl.Refresh();
                    MessageBox.Show("新建地图文档成功!", "信息提示", MessageBoxButtons.OK);
                    return;
                }
                else
                {
                    return;
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show("新建地图文档失败!" + exc.Message, "信息提示", MessageBoxButtons.OK);
                return;
            }
        }
예제 #17
0
 /// <summary>
 /// 保存工程
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void iSaveProject_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
 {
     //判断当前是否存在mxd文件,若存在则执行保存,否则执行另存为。
     if (m_mapControl.DocumentFilename != null)
     {
         IMxdContents pMxdC        = m_mapControl.Map as IMxdContents;
         IMapDocument pMapDocument = new MapDocumentClass();
         pMapDocument.Open(m_mapControl.DocumentFilename, "");
         IActiveView pActiveView = m_mapControl.Map as IActiveView;
         pMapDocument.ReplaceContents(pMxdC);
         IObjectCopy lip_ObjCopy = new ObjectCopyClass(); //使用Copy,避免共享引用
         m_mapControl.Map = (IMap)lip_ObjCopy.Copy(pMapDocument.Map[0]);
         lip_ObjCopy      = null;
         pMapDocument.Save(true, false);
         pMapDocument.Close();
         MessageBox.Show("保存成功");
     }
     else
     {
         IMapDocument   pMapDocument = new MapDocumentClass();
         SaveFileDialog opensavemxd  = new SaveFileDialog();
         opensavemxd.Filter = "地图文档(*.mxd)|*.mxd"; //对话框的过滤器
         if (opensavemxd.ShowDialog() == DialogResult.OK)
         {
             string filePath = opensavemxd.FileName; //获取文件全路径
             pMapDocument.New(filePath);
             IMxdContents pMxdC = m_mapControl.Map as IMxdContents;
             pMapDocument.ReplaceContents(pMxdC);
             pMapDocument.Save(true, false);
             m_mapControl.LoadMxFile(filePath, 0, Type.Missing);
             //循环遍历所有的地图
             for (int i = 0; i < pMapDocument.MapCount; i++)
             {
                 m_mapControl.Map = pMapDocument.get_Map(i); //绑定地图控件
             }
             m_mapControl.Map.Name = "Layers";
             m_tocControl.SetBuddyControl(m_mapControl.Object);
             pMapDocument.Close();
         }
     }
 }
        public void OnClick_RecentFileMenuItem(string docName)
        {
            // TODO: Add OpenDocument.OnClick implementation

            IMapDocument mapDoc = new MapDocumentClass();

            if (mapDoc.get_IsMapDocument(docName))
            {
                mapDoc.Open(docName, string.Empty);
                IMap map = mapDoc.get_Map(0);
                m_ControlsSynchronizer.ReplaceMap(map);
                mapDoc.Close();

                RecnetFilesList.Add(docName);
            }
            else
            {
                MessageBox.Show("不可用的地图文档", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                RecnetFilesList.Remove(docName);
            }
        }
        /// <summary>
        /// Occurs when this command is clicked
        /// </summary>
        public override void OnClick()
        {
            // TODO: Add OpenNewMapDocument.OnClick implementation
            OpenFileDialog dlg = new OpenFileDialog();

            dlg.Filter      = "Map Documents (*.mxd)|*.mxd";
            dlg.Multiselect = false;
            dlg.Title       = "Open Map Document";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                string       docName = dlg.FileName;
                IMapDocument mapDoc  = new MapDocumentClass();
                if (mapDoc.get_IsPresent(docName) && !mapDoc.get_IsPasswordProtected(docName))
                {
                    mapDoc.Open(docName, string.Empty);
                    IMap map = mapDoc.get_Map(0);
                    m_controlsSynchronizer.ReplaceMap(map);
                    mapDoc.Close();
                }
            }
        }
예제 #20
0
        //新建
        public static void NewDoc(AxMapControl mapControl, AxPageLayoutControl pageLayoutControl = null)
        {
            SaveFileDialog NewDlg = new SaveFileDialog();

            NewDlg.Title            = "新建文档";
            NewDlg.InitialDirectory = "C:\\Users\\Administrator\\Desktop";
            NewDlg.FileName         = "Default";
            NewDlg.Filter           = "mxd文件|*.mxd";
            if (NewDlg.ShowDialog() == DialogResult.OK)
            {
                if (MessageBox.Show("        是否保存当前文档?", "信息提示", MessageBoxButtons.YesNo) == DialogResult.OK)
                {
                    OperateFile.SaveDoc(mapControl);
                }
                IMapDocument pMapDocument = new MapDocumentClass();

                pMapDocument.New(NewDlg.FileName);
                pMapDocument.Open(NewDlg.FileName);
                mapControl.Map = pMapDocument.get_Map(0);
            }
        }
예제 #21
0
        /// <summary>
        /// 打开Mxd文档的方法
        /// </summary>
        private void OpenMxd()
        {
            try
            {
                IMapDocument pMapDocument = new MapDocumentClass();

                string filePath = Global.MxdPath;

                pMapDocument.Open(filePath, "");

                IMap pMap = pMapDocument.get_Map(0);
                //arcgis10若使用GDB保存mxd文件的图层要素类,在图层对应的要素类路径使用相对路径存放,无需再重新赋值
                Global.pOriginalMap = pMap;

                axMapControl1.Map = pMap;
                axMapControl1.Refresh();
                axTOCControl1.SetBuddyControl(axMapControl1.Object);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
 private void btnLoadmpk_Click(object sender, EventArgs e)
 {
     try
     {
         IMapDocument mapDocument = new MapDocumentClass();
         if (IsConnected())
         {
             mapDocument.Open(txtMapPackage.Text, "");
         }
         else
         {
             if (DoesPackageExist(PackageType.MapPackage))
             {
                 mapDocument.Open(packageLocation, "");
             }
         }
         axMapControl1.Map = mapDocument.get_Map(0);
     }
     catch (Exception ex)
     {
         MessageBox.Show("Failed to open Map Package!", ex.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
예제 #23
0
        /// <summary>
        /// 作用:MapControl加载mxd文件
        /// 作者:汪建龙
        /// 编写时间:2016年12月26日09:49:25
        /// </summary>
        /// <param name="mapControl"></param>
        /// <param name="mxdFile"></param>
        public static void Load(this IMapControl2 mapControl, string mxdFile)
        {
            try
            {
                if (System.IO.File.Exists(mxdFile) == false)
                {
                    return;
                }

                IMapDocument mapDocument = new MapDocumentClass();
                if (!mapDocument.get_IsPresent(mxdFile) ||
                    !mapDocument.get_IsMapDocument(mxdFile) ||
                    mapDocument.get_IsPasswordProtected(mxdFile) ||
                    mapDocument.get_IsRestricted(mxdFile))
                {
                    string message = string.Format("路径:\"{0}\"下的地图文档不正确,请拷贝文件到该路径下。", mxdFile);
                    System.Diagnostics.Trace.WriteLine(message);
                }
                else
                {
                    mapDocument.Open(mxdFile, null);
                    if (mapDocument.DocumentVersion == esriMapDocumentVersionInfo.esriMapDocumentVersionInfoFail)
                    {
                        string message = string.Format("路径:\"{0}\"下的地图文档版本不正确,请拷贝该文件到该路径下。", mxdFile);
                        System.Diagnostics.Trace.WriteLine(message);
                    }
                    else if (mapDocument.MapCount > 0)
                    {
                        IMap map = mapDocument.get_Map(0);
                        mapControl.Map = map;
                    }
                }
            }catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex);
            }
        }
예제 #24
0
        public static void Execute(object threadData)
        {
            UTFGridGeneratorConfig config = threadData as UTFGridGeneratorConfig;

            try {
                config.WorkerStart();
                IMap map = null;
                try {
                    IMapDocument mapDocument = new MapDocumentClass();
                    mapDocument.Open(config.MapPath, null);
                    map = mapDocument.ActiveView as IMap;
                    if (map == null)
                    {
                        map = mapDocument.get_Map(0);
                    }
                    mapDocument.Close();
                } catch (Exception) { }
                if (map == null)
                {
                    throw new Exception("Unable to open map at " + config.MapPath);
                }
                if ((map.SpatialReference.FactoryCode != 102113) &&
                    (map.SpatialReference.FactoryCode != 102100) &&
                    (map.SpatialReference.FactoryCode != 3785))
                {
                    throw new Exception("Spatial reference of map must be Web Mercator (is " + map.SpatialReference.FactoryCode + ")");
                }

                while (true)
                {
                    TileDescription tile = config.NextTile();
                    if (tile == null)
                    {
                        return;
                    }
                    string folder = String.Format("{0}\\{1}\\{2}", config.Destination, tile.Level, tile.Col);
                    if (!Directory.Exists(folder))
                    {
                        Directory.CreateDirectory(folder);
                    }
                    string file = String.Format("{0}\\{1}.grid.json", folder, tile.Row);
                    if (config.GZip)
                    {
                        file += ".gz";
                    }
                    if ((!File.Exists(file)) || config.Overwrite)
                    {
                        if (config.Verbose)
                        {
                            Console.WriteLine(Thread.CurrentThread.Name + " generating tile " + tile.Level + ", " + tile.Row + ", " + tile.Col);
                        }
                        Dictionary <string, object> data = CollectData(map, tile.Extent, config.Fields);
                        if (data != null)
                        {
                            if (config.Verbose)
                            {
                                Console.WriteLine(Thread.CurrentThread.Name + " saving to " + file);
                            }
                            Stream fOut = new System.IO.FileStream(file, FileMode.Create);
                            if (config.GZip)
                            {
                                fOut = new GZipStream(fOut, CompressionMode.Compress, CompressionLevel.BestCompression);
                            }
                            using (fOut) {
                                string   json        = JsonConvert.SerializeObject(data, Formatting.Indented);
                                Encoding utf8        = new UTF8Encoding(false, true);
                                byte[]   encodedJson = utf8.GetBytes(json);
                                fOut.Write(encodedJson, 0, encodedJson.Length);
                            }
                        }
                    }
                }
            } finally {
                config.WorkerEnd();
            }
        }
 private void Form1_Load(object sender, EventArgs e)
 {
     IMapDocument imapDocument = new MapDocumentClass();
     imapDocument.Open(@"C:\Users\huty\Desktop\武汉实习数据\wuhan.mxd", "");
     for (int i = 0; i <= imapDocument.MapCount - 1; i++)
     {
         axMapControl1.Map = imapDocument.get_Map(i);//axMapControl1为MapControl的自动对象
     }
     IGraphicsContainer pgraghicscontainer = axMapControl1.Map as IGraphicsContainer;
     IActiveView pactiveview = pgraghicscontainer as IActiveView;
     axMapControl1.Extent = pactiveview.FullExtent;
     pactiveview.Refresh();
     axMapControl2.AddLayer(mainroadlayer);
     axMapControl2.AddLayer(secondroadlayer);
     axMapControl2.AddLayer(waterregionlayer);
     double scale = axMapControl1.ActiveView.FocusMap.MapScale;
     string a = scale.ToString("#0.00");
     this.scaletextbox.Text = "1:" + a;
     clsload();
     this.select.Checked = true;
 }
예제 #26
0
파일: Task.cs 프로젝트: hy1314200/HyDM
        /// <summary>
        /// 生成MXD,并将数据库重置
        /// </summary>
        /// <returns></returns>
        public bool CreateMXD()
        {
            try
            {
                string strMxdFile = GetMXDFile();
                File.Copy(System.Windows.Forms.Application.StartupPath + "\\" + COMMONCONST.RelativePath_MXD +"\\"+ this.StandardName + ".MXD", strMxdFile);
                IMapDocument mapDoc = new MapDocumentClass();
                mapDoc.Open(strMxdFile, null);

                // 重定向数据库
                IMap mapTarget = mapDoc.get_Map(0);
                Hy.Common.Utility.Esri.AEAccessFactory.ResetMapWorkspace(this.BaseWorkspace, mapTarget);
                // 修改空间参考及范围
                IEnumDataset enDataset = this.BaseWorkspace.get_Datasets(esriDatasetType.esriDTAny);
                IDataset dataset = enDataset.Next();
                double xMin=double.MaxValue, xMax=double.MinValue, yMin=double.MaxValue, yMax=double.MinValue;
                IEnvelope envExtent = null;
                ISpatialReference spatialRef = null;
                while (dataset != null)
                {
                    IGeoDataset geoDataset = dataset as IGeoDataset;
                    if (geoDataset != null)
                    {
                        //mapTarget.SpatialReference = geoDataset.SpatialReference;
                        //mapDoc.ActiveView.Extent.SpatialReference = geoDataset.SpatialReference;
                        //mapDoc.ActiveView.Extent = geoDataset.Extent;
                        //mapDoc.ActiveView.FullExtent.SpatialReference = geoDataset.SpatialReference;
                        //mapDoc.ActiveView.FullExtent = geoDataset.Extent;

                        spatialRef = geoDataset.SpatialReference;
                        envExtent = geoDataset.Extent;
                        if (!envExtent.IsEmpty)
                        {

                            if (xMin > envExtent.XMin) xMin = envExtent.XMin;
                            if (yMin > envExtent.YMin) yMin = envExtent.YMin;
                            if (xMax < envExtent.XMax) xMax = envExtent.XMax;
                            if (yMax < envExtent.YMax) yMax = envExtent.YMax;
                        }
                        //break;
                    }
                    dataset = enDataset.Next();
                }
                mapTarget.SpatialReference = spatialRef;
                envExtent.PutCoords(xMin, yMin, xMax, yMax);
                //mapTarget.RecalcFullExtent();
                mapDoc.ActiveView.Extent = envExtent;
                mapDoc.ActiveView.FullExtent = envExtent;
                (mapTarget as IActiveView).FullExtent = envExtent;

                mapDoc.Save(true, false);
                mapDoc.Close();

                // 再复制 “任务执行格式验证.xsd”文件
                File.Copy(System.Windows.Forms.Application.StartupPath + "\\" + COMMONCONST.RelativePath_MXD + "\\" + COMMONCONST.File_Name_XSD, GetTaskFolder() + "\\" + COMMONCONST.File_Name_XSD);
                return true;
            }
            catch (Exception exp)
            {
                SendMessage(enumMessageType.Exception, "生成MXD失败,错误信息:" + exp.Message);
                return false;
            }
        }
예제 #27
0
        public void ChangelayoutAndSave(string mxdPath, string templatePath, string savePath)
        {
            //   IMapDocument pDoc = new MapDocumentClass();
            IMxdContents pMxdC;
            IMapDocument pMapDocument = new MapDocumentClass();

            pMapDocument.Open(mxdPath, "");
            pMxdC = pMapDocument.PageLayout as IMxdContents;

            IMap        pMap        = pMxdC.ActiveView.FocusMap; //this.axPageLayoutControl1.ActiveView.FocusMap;
            IPageLayout pPageLayout = pMxdC.PageLayout;          //this.axPageLayoutControl1.PageLayout;
            //读取新模板
            IMapDocument pNewDoc = new MapDocumentClass();

            pNewDoc.Open(templatePath, "");
            IMap        pTempMap;
            IPageLayout pTempPagelayout = pNewDoc.PageLayout;

            pTempMap = pNewDoc.get_Map(0);
            IPage pTempPage = pTempPagelayout.Page;

            IPage pCurPage = pPageLayout.Page;

            //替换单位
            pCurPage.Units = pTempPage.Units;
            //exchange page orientation
            pCurPage.Orientation = pTempPage.Orientation;
            //替换页面尺寸
            Double dWidth  = 0;
            Double dHeight = 0;

            pTempPage.QuerySize(out dWidth, out dHeight);
            pCurPage.PutCustomSize(dWidth, dHeight);

            //删除当前Layout中除了mapframe外的所有elements
            IGraphicsContainer pGraphicsCont;
            IElement           pElement;

            pGraphicsCont = pPageLayout as IGraphicsContainer;
            pGraphicsCont.Reset();
            pElement = pGraphicsCont.Next();
            IMapFrame pMapFrame        = null;
            IElement  pMapFrameElement = null;

            while (pElement != null)
            {
                if (pElement is IMapFrame)
                {
                    // Console.WriteLine(pElement.Geometry.GeometryType.ToString() + '0');
                    pMapFrameElement = pElement;
                    pMapFrame        = pElement as IMapFrame;
                    pMapFrame.Border = null;
                }
                else
                {
                    pGraphicsCont.DeleteElement(pElement);
                    pGraphicsCont.Reset();
                }
                pElement = pGraphicsCont.Next();
            }

            //遍历模板的PageLayout中的所有元素,并且替换当前PageLayout中的所有元素
            IGraphicsContainer pTempGraphicsCont;

            pTempGraphicsCont = pTempPagelayout as IGraphicsContainer;
            pTempGraphicsCont.Reset();
            pElement = pTempGraphicsCont.Next();
            IArray pArray;

            pArray = new ESRI.ArcGIS.esriSystem.Array();
            while (pElement != null)
            {
                if (pElement is IMapFrame)
                {
                    pMapFrameElement.Geometry = pElement.Geometry;
                }
                else
                {
                    if (pElement is IMapSurroundFrame)
                    {
                        IMapSurround      pTempMapSurround;
                        IMapSurroundFrame pTempMapSurroundFrame = pElement as IMapSurroundFrame;
                        pTempMapSurroundFrame.MapFrame = pMapFrame;
                        pTempMapSurround = pTempMapSurroundFrame.MapSurround;
                        pMap.AddMapSurround(pTempMapSurround);
                    }

                    pArray.Add(pElement);
                }
                pElement = pTempGraphicsCont.Next();
            }

            int pElementCount = pArray.Count;

            //将模板PageLayout中的其它元素(除了MapFrameElement和MapSurroundFrame外的元素)添加到当前PageLayout中去
            for (int i = 0; i < pElementCount; i++)
            {
                pGraphicsCont.AddElement(pArray.get_Element(pElementCount - 1 - i) as IElement, 0);

                // this.axPageLayoutControl1.ActiveView.Refresh();
            }
            //     pMxdC.ActiveView.Refresh();
            pNewDoc.Close();
            pMapDocument = new MapDocumentClass();
            pMapDocument.New(savePath);
            // IActiveView pActiveView = this.axPageLayoutControl1.ActiveView.FocusMap as IActiveView;
            pMapDocument.ReplaceContents(pMxdC);
            pMapDocument.Save(true, true);
            pMapDocument.Close();
        }
예제 #28
0
        public bool Export(ExportMapInfo info, out string outmsg)
        {
            bool result   = false;
            bool hasright = true;

            outmsg = string.Empty;
            //hasright = InitialApp(out outmsg);
            if (hasright)
            {
                #region 地图元素参数设定

                PageSize        currentPageSize = PageSize.A4;
                PageOrientation currentPageOri  = PageOrientation.Portrait;
                currentPageSize = (PageSize)int.Parse(info.PageSize);
                currentPageOri  = (PageOrientation)int.Parse(info.PageOri);

                double   left = 0, bottom = 0, right = 0, top = 0;
                double   outlineoffset = 0;
                string[] margins       = info.PageMargin.Split(',');
                if (margins.Length == 4)
                {
                    left   = double.Parse(margins[0]) + outlineoffset;
                    bottom = double.Parse(margins[3]) + outlineoffset;
                    top    = double.Parse(margins[1]) + outlineoffset;
                    right  = double.Parse(margins[2]) + outlineoffset;
                }

                #endregion

                #region 根据mxd获取相关信息。

                /// <summary>
                /// mxd文档
                /// </summary>
                IMapDocument pMapDocument;

                IMapFrame pPageMapFrame;
                /// <summary>
                /// 制图接口
                /// </summary>
                IPageLayout pPageLayout;
                /// <summary>
                /// 页面
                /// </summary>
                IPage pPage;
                /// <summary>
                /// 当前地图
                /// </summary>
                IMap pMap;
                /// <summary>
                /// 当前数据窗口
                /// </summary>
                IActiveView pDataAV;
                /// <summary>
                /// 当前制图窗口
                /// </summary>
                IActiveView              pPageAV;
                IGraphicsContainer       pGraphicsContainer;
                IGraphicsContainerSelect pGrapSel;
                IExport         docExport;
                IPrintAndExport docPrintExport;

                pMapDocument = new MapDocumentClass();
                info.MxdPath = printPath + "\\Mxds\\";
                string mxdfile = info.MxdPath + (info.TemplateName.ToUpper().EndsWith(".MXD") ? info.TemplateName : info.TemplateName + ".mxd");
                if (File.Exists(mxdfile))
                {
                    pMapDocument.Open(mxdfile, "");
                    pPageLayout        = pMapDocument.PageLayout;
                    pPage              = pPageLayout.Page;
                    pPageAV            = pPageLayout as IActiveView;
                    pDataAV            = pPageAV.FocusMap as IActiveView;
                    pMap               = pPageAV.FocusMap;
                    pGraphicsContainer = pPageLayout as IGraphicsContainer;
                    pPageMapFrame      = pGraphicsContainer.FindFrame(pPageAV.FocusMap) as IMapFrame;

                    pGrapSel = pMapDocument.ActiveView as IGraphicsContainerSelect;

                    docExport      = new ExportPDFClass();
                    docPrintExport = new PrintAndExportClass();

                    try
                    {
                        //处理所见所得
                        if (mxdfile.ToUpper().EndsWith("TEMP.MXD"))
                        {
                            ////处理坐标系
                            //PageUtility.ReplaceSR(pPageControl, info.Wkid);
                            //加载要打印的图层
                            if (info.Lyrs != null)
                            {
                                foreach (string lyr in info.Lyrs)
                                {
                                    IMapDocument pLyrDocument = new MapDocumentClass();
                                    pLyrDocument.Open(info.LyrPath + lyr, "");
                                    pMap.AddLayer(pLyrDocument.get_Map(0).get_Layer(0));
                                    //针对所见即所得,如果加载的是影像,现状,规划等大数据量的数据,则需要延时8s处理
                                    Delay(10);
                                    pPageAV.PartialRefresh(esriViewDrawPhase.esriViewAll, null, null);
                                }
                            }
                        }

                        IGeometry dataCenterGeo = EsriWktConverter.ConvertWKTToGeometry(info.DataCenter);

                        IPoint dataCenter = dataCenterGeo as IPoint;
                        PageSizeUtility.SetCenterAndScale(pPageLayout, dataCenter, info.Scale);
                        SetPageTemplate(pPageLayout, dataCenter, left, right, top, bottom, currentPageSize, currentPageOri, info);

                        //业务几何图形处理
                        if (info.BusinessShapes != null && info.BusinessShapes.Count > 0)
                        {
                            foreach (string str in info.BusinessShapes)
                            {
                                string[]  strs          = str.Split(';');
                                IGeometry shapeGeometry = EsriWktConverter.ConvertWKTToGeometry(strs[0]);
                                IPolygon  pPolygon      = shapeGeometry as IPolygon;
                                if (pPolygon != null)
                                {
                                    //地块样式
                                    IRgbColor shapeFillRgbColor = new RgbColorClass();
                                    shapeFillRgbColor.NullColor = true;
                                    IRgbColor shapeBorderRGBColor = new RgbColorClass();
                                    shapeBorderRGBColor.Red   = 255;
                                    shapeBorderRGBColor.Green = 0;
                                    shapeBorderRGBColor.Blue  = 0;
                                    double shapeBorderWidth = 1.5;
                                    // 颜色组织 a,r,g,b
                                    // 业务数据 shapewkt;bordercolor;fillcolor;borderthickness
                                    if (strs.Length == 4)
                                    {
                                        string[] bordercolorargb = strs[1].Split(',');
                                        if (bordercolorargb.Length == 4)
                                        {
                                            int ba = 255, br = 255, bg = 0, bb = 0;
                                            int.TryParse(bordercolorargb[0], out ba);
                                            int.TryParse(bordercolorargb[1], out br);
                                            int.TryParse(bordercolorargb[2], out bg);
                                            int.TryParse(bordercolorargb[3], out bb);
                                            shapeBorderRGBColor.Red          = br;
                                            shapeBorderRGBColor.Green        = bg;
                                            shapeBorderRGBColor.Blue         = bb;
                                            shapeBorderRGBColor.Transparency = (byte)ba;
                                        }
                                        string[] fillcolorargb = strs[2].Split(',');
                                        if (fillcolorargb.Length == 4)
                                        {
                                            int fa = 0, fr = 255, fg = 0, fb = 0;
                                            int.TryParse(fillcolorargb[0], out fa);
                                            int.TryParse(fillcolorargb[1], out fr);
                                            int.TryParse(fillcolorargb[2], out fg);
                                            int.TryParse(fillcolorargb[3], out fb);
                                            shapeFillRgbColor.Red          = fr;
                                            shapeFillRgbColor.Green        = fg;
                                            shapeFillRgbColor.Blue         = fb;
                                            shapeFillRgbColor.Transparency = (byte)fa;
                                        }
                                        string borderwidth = strs[3];
                                        double.TryParse(borderwidth, out shapeBorderWidth);
                                    }

                                    PageElementUtility.AddPolygonElement(pMapDocument, pPolygon, shapeBorderWidth, shapeFillRgbColor, shapeBorderRGBColor);
                                }
                            }
                        }

                        //标注处理
                        if (info.Labels != null && info.Labels.Count > 0)
                        {
                            foreach (string str in info.Labels)
                            {
                                string[] strs       = str.Split(';');
                                string   name       = strs[0];
                                string   labelxywkt = strs[1];
                                string   labelwkt   = strs[2];

                                //注记数据 name;labelxywkt;labelwkt;fontname;fontsize;fontcolor;labelbordercolor;labelfillcolor;labelborderthikness
                                IRgbColor labelFontColor   = new RgbColorClass();
                                IRgbColor labelBorderColor = new RgbColorClass();
                                IRgbColor labelFillColor   = new RgbColorClass();
                                double    labelBorderWidth = 1;
                                int       fontSize         = 14;
                                string    fontName         = "宋体";
                                if (strs.Length == 9)
                                {
                                    fontName = string.IsNullOrEmpty(strs[3]) ? "宋体" : strs[3];
                                    int.TryParse(strs[4], out fontSize);
                                    string[] fontcolorargb = strs[5].Split(',');
                                    if (fontcolorargb.Length == 4)
                                    {
                                        int fa = 0, fr = 255, fg = 0, fb = 0;
                                        int.TryParse(fontcolorargb[0], out fa);
                                        int.TryParse(fontcolorargb[1], out fr);
                                        int.TryParse(fontcolorargb[2], out fg);
                                        int.TryParse(fontcolorargb[3], out fb);
                                        labelFontColor.Red          = fr;
                                        labelFontColor.Green        = fg;
                                        labelFontColor.Blue         = fb;
                                        labelFontColor.Transparency = (byte)fa;
                                    }
                                    string[] labelborderargb = strs[6].Split(',');
                                    if (labelborderargb.Length == 4)
                                    {
                                        int ba = 0, br = 255, bg = 0, bb = 0;
                                        int.TryParse(labelborderargb[0], out ba);
                                        int.TryParse(labelborderargb[1], out br);
                                        int.TryParse(labelborderargb[2], out bg);
                                        int.TryParse(labelborderargb[3], out bb);
                                        labelBorderColor.Red          = br;
                                        labelBorderColor.Green        = bg;
                                        labelBorderColor.Blue         = bb;
                                        labelBorderColor.Transparency = (byte)ba;
                                    }
                                    string[] labelfillargb = strs[7].Split(',');
                                    if (labelfillargb.Length == 4)
                                    {
                                        int lfa = 0, lfr = 255, lfg = 0, lfb = 0;
                                        int.TryParse(labelfillargb[0], out lfa);
                                        int.TryParse(labelfillargb[1], out lfr);
                                        int.TryParse(labelfillargb[2], out lfg);
                                        int.TryParse(labelfillargb[3], out lfb);
                                        labelFillColor.Red          = lfr;
                                        labelFillColor.Green        = lfg;
                                        labelFillColor.Blue         = lfb;
                                        labelFillColor.Transparency = (byte)lfa;
                                    }
                                    double.TryParse(strs[8], out labelBorderWidth);
                                }

                                IGeometry labelxyGeometry = EsriWktConverter.ConvertWKTToGeometry(labelxywkt);
                                IPoint    pLabelXY        = labelxyGeometry as IPoint;
                                double    labelX          = pLabelXY.X;
                                double    labelY          = pLabelXY.Y;
                                IGeometry labelGeometry   = EsriWktConverter.ConvertWKTToGeometry(labelwkt);
                                IPolygon  pLabelPolygon   = labelGeometry as IPolygon;
                                PageElementUtility.AddPolygonElement(pMapDocument, pLabelPolygon, labelBorderWidth, labelFillColor, labelBorderColor);
                                PageElementUtility.AddTextElement(pMapDocument, labelX, labelY, name, fontSize, fontName, labelFontColor);
                            }
                        }

                        info.OutPath = printPath + "\\LocalFiles\\";
                        try
                        {
                            foreach (string tmpPath in info.AdditionalImages)
                            {
                                PageElementUtility.AddImageElement(pPageLayout
                                                                   , info.OutPath + tmpPath
                                                                   , Guid.NewGuid().ToString()
                                                                   , ElementPosition.DBL
                                                                   , 0.05
                                                                   , 0.05);
                            }
                        }
                        catch
                        {
                        }

                        string tmpfilename = (info.TemplateName.ToUpper().EndsWith(".MXD") ? info.TemplateName.Substring(0, info.TemplateName.Length - 4) : info.TemplateName) + Guid.NewGuid().ToString() + ".pdf";
                        info.OutPath += tmpfilename;
                        switch (info.ExportFormat.Trim().ToUpper())
                        {
                        case "PDF":
                            docExport = new ExportPDFClass();
                            break;

                        case "BMP":
                            docExport    = new ExportBMPClass();
                            info.OutPath = info.OutPath.Replace(".pdf", ".bmp");
                            break;

                        case "JPG":
                            docExport    = new ExportJPEGClass();
                            info.OutPath = info.OutPath.Replace(".pdf", ".jpg");
                            break;

                        default:
                            docExport = new ExportPDFClass();
                            break;
                        }
                        docExport.ExportFileName = info.OutPath;
                        docPrintExport.Export(pPageAV, docExport, info.DPI, false, null);
                        outmsg = printIISRoot + tmpfilename;
                        result = true;
                    }
                    catch (Exception ex)
                    {
                        result = false;
                        outmsg = string.Format("制图错误:坐标系是否一致——{0}", ex.Message);
                    }
                    finally
                    {
                        ReleaseObject(pMapDocument);
                        ReleaseObject(docExport);
                        ReleaseObject(docPrintExport);
                    }
                }
                else
                {
                    result = false;
                    outmsg = "制图模板:" + info.MxdPath + GetFilePath() + "未找到!";
                }

                #endregion
            }
            else
            {
                result = hasright;
            }

            return(result);
        }
예제 #29
0
파일: Task.cs 프로젝트: zj8487/HyDM
        /// <summary>
        /// 生成MXD,并将数据库重置
        /// </summary>
        /// <returns></returns>
        public bool CreateMXD()
        {
            try
            {
                string strMxdFile = GetMXDFile();
                File.Copy(System.Windows.Forms.Application.StartupPath + "\\" + COMMONCONST.RelativePath_MXD + "\\" + this.StandardName + ".MXD", strMxdFile);
                IMapDocument mapDoc = new MapDocumentClass();
                mapDoc.Open(strMxdFile, null);

                // 重定向数据库
                IMap mapTarget = mapDoc.get_Map(0);
                Hy.Common.Utility.Esri.AEAccessFactory.ResetMapWorkspace(this.BaseWorkspace, mapTarget);
                // 修改空间参考及范围
                IEnumDataset      enDataset = this.BaseWorkspace.get_Datasets(esriDatasetType.esriDTAny);
                IDataset          dataset = enDataset.Next();
                double            xMin = double.MaxValue, xMax = double.MinValue, yMin = double.MaxValue, yMax = double.MinValue;
                IEnvelope         envExtent  = null;
                ISpatialReference spatialRef = null;
                while (dataset != null)
                {
                    IGeoDataset geoDataset = dataset as IGeoDataset;
                    if (geoDataset != null)
                    {
                        //mapTarget.SpatialReference = geoDataset.SpatialReference;
                        //mapDoc.ActiveView.Extent.SpatialReference = geoDataset.SpatialReference;
                        //mapDoc.ActiveView.Extent = geoDataset.Extent;
                        //mapDoc.ActiveView.FullExtent.SpatialReference = geoDataset.SpatialReference;
                        //mapDoc.ActiveView.FullExtent = geoDataset.Extent;

                        spatialRef = geoDataset.SpatialReference;
                        envExtent  = geoDataset.Extent;
                        if (!envExtent.IsEmpty)
                        {
                            if (xMin > envExtent.XMin)
                            {
                                xMin = envExtent.XMin;
                            }
                            if (yMin > envExtent.YMin)
                            {
                                yMin = envExtent.YMin;
                            }
                            if (xMax < envExtent.XMax)
                            {
                                xMax = envExtent.XMax;
                            }
                            if (yMax < envExtent.YMax)
                            {
                                yMax = envExtent.YMax;
                            }
                        }
                        //break;
                    }
                    dataset = enDataset.Next();
                }
                mapTarget.SpatialReference = spatialRef;
                envExtent.PutCoords(xMin, yMin, xMax, yMax);
                //mapTarget.RecalcFullExtent();
                mapDoc.ActiveView.Extent              = envExtent;
                mapDoc.ActiveView.FullExtent          = envExtent;
                (mapTarget as IActiveView).FullExtent = envExtent;

                mapDoc.Save(true, false);
                mapDoc.Close();

                // 再复制 “任务执行格式验证.xsd”文件
                File.Copy(System.Windows.Forms.Application.StartupPath + "\\" + COMMONCONST.RelativePath_MXD + "\\" + COMMONCONST.File_Name_XSD, GetTaskFolder() + "\\" + COMMONCONST.File_Name_XSD);
                return(true);
            }
            catch (Exception exp)
            {
                SendMessage(enumMessageType.Exception, "生成MXD失败,错误信息:" + exp.Message);
                return(false);
            }
        }
    private void btnLoadmpk_Click(object sender, EventArgs e)
    {
      try
      {
        IMapDocument mapDocument = new MapDocumentClass();
        if (IsConnected())
        {
          mapDocument.Open(txtMapPackage.Text, "");
        }
        else
        {
          if (DoesPackageExist(PackageType.MapPackage))
          {
            mapDocument.Open(packageLocation, "");
          }

        }
        axMapControl1.Map = mapDocument.get_Map(0);
      }
      catch (Exception ex)
      {
        MessageBox.Show("Failed to open Map Package!", ex.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
    }
 private void btnWebMap_Click(object sender, EventArgs e)
 {
   if (!(IsConnected()))
   {
     // Since Web Maps require and internet connection anyways
     // just fail if there isn't one.
     MessageBox.Show("Cannot Connect to ArcGIS.com!", "Failed to open Web Map.", MessageBoxButtons.OK, MessageBoxIcon.Error);
     return;
   }
   try
   {
     IMapDocument mapDocument = new MapDocumentClass();
     string webMapMxd = webMapLocation + @"\" + myWebMapName + @"\" + myWebMapName + ".mxd";
     if (File.Exists(webMapMxd))
       mapDocument.Open(webMapMxd, "");
     else
       mapDocument.Open(txtWebMap.Text, "");
     axMapControl1.Map = mapDocument.get_Map(0);
   }
   catch (Exception ex)
   {
     MessageBox.Show("Failed to open Web Map!", ex.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
   }
 }
예제 #32
0
        public void FetchLayers(object a)
        {
            Status = "Fetching...";
            IMapDocument pMapDoc = new MapDocumentClass();
            try
            {
                pMapDoc.Open(MxdInfo.FullName);
                IDocumentInfo2 pDocInfo = (IDocumentInfo2)pMapDoc;
                var map = pMapDoc.get_Map(0);
                var count = map.LayerCount;
                for (int i = 0; i < map.LayerCount; i++)
                {
                    ILayer layer = (ILayer)map.get_Layer(i);
                    try
                    {
                        IDataLayer2 dataLayer = (IDataLayer2)layer;
                        IDatasetName name = (IDatasetName)dataLayer.DataSourceName;
                        IWorkspaceName workspace = name.WorkspaceName;
                        IPropertySet propSet = workspace.ConnectionProperties;
                        object obj1 = new object[1];
                        object obj2 = new object[1];
                        propSet.GetAllProperties(out obj1, out obj2);

                        object[] array1 = (object[])obj1;
                        object[] array2 = (object[])obj2;

                        _knownLayers.Add(new LayerEntry(layer.Name, array2[0].ToString(), MxdInfo.Name));
                        Status = string.Format("Found {0}/{1}", (i + 1), count);
                        FetchLayersEvent();
                    }
                    catch (Exception e)
                    {
                        _knownLayers.Add(new LayerEntry(layer.Name, "Unknown - not a feature layer", MxdInfo.Name));
                        Status = string.Format("Found {0}/{1}", (i + 1), count);
                        FetchLayersEvent();
                    }
                }
            }
            catch (Exception e)
            {
                Status = "An error occurred";
            }
            finally
            {
                pMapDoc.Close();
                FetchLayersEvent();
            }
        }
예제 #33
0
        private void bt_ok_Click(object sender, EventArgs e)
        {
            //判断输入路径是否正确
            #region
            try
            {
                if (!File.Exists(tb_nppinput.Text))
                {
                    MessageBox.Show("生态系统净初级生产力平均值数据输入路径不正确或文件被占用,请重新输入路径!", "提示", MessageBoxButtons.OK);
                    return;
                }
                if (!File.Exists(tb_preinput.Text))
                {
                    MessageBox.Show("平均年降水量数据输入路径不正确或文件被占用,请重新输入路径!", "提示", MessageBoxButtons.OK);
                    return;
                }
                if (!File.Exists(tb_tminput.Text))
                {
                    MessageBox.Show("平均温度数据输入路径不正确或文件被占用,请重新输入路径!", "提示", MessageBoxButtons.OK);
                    return;
                }
                if (!File.Exists(tb_altinput.Text))
                {
                    MessageBox.Show("海拔参数数据输入路径不正确或文件被占用,请重新输入路径!", "提示", MessageBoxButtons.OK);
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("设置路径不合法,请检查!");
                return;
            }
            #endregion
            object sev = null;
            tb_state.Text = "正在处理……";
            ESRI.ArcGIS.SpatialAnalystTools.RasterCalculator rc      = new ESRI.ArcGIS.SpatialAnalystTools.RasterCalculator();
            ESRI.ArcGIS.SpatialAnalystTools.Float            tofloat = new ESRI.ArcGIS.SpatialAnalystTools.Float();
            Geoprocessor gp = new Geoprocessor();
            gp.OverwriteOutput = true;
            try
            {
                //输入数据类型转换
                #region
                //npp输入数据转化为浮点型
                string floatfilepath_npp = System.IO.Path.GetDirectoryName(tb_biooutput.Text) + "\\" + System.IO.Path.GetFileNameWithoutExtension(tb_biooutput.Text) + "_float_npp" + System.IO.Path.GetExtension(tb_biooutput.Text);
                tofloat.in_raster_or_constant = tb_nppinput.Text;
                tofloat.out_raster            = floatfilepath_npp;
                gp.Execute(tofloat, null);

                //pre输入数据转化为浮点型
                string floatfilepath_pre = System.IO.Path.GetDirectoryName(tb_biooutput.Text) + "\\" + System.IO.Path.GetFileNameWithoutExtension(tb_biooutput.Text) + "_float_pre" + System.IO.Path.GetExtension(tb_biooutput.Text);
                tofloat.in_raster_or_constant = tb_preinput.Text;
                tofloat.out_raster            = floatfilepath_pre;
                gp.Execute(tofloat, null);

                //tm输入数据转化为浮点型
                string floatfilepath_tm = System.IO.Path.GetDirectoryName(tb_biooutput.Text) + "\\" + System.IO.Path.GetFileNameWithoutExtension(tb_biooutput.Text) + "_float_tm" + System.IO.Path.GetExtension(tb_biooutput.Text);
                tofloat.in_raster_or_constant = tb_tminput.Text;
                tofloat.out_raster            = floatfilepath_tm;
                gp.Execute(tofloat, null);

                //alt输入数据转化为浮点型
                string floatfilepath_alt = System.IO.Path.GetDirectoryName(tb_biooutput.Text) + "\\" + System.IO.Path.GetFileNameWithoutExtension(tb_biooutput.Text) + "_float_alt" + System.IO.Path.GetExtension(tb_biooutput.Text);
                tofloat.in_raster_or_constant = tb_altinput.Text;
                tofloat.out_raster            = floatfilepath_alt;
                gp.Execute(tofloat, null);
                #endregion


                //输入数据进行归一化处理
                #region
                //npp数据归一化处理
                string npp;
                npp              = System.IO.Path.GetDirectoryName(tb_biooutput.Text) + "\\" + System.IO.Path.GetFileNameWithoutExtension(tb_biooutput.Text) + "_npp" + System.IO.Path.GetExtension(tb_biooutput.Text);
                rc.expression    = "(\"" + floatfilepath_npp + "\" - " + GetMinPixelValue(floatfilepath_npp).ToString() + ") / (" + (GetMaxPixelValue(floatfilepath_npp) - GetMinPixelValue(floatfilepath_npp)).ToString() + ")";
                rc.output_raster = npp;
                tb_state.Text    = "正在对生态系统净初级生产力平均值进行归一化……";
                gp.Execute(rc, null);
                tb_state.Text = "生态系统净初级生产力平均值归一化处理完成!";

                //pre数据归一化处理
                string pre;
                pre              = System.IO.Path.GetDirectoryName(tb_biooutput.Text) + "\\" + System.IO.Path.GetFileNameWithoutExtension(tb_biooutput.Text) + "_pre" + System.IO.Path.GetExtension(tb_biooutput.Text);
                rc.expression    = "(\"" + floatfilepath_pre + "\" - " + GetMinPixelValue(floatfilepath_pre).ToString() + ") / (" + (GetMaxPixelValue(floatfilepath_pre) - GetMinPixelValue(floatfilepath_pre)).ToString() + ")";
                rc.output_raster = pre;
                tb_state.Text    = "正在对平均年降水量数据进行归一化……";
                gp.Execute(rc, null);
                tb_state.Text = "平均年降水量数据归一化处理完成!";

                //tm数据归一化处理
                string tm;
                tm               = System.IO.Path.GetDirectoryName(tb_biooutput.Text) + "\\" + System.IO.Path.GetFileNameWithoutExtension(tb_biooutput.Text) + "_tm" + System.IO.Path.GetExtension(tb_biooutput.Text);
                rc.expression    = "(\"" + floatfilepath_tm + "\" - " + GetMinPixelValue(floatfilepath_tm).ToString() + ") / (" + (GetMaxPixelValue(floatfilepath_tm) - GetMinPixelValue(floatfilepath_tm)).ToString() + ")";
                rc.output_raster = tm;
                tb_state.Text    = "正在对平均温度进行归一化……";
                gp.Execute(rc, null);
                tb_state.Text = "平均温度归一化处理完成!";

                //alt数据归一化处理
                string alt;
                alt              = System.IO.Path.GetDirectoryName(tb_biooutput.Text) + "\\" + System.IO.Path.GetFileNameWithoutExtension(tb_biooutput.Text) + "_alt" + System.IO.Path.GetExtension(tb_biooutput.Text);
                rc.expression    = "(\"" + floatfilepath_alt + "\" - " + GetMinPixelValue(floatfilepath_alt).ToString() + ") / (" + (GetMaxPixelValue(floatfilepath_alt) - GetMinPixelValue(floatfilepath_alt)).ToString() + ")";
                rc.output_raster = alt;
                tb_state.Text    = "正在对海拔参数数据进行归一化……";
                gp.Execute(rc, null);
                tb_state.Text = "海拔参数数据归一化处理完成!";
                #endregion


                //计算生物多样性保护服务能力指数
                rc.expression    = "\"" + npp + "\" * \"" + pre + "\" * \"" + tm + "\" * ( 1 - \"" + alt + "\" )";
                rc.output_raster = tb_biooutput.Text;
                tb_state.Text    = "正在计算计算生物多样性保护服务能力指数……";
                gp.Execute(rc, null);
                tb_state.Text = "计算生物多样性保护服务能力指数计算完成!";


                //删除临时文件
                if (tb_state.Text == "计算生物多样性保护服务能力指数计算完成!")
                {
                    string[] files = Directory.GetFiles(System.IO.Path.GetDirectoryName(tb_biooutput.Text), System.IO.Path.GetFileNameWithoutExtension(tb_biooutput.Text) + "*");
                    foreach (string file in files)
                    {
                        if (System.IO.Path.GetFileNameWithoutExtension(tb_biooutput.Text) != System.IO.Path.GetFileNameWithoutExtension(file))
                        {
                            File.Delete(file);
                        }
                    }
                }



                //将结果加载显示
                #region
                string       mxfile       = System.Environment.CurrentDirectory + "\\Data\\EcoRedLine\\生物多样性生态红线划分.mxd";
                IMapDocument pMapDocument = new MapDocumentClass();
                pMapDocument.Open(mxfile); //打开本地的地图文档,用来操作改mxd文件
                IMap              pMap                   = pMapDocument.get_Map(0);
                IMapLayers        pMapLayer              = pMap as IMapLayers;
                IRasterLayer      pRasterLayer           = new RasterLayerClass();
                IWorkspaceFactory rasterWorkspaceFactory = new RasterWorkspaceFactoryClass();
                IRasterWorkspace  rasterWorkspace        = (IRasterWorkspace)rasterWorkspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(tb_biooutput.Text), 0);
                IRasterDataset    pRasterDataset1        = rasterWorkspace.OpenRasterDataset("Biodiversity.tif"); //打开栅格图的文件名
                pRasterLayer.CreateFromDataset(pRasterDataset1);                                                  //创建
                pRasterLayer = pMapLayer.get_Layer(0) as IRasterLayer;
                pRasterLayer.CreateFromDataset(pRasterDataset1);
                pMapDocument.Save(true, true);//保存更改完路径后的mxd文件

                _PageLayoutControl.LoadMxFile(mxfile);
                _PageLayoutControl.Extent = _PageLayoutControl.FullExtent;
                _PageLayoutControl.ZoomToWholePage();


                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(gp.GetMessages(ref sev), "提示", MessageBoxButtons.OK);
            }
        }
예제 #34
0
        public override bool LoadMap(string filePath)
        {
            IMapDocument mapDoc = new MapDocumentClass();
            if (mapDoc.get_IsPresent(filePath) && !mapDoc.get_IsPasswordProtected(filePath))
            {
                mapDoc.Open(filePath, string.Empty);
                // set the first map as the active view
                IMap map = mapDoc.get_Map(0);
                mapDoc.SetActiveView((IActiveView)map);
                this._axLayoutCtrl.PageLayout = mapDoc.PageLayout;
                this._mapAndLayoutSync.ReplaceMap(map);
                mapDoc.Close();
                this._mapFile = filePath;
                return true;
            }
            else
            {
                return false;
            }

            /*
            if (this._axMapCtrl.CheckMxFile(filePath))
            {
                


                this._axMapCtrl.LoadMxFile(filePath, Type.Missing, Type.Missing);
                this._axMapCtrl.Enabled = true;
                this._mapFile = filePath;
                return true;
            }
            else
            {
                return false;
            }
            */ 
        }
예제 #35
0
        static void Main(string[] args)
        {
            bool   showHelp    = false;
            bool   gzip        = false;
            bool   overwrite   = false;
            bool   verbose     = false;
            string destination = ".";

            int[]            levels = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 };
            HashSet <string> fields = null;
            int threadCount         = System.Environment.ProcessorCount;

            OptionSet p = new OptionSet()
            {
                { "d|dir=", "destination directory (defaults to current directory)", d => destination = d },
                { "l|levels=",
                  "list of scale levels [0-19], separated by commas",
                  l => levels = l.Split(new char[] { ',' }).Select(s => Convert.ToInt32(s)).ToArray() },
                { "f|fields=",
                  "list of field names to include in UTFGrid data",
                  f => fields = new HashSet <string>(f.Split(new char[] { ',' })) },
                { "t|threads=",
                  "number of threads to use (defaults to number of processors)",
                  t => threadCount = Convert.ToInt32(t) },
                { "z|zip", "zip the json files using gzip compression before saving", z => gzip = z != null },
                { "o|overwrite", "overwrite existing files", o => overwrite = o != null },
                { "v|verbose", "verbose output", v => verbose = v != null },
                { "h|help", "show this message and exit", h => showHelp = h != null }
            };
            List <string> extra;

            try {
                extra = p.Parse(args);
            } catch (OptionException e) {
                Console.Write("utfgrid");
                Console.WriteLine(e.Message);
                Console.WriteLine("Try `utfgrid --help' for more information.");
                return;
            }
            if (showHelp)
            {
                Console.WriteLine("Usage: utfgrid [OPTIONS]+ mxd_document");
                Console.WriteLine("Generate UTFGrid files from the given map document");
                Console.WriteLine();
                Console.WriteLine("Options:");
                p.WriteOptionDescriptions(Console.Out);
                return;
            }
            else if (extra.Count < 1)
            {
                Console.WriteLine("utfgrid: no map document specified");
                Console.WriteLine("Try `utfgrid --help' for more information.");
                return;
            }
            RuntimeManager.BindLicense(ProductCode.EngineOrDesktop);

            IMap map = null;

            try {
                IMapDocument mapDocument = new MapDocumentClass();
                mapDocument.Open(extra[0], null);
                map = mapDocument.ActiveView as IMap;
                if (map == null)
                {
                    map = mapDocument.get_Map(0);
                }
                mapDocument.Close();
            } catch (Exception) { }
            if (map == null)
            {
                Console.WriteLine("Unable to open map at " + extra[0]);
                return;
            }
            if ((map.SpatialReference.FactoryCode != 102113) &&
                (map.SpatialReference.FactoryCode != 102100) &&
                (map.SpatialReference.FactoryCode != 3785))
            {
                Console.WriteLine("Spatial reference of map must be Web Mercator (is " + map.SpatialReference.FactoryCode + ")");
                return;
            }

            IActiveView activeView = map as IActiveView;
            // get the extent from the active view
            IEnvelope fullExtent = activeView.FullExtent;

            Console.WriteLine("starting utfgrid generator with " + threadCount + " threads");

            UTFGridGeneratorConfig config = new UTFGridGeneratorConfig(extra[0], DescribeTiles(levels, activeView.FullExtent));

            config.GZip        = gzip;
            config.Overwrite   = overwrite;
            config.Verbose     = verbose;
            config.Destination = destination;

            Thread[] workerThreads = new Thread[threadCount];

            for (int i = 0; i < threadCount; i++)
            {
                workerThreads[i] = new Thread(new ParameterizedThreadStart(UTFGridGenerator.Execute));
                workerThreads[i].SetApartmentState(ApartmentState.STA);
                workerThreads[i].IsBackground = true;
                workerThreads[i].Priority     = ThreadPriority.BelowNormal;
                workerThreads[i].Name         = "UTFGridGenerator " + (i + 1).ToString();
                workerThreads[i].Start(config);
            }

            foreach (Thread t in workerThreads)
            {
                t.Join();
            }
            workerThreads = null;
        }
예제 #36
0
        protected void OpenPastureMapDoc(Pasture pasture)
        {
            IMapDocument mapDoc = new MapDocumentClass();
            if (mapDoc.get_IsPresent(pasture.strMapDoc) &&
                !mapDoc.get_IsPasswordProtected(pasture.strMapDoc))
            {
                mapDoc.Open(pasture.strMapDoc, string.Empty);

                // set the first map as the active view
                m_pastureMap = mapDoc.get_Map(0);
                mapDoc.SetActiveView((IActiveView)m_pastureMap);
                mapDoc.Close();
            }
        }
    /// <summary>
    /// Occurs when this command is clicked
    /// </summary>
    public override void OnClick()
    {
      //launch a new OpenFile dialog
      OpenFileDialog dlg = new OpenFileDialog();
      dlg.Filter = "Map Documents (*.mxd)|*.mxd";
      dlg.Multiselect = false;
      dlg.Title = "Open Map Document";
      if (dlg.ShowDialog() == DialogResult.OK)
      {
        string docName = dlg.FileName;

        IMapDocument mapDoc = new MapDocumentClass();
        if (mapDoc.get_IsPresent(docName) && !mapDoc.get_IsPasswordProtected(docName))
        {
          mapDoc.Open(docName, string.Empty);

          // set the first map as the active view
          IMap map = mapDoc.get_Map(0);
          mapDoc.SetActiveView((IActiveView)map);

          m_controlsSynchronizer.PageLayoutControl.PageLayout = mapDoc.PageLayout;

          m_controlsSynchronizer.ReplaceMap(map);

          mapDoc.Close();

          m_sDocumentPath = docName;
        }
      }
    }
예제 #38
0
        static void Main(string[] args)
        {
            bool showHelp = false;
            bool gzip = false;
            bool overwrite = false;
            bool verbose = false;
            string destination = ".";
            int[] levels = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 };
            HashSet<string> fields = null;
            int threadCount = System.Environment.ProcessorCount;

            OptionSet p = new OptionSet() {
                { "d|dir=", "destination directory (defaults to current directory)", d => destination = d },
                { "l|levels=",
                  "list of scale levels [0-19], separated by commas",
                  l => levels = l.Split(new char[] { ',' }).Select(s => Convert.ToInt32(s)).ToArray() },
                { "f|fields=",
                  "list of field names to include in UTFGrid data",
                  f => fields = new HashSet<string>(f.Split(new char[] { ',' })) },
                { "t|threads=",
                  "number of threads to use (defaults to number of processors)",
                  t => threadCount = Convert.ToInt32(t) },
                { "z|zip",  "zip the json files using gzip compression before saving", z => gzip = z != null },
                { "o|overwrite", "overwrite existing files", o => overwrite = o != null },
                { "v|verbose", "verbose output", v => verbose = v != null },
                { "h|help",  "show this message and exit", h => showHelp = h != null }
            };
            List<string> extra;
            try {
                extra = p.Parse(args);
            } catch (OptionException e) {
                Console.Write("utfgrid");
                Console.WriteLine(e.Message);
                Console.WriteLine("Try `utfgrid --help' for more information.");
                return;
            }
            if (showHelp) {
                Console.WriteLine("Usage: utfgrid [OPTIONS]+ mxd_document");
                Console.WriteLine("Generate UTFGrid files from the given map document");
                Console.WriteLine();
                Console.WriteLine("Options:");
                p.WriteOptionDescriptions(Console.Out);
                return;
            } else if (extra.Count < 1) {
                Console.WriteLine("utfgrid: no map document specified");
                Console.WriteLine("Try `utfgrid --help' for more information.");
                return;
            }
            RuntimeManager.BindLicense(ProductCode.EngineOrDesktop);

            IMap map = null;
            try {
                IMapDocument mapDocument = new MapDocumentClass();
                mapDocument.Open(extra[0], null);
                map = mapDocument.ActiveView as IMap;
                if (map == null) {
                    map = mapDocument.get_Map(0);
                }
                mapDocument.Close();
            } catch (Exception) { }
            if (map == null) {
                Console.WriteLine("Unable to open map at " + extra[0]);
                return;
            }
            if ((map.SpatialReference.FactoryCode != 102113) &&
                (map.SpatialReference.FactoryCode != 102100) &&
                (map.SpatialReference.FactoryCode != 3785)) {
                Console.WriteLine("Spatial reference of map must be Web Mercator (is " + map.SpatialReference.FactoryCode + ")");
                return;
            }

            IActiveView activeView = map as IActiveView;
            // get the extent from the active view
            IEnvelope fullExtent = activeView.FullExtent;

            Console.WriteLine("starting utfgrid generator with " + threadCount + " threads");

            UTFGridGeneratorConfig config = new UTFGridGeneratorConfig(extra[0], DescribeTiles(levels, activeView.FullExtent));
            config.GZip = gzip;
            config.Overwrite = overwrite;
            config.Verbose = verbose;
            config.Destination = destination;

            Thread[] workerThreads = new Thread[threadCount];

            for (int i = 0; i < threadCount; i++) {
                workerThreads[i] = new Thread(new ParameterizedThreadStart(UTFGridGenerator.Execute));
                workerThreads[i].SetApartmentState(ApartmentState.STA);
                workerThreads[i].IsBackground = true;
                workerThreads[i].Priority = ThreadPriority.BelowNormal;
                workerThreads[i].Name = "UTFGridGenerator " + (i + 1).ToString();
                workerThreads[i].Start(config);
            }

            foreach (Thread t in workerThreads) {
                t.Join();
            }
            workerThreads = null;
        }
예제 #39
0
        private void bt_ok_Click(object sender, EventArgs e)
        {
            //判断输入路径是否正确
            #region
            try
            {
                if (!File.Exists(tb_demnput.Text))
                {
                    MessageBox.Show("平均降水量数据输入路径不正确或文件被占用,请重新输入路径!", "提示", MessageBoxButtons.OK);
                    return;
                }
                if (Convert.ToDouble(tb_highinput.Text) < 0)
                {
                    MessageBox.Show("请输入正确的水位高程值!", "提示", MessageBoxButtons.OK);
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("设置路径或水位高程值不合法,请检查!");
                return;
            }
            #endregion



            ESRI.ArcGIS.SpatialAnalystTools.RasterCalculator rc = new ESRI.ArcGIS.SpatialAnalystTools.RasterCalculator();
            Geoprocessor gp = new Geoprocessor();
            gp.OverwriteOutput = true;
            object sev = null;
            try
            {
                tb_state.Text = "正在处理……";
                //判断输入水位数据的单位
                double waterunit = 0;
                if (cb_waterunits.Text == "米(m)")
                {
                    waterunit = 1;
                }
                else
                {
                    waterunit = 0.001;
                }


                //判断输入缓冲距离及缓冲单位
                double bufferunit = 0;
                if (cb_bufferunits.Text == "米(m)")
                {
                    bufferunit = 1;
                }
                else
                {
                    bufferunit = 1000;
                }
                double[] bufferdistance = { Convert.ToDouble(nud_one.Value) * bufferunit, Convert.ToDouble(nud_two.Value) * bufferunit, Convert.ToDouble(nud_three.Value) * bufferunit, Convert.ToDouble(nud_four.Value) * bufferunit };


                //提取高程高于水位的区域
                tb_state.Text = "正在提取未淹没区域……";
                string flood_high = System.IO.Path.GetDirectoryName(tb_flooutput.Text) + "\\" + System.IO.Path.GetFileNameWithoutExtension(tb_flooutput.Text) + "_high" + System.IO.Path.GetExtension(tb_flooutput.Text);
                rc.output_raster = flood_high;
                rc.expression    = "Con(\"" + tb_demnput.Text + "\" >= (" + tb_highinput.Text + " * " + waterunit.ToString() + "),\"" + tb_demnput.Text + "\")";
                gp.Execute(rc, null);
                tb_state.Text = "未淹没区域提取完成!";


                //水文分析填洼
                tb_state.Text = "正在进行水文分析计算填洼……";
                ESRI.ArcGIS.SpatialAnalystTools.Fill fill = new ESRI.ArcGIS.SpatialAnalystTools.Fill();
                string fill_input, fill_output;
                fill_input              = flood_high;
                fill_output             = System.IO.Path.GetDirectoryName(tb_flooutput.Text) + "\\" + System.IO.Path.GetFileNameWithoutExtension(tb_flooutput.Text) + "_fill" + System.IO.Path.GetExtension(tb_flooutput.Text);
                fill.in_surface_raster  = fill_input;
                fill.out_surface_raster = fill_output;
                gp.Execute(fill, null);
                tb_state.Text = "水文分析填洼计算完成!";

                //水文分析计算流向
                tb_state.Text = "正在进行水文分析计算流向……";
                ESRI.ArcGIS.SpatialAnalystTools.FlowDirection flowdirection = new ESRI.ArcGIS.SpatialAnalystTools.FlowDirection();
                string flowdirection_input, flowdirection_output;
                flowdirection_input                     = fill_output;
                flowdirection_output                    = System.IO.Path.GetDirectoryName(tb_flooutput.Text) + "\\" + System.IO.Path.GetFileNameWithoutExtension(tb_flooutput.Text) + "_FlowDir" + System.IO.Path.GetExtension(tb_flooutput.Text);
                flowdirection.in_surface_raster         = flowdirection_input;
                flowdirection.out_flow_direction_raster = flowdirection_output;
                gp.Execute(flowdirection, null);
                tb_state.Text = "水文分析流向计算完成!";



                //水文分析计算流量
                tb_state.Text = "正在进行水文分析计算流量……";
                ESRI.ArcGIS.SpatialAnalystTools.FlowAccumulation flowaccumulation = new ESRI.ArcGIS.SpatialAnalystTools.FlowAccumulation();
                string flowaccumulation_input, flowaccumulation_output;
                flowaccumulation_input  = flowdirection_output;
                flowaccumulation_output = System.IO.Path.GetDirectoryName(tb_flooutput.Text) + "\\" + System.IO.Path.GetFileNameWithoutExtension(tb_flooutput.Text) + "_FlowAcc" + System.IO.Path.GetExtension(tb_flooutput.Text);
                flowaccumulation.in_flow_direction_raster = flowaccumulation_input;
                flowaccumulation.out_accumulation_raster  = flowaccumulation_output;
                gp.Execute(flowaccumulation, null);
                tb_state.Text = "水文分析流量计算完成!";

                //盆域分析
                tb_state.Text = "正在进行水文分析盆域分析……";
                ESRI.ArcGIS.SpatialAnalystTools.Basin basin = new ESRI.ArcGIS.SpatialAnalystTools.Basin();
                string basin_input, basin_output;
                basin_input  = flowdirection_output;
                basin_output = System.IO.Path.GetDirectoryName(tb_flooutput.Text) + "\\" + System.IO.Path.GetFileNameWithoutExtension(tb_flooutput.Text) + "_Basin" + System.IO.Path.GetExtension(tb_flooutput.Text);
                basin.in_flow_direction_raster = basin_input;
                basin.out_raster = basin_output;
                gp.Execute(basin, null);
                tb_state.Text = "水文分析盆域分析计算完成!";


                //阈值提取河流
                tb_state.Text = "正在阈值提取河流……";
                string flood_rasterriver = System.IO.Path.GetDirectoryName(tb_flooutput.Text) + "\\" + System.IO.Path.GetFileNameWithoutExtension(tb_flooutput.Text) + "_river" + System.IO.Path.GetExtension(tb_flooutput.Text);
                rc.expression    = "Con(\"" + flowaccumulation_output + "\" >= 800,1)";
                rc.output_raster = flood_rasterriver;
                gp.Execute(rc, null);
                tb_state.Text = "阈值提取河流计算完成!";

                //水文分析栅格河网矢量化
                tb_state.Text = "正在进行水文分析栅格河网矢量化……";
                ESRI.ArcGIS.SpatialAnalystTools.StreamToFeature streamtofeature = new ESRI.ArcGIS.SpatialAnalystTools.StreamToFeature();
                string streamtofeature_output;
                streamtofeature_output = System.IO.Path.GetDirectoryName(tb_flooutput.Text) + "\\" + System.IO.Path.GetFileNameWithoutExtension(tb_flooutput.Text) + "_river.shp";
                streamtofeature.in_flow_direction_raster = flowdirection_output;
                streamtofeature.in_stream_raster         = flood_rasterriver;
                streamtofeature.out_polyline_features    = streamtofeature_output;
                gp.Execute(streamtofeature, null);
                tb_state.Text = "水文分析栅格河网矢量化计算完成!";


                //多环缓冲区
                tb_state.Text = "正在计算多环缓冲区……";
                ESRI.ArcGIS.AnalysisTools.MultipleRingBuffer multipleringbuffer = new ESRI.ArcGIS.AnalysisTools.MultipleRingBuffer();
                string multipleringbuffer_output = System.IO.Path.GetDirectoryName(tb_flooutput.Text) + "\\" + System.IO.Path.GetFileNameWithoutExtension(tb_flooutput.Text) + "_multbuffer.shp";
                multipleringbuffer.Input_Features = streamtofeature_output;
                multipleringbuffer.Distances      = bufferdistance[0].ToString() + ";" + bufferdistance[1].ToString() + ";" + bufferdistance[2].ToString() + ";" + bufferdistance[3].ToString() + ";";
                ;
                multipleringbuffer.Buffer_Unit          = "meters";
                multipleringbuffer.Output_Feature_class = multipleringbuffer_output;
                gp.Execute(multipleringbuffer, null);
                tb_state.Text = "多环缓冲区计算完成!";


                //多环缓冲区矢量转栅格
                tb_state.Text = "正在进行多环缓冲区矢量转栅格……";
                ESRI.ArcGIS.ConversionTools.FeatureToRaster featuretoraster = new ESRI.ArcGIS.ConversionTools.FeatureToRaster();
                string featuretoraster_output = System.IO.Path.GetDirectoryName(tb_flooutput.Text) + "\\" + System.IO.Path.GetFileNameWithoutExtension(tb_flooutput.Text) + "_multbuffer" + System.IO.Path.GetExtension(tb_flooutput.Text);
                featuretoraster.in_features = System.IO.Path.GetDirectoryName(tb_flooutput.Text) + "\\" + System.IO.Path.GetFileNameWithoutExtension(tb_flooutput.Text) + "_multbuffer.shp";
                featuretoraster.field       = "distance";
                featuretoraster.out_raster  = featuretoraster_output;
                gp.Execute(featuretoraster, null);
                tb_state.Text = "多环缓冲区矢量转栅格计算完成!";


                //删除临时文件
                if (tb_state.Text == "多环缓冲区矢量转栅格计算完成!")
                {
                    string[] files = Directory.GetFiles(System.IO.Path.GetDirectoryName(tb_flooutput.Text), System.IO.Path.GetFileNameWithoutExtension(tb_flooutput.Text) + "*");
                    foreach (string file in files)
                    {
                        if (System.IO.Path.GetFileNameWithoutExtension(file) != System.IO.Path.GetFileNameWithoutExtension(basin_output) && System.IO.Path.GetFileNameWithoutExtension(file) != System.IO.Path.GetFileNameWithoutExtension(featuretoraster_output))
                        {
                            File.Delete(file);
                        }
                    }
                }


                //将结果加载显示
                #region
                string       mxfile       = System.Environment.CurrentDirectory + "\\Data\\EcoRedLine\\洪水淹没生态红线划分.mxd";
                IMapDocument pMapDocument = new MapDocumentClass();
                pMapDocument.Open(mxfile); //打开本地的地图文档,用来操作改mxd文件
                IMap              pMap                   = pMapDocument.get_Map(0);
                IMapLayers        pMapLayer              = pMap as IMapLayers;
                IRasterLayer      pRasterLayer           = new RasterLayerClass();
                IWorkspaceFactory rasterWorkspaceFactory = new RasterWorkspaceFactoryClass();
                IRasterWorkspace  rasterWorkspace        = (IRasterWorkspace)rasterWorkspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(tb_flooutput.Text), 0);

                IRasterDataset pRasterDataset1 = rasterWorkspace.OpenRasterDataset("Flood_multbuffer.tif"); //打开栅格图的文件名
                pRasterLayer.CreateFromDataset(pRasterDataset1);                                            //创建
                pRasterLayer = pMapLayer.get_Layer(0) as IRasterLayer;
                pRasterLayer.CreateFromDataset(pRasterDataset1);

                IRasterLayer   pRasterLayer2   = new RasterLayerClass();
                IRasterDataset pRasterDataset2 = rasterWorkspace.OpenRasterDataset("Flood_Basin.tif"); //打开栅格图的文件名
                pRasterLayer2.CreateFromDataset(pRasterDataset2);                                      //创建
                pRasterLayer2 = pMapLayer.get_Layer(1) as IRasterLayer;
                pRasterLayer2.CreateFromDataset(pRasterDataset2);


                pMapDocument.Save(true, true);//保存更改完路径后的mxd文件

                _PageLayoutControl.LoadMxFile(mxfile);
                _PageLayoutControl.Extent = _PageLayoutControl.FullExtent;
                _PageLayoutControl.ZoomToWholePage();


                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(gp.GetMessages(ref sev), "提示", MessageBoxButtons.OK);
            }
        }
예제 #40
0
        protected void OpenAdministrativeMapDoc(string adminMapDoc)
        {
            IMapDocument mapDoc = new MapDocumentClass();
            if (mapDoc.get_IsPresent(adminMapDoc) &&
                !mapDoc.get_IsPasswordProtected(adminMapDoc))
            {
                mapDoc.Open(adminMapDoc, string.Empty);

                // set the first map as the active view
                m_adminMap = mapDoc.get_Map(0);
                mapDoc.SetActiveView((IActiveView)m_adminMap);
                mapDoc.Close();

                m_mapcontrol.Map = m_adminMap;
            }
        }