/// <summary>
        /// Call the Service Area solver and display the results
        /// </summary>
        /// <param name="sender">Sender of the event</param>
        /// <param name="e">Event</param>
        private void btnSolve_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            lstOutput.Items.Clear();

            IGPMessages gpMessages = new GPMessagesClass();

            try
            {
                lstOutput.Items.Clear();
                lstOutput.Items.Add("Solving...");

                ConfigureSolverSettings();

                if (m_NAContext.Solver.Solve(m_NAContext, gpMessages, null))
                {
                    lstOutput.Items.Add("Partial Solve Generated.");
                }

                DisplayOutput();
            }
            catch (Exception ee)
            {
                lstOutput.Items.Add("Failure: " + ee.Message);
            }

            lstOutput.Items.Add(GetGPMessagesAsString(gpMessages));

            RefreshMapDisplay();

            this.Cursor = Cursors.Default;
        }
		/// <summary>
		/// Call the OD cost matrix solver and display the results
		/// </summary>
		/// <param name="sender">Sender of the event</param>
		/// <param name="e">Event</param>
		private void cmdSolve_Click(object sender, EventArgs e)
		{
            IGPMessages gpMessages = new GPMessagesClass();
            try
			{
				lstOutput.Items.Clear();
				cmdSolve.Text = "Solving...";

				SetSolverSettings();

				// Solve
				if (!m_NAContext.Solver.Solve(m_NAContext, gpMessages, null))
					lstOutput.Items.Add("Partial Result");

				DisplayOutput();

				// Zoom to the extent of the route
				IGeoDataset gDataset = m_NAContext.NAClasses.get_ItemByName("ODLines") as IGeoDataset;
				IEnvelope envelope = gDataset.Extent;
				if (!envelope.IsEmpty)
				{
					envelope.Expand(1.1, 1.1, true);
					axMapControl.Extent = envelope;
				}

				axMapControl.Refresh();
			}
			catch (Exception ex)
			{
                lstOutput.Items.Add("Failure: " + ex.Message);
            }

            lstOutput.Items.Add(GetGPMessagesAsString(gpMessages));
            cmdSolve.Text = "Find OD Cost Matrix";
		}
Exemplo n.º 3
0
        /// <summary>
        /// Call VRP solver and display the results
        /// </summary>
        /// <param name="sender">Sender of the event</param>
        /// <param name="e">Event</param>
        private void cmdSolve_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            listOutput.Items.Clear();

            IGPMessages gpMessages = new GPMessagesClass();

            try
            {
                listOutput.Items.Add("Solving...");

                SetSolverSettings();

                // Solve
                m_NAContext.Solver.Solve(m_NAContext, gpMessages, null);

                // Get the VRP output
                DisplayOutput();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            listOutput.Items.Add(GetGPMessagesAsString(gpMessages));
            cmdSolve.Text = "Find VRP Solution";

            RefreshMapDisplay();

            this.Cursor = Cursors.Default;
        }
Exemplo n.º 4
0
        private void btnSolve_Click(object sender, EventArgs e)
        {
            this.toolStripStatusLabel1.Text = "Working...";
            this.Cursor = Cursors.WaitCursor;
            lbOutput.Items.Clear();

            ConfigureSolverSettings();

            try
            {
                IGPMessages gpMessages = new GPMessagesClass();
                if (m_naContext.Solver.Solve(m_naContext, gpMessages, null))
                {
                    LoadListboxAfterPartialSolve(gpMessages);
                }
                else
                {
                    LoadListboxAfterSuccessfulSolve();
                }
            }
            catch (Exception ex)
            {
                lbOutput.Items.Add("Solve Failed: " + ex.Message);
            }

            UpdateMapDisplayAfterSolve();

            this.Cursor = Cursors.Default;
            this.toolStripStatusLabel1.Text = "Done!";
        }
        /// <summary>
        /// Call the Service Area solver and display the results
        /// </summary>
        /// <param name="sender">Sender of the event</param>
        /// <param name="e">Event</param>
        private void btnSolve_Click(object sender, EventArgs e)
		{
			this.Cursor = Cursors.WaitCursor;
			lstOutput.Items.Clear();

            IGPMessages gpMessages = new GPMessagesClass();
            try
            {
                lstOutput.Items.Clear();
                lstOutput.Items.Add("Solving...");

                ConfigureSolverSettings();

				if (m_NAContext.Solver.Solve(m_NAContext, gpMessages, null))
			        lstOutput.Items.Add("Partial Solve Generated.");

                DisplayOutput();

            }
			catch (Exception ee)
			{
                lstOutput.Items.Add("Failure: " + ee.Message);
            }

            lstOutput.Items.Add(GetGPMessagesAsString(gpMessages));

            RefreshMapDisplay();

			this.Cursor = Cursors.Default;
		}
Exemplo n.º 6
0
        public bool ShowModal(INALayer naLayer)
        {
            m_okClicked = false;

            // Get the NAContext and NetworkDataset
            INAContext      naContext      = naLayer.Context;
            INetworkDataset networkDataset = naContext.NetworkDataset;

            // Setup the window based on the current NALayer settings
            PopulateControls(naLayer);
            tabPropPages.SelectedIndex = 1;
            this.Text = ((ILayer)naLayer).Name + " Properties";

            this.ShowDialog();
            if (m_okClicked)
            {
                // Update the layer properties based on the items chosen
                UpdateNALayer(naLayer);

                // Update the Context so it can respond to changes made to the solver settings
                IGPMessages       gpMessages       = new GPMessagesClass();
                IDENetworkDataset deNetworkDataset = ((IDatasetComponent)networkDataset).DataElement as IDENetworkDataset;
                naContext.Solver.UpdateContext(naContext, deNetworkDataset, gpMessages);
            }

            return(m_okClicked);
        }
        private static INAODCostMatrix Solve(INAContext context, INAODCostMatrixSolver2 odSolver)
        {
            // Set the solver to generate a matrix.
            odSolver.MatrixResultType = esriNAODCostMatrixType.esriNAODCostMatrixFull;
            odSolver.PopulateODLines  = false;

            // Solve
            IGPMessages gpMessages = new GPMessagesClass();

            try
            {
                context.Solver.Solve(context, gpMessages, null);
            }
            catch (Exception e)
            {
                var gpMessagesString = GenerateStringOfAllGpMessages(gpMessages);
                throw new InvalidOdLayerException($"Solve exception message: {e.Message}{Environment.NewLine}" +
                                                  $"Returned GPMessages are as follows:{Environment.NewLine}{gpMessagesString}");
            }

            var odCostMatrix = context.Result as INAODCostMatrix;

            if (!context.Result.HasValidResult || odCostMatrix == null)
            {
                throw new InvalidOdLayerException("Valid result could not be generated. Is something wrong with your layer? Try solving it in ArcMap.");
            }

            return(odCostMatrix);
        }
Exemplo n.º 8
0
        private void cmdSolve_Click(object sender, EventArgs e)
        {
            try
            {
                this.lstOutput.Items.Clear();
                this.lstOutput.Items.Add("Solving...");
                this.SetSolverSettings();
                IGPMessages messages = new GPMessagesClass();
                if (!this.m_pNAContext.Solver.Solve(this.m_pNAContext, messages, null))
                {
                    this.GetCFOutput("CFRoutes");
                }
                else
                {
                    this.lstOutput.Items.Add("Partial Result");
                }
                if (messages != null)
                {
                    for (int i = 0; i < messages.Count; i++)
                    {
                        esriGPMessageType type = messages.GetMessage(i).Type;
                        if (type != esriGPMessageType.esriGPMessageTypeWarning)
                        {
                            if (type != esriGPMessageType.esriGPMessageTypeError)
                            {
                                goto Label_0116;
                            }
                            this.lstOutput.Items.Add("Error " + messages.GetMessage(i).ErrorCode.ToString() + " " +
                                                     messages.GetMessage(i).Description);
                        }
                        else
                        {
                            this.lstOutput.Items.Add("Warning " + messages.GetMessage(i).Description);
                        }
                        continue;
Label_0116:
                        this.lstOutput.Items.Add("Information " + messages.GetMessage(i).Description);
                    }
                }
                IGeoDataset dataset = this.m_pNAContext.NAClasses.get_ItemByName("CFRoutes") as IGeoDataset;
                IEnvelope   extent  = dataset.Extent;
                if (!extent.IsEmpty)
                {
                    extent.Expand(1.1, 1.1, true);
                }
                (this.m_pFocusMap as IActiveView).Extent = extent;
                (this.m_pFocusMap as IActiveView).Refresh();
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
                this.cmdSolve.Text = "Find Closest Faclities";
            }
        }
Exemplo n.º 9
0
        private void btnGO_Click(object sender, System.EventArgs e)
        {
            int facilityCount = 0, cutOffVal = 0;

            if (txtFacilityCount.Text.Length > 0)
            {
                facilityCount = Convert.ToInt32(txtFacilityCount.Text);
            }

            if (txtCutOff.Text.Length > 0)
            {
                cutOffVal = Convert.ToInt32(txtCutOff.Text);
            }

            pGISHelper.SetSolverSettings(ref m_pNAContext, cutOffVal, facilityCount, cmbCost.Text, chkOneWay.Checked, chkHierachy.Checked);


            IGPMessages pGPMessages = new GPMessagesClass();

            IGPMessage pGPMessage = null;

            if (m_pNAContext.Solver.Solve(m_pNAContext, pGPMessages, null) == false)
            {
                for (int ii = 0; ii < pGPMessages.Count; ii++)
                {
                    pGPMessage = pGPMessages.GetMessage(ii);

                    MessageBox.Show(pGPMessage.Description);
                }

                pGISHelper.GetCFOutput("CFRoutes", ref m_pNAContext);
            }


            //'Zoom to the extent of the route
            IGeoDataset pGDS;
            IEnvelope   pEnv;

            pGDS = m_pNAContext.NAClasses.get_ItemByName("CFRoutes") as IGeoDataset;


            pEnv = pGDS.Extent;
            if (!pEnv.IsEmpty)
            {
                pEnv.Expand(1.1, 1.1, true);
                pMainFrm.getMapControl().Extent = pEnv;
            }


            pMainFrm.getMapControl().Refresh();
        }
Exemplo n.º 10
0
        internal SupplyRoute FindRoute()
        {
            IFeatureCursor cursor = null;

            try
            {
                IGPMessages gpMessages = new GPMessagesClass();
                SetSolverSettings(this.Attribute);

                if (!m_NAContext.Solver.Solve(m_NAContext, gpMessages, null))
                {
                }

                IFeatureClass routeClass = m_NAContext.NAClasses.get_ItemByName(OUTPUTCLASSNAME) as IFeatureClass;

                cursor = routeClass.Search(null, false);
                IFeature fcRoute = cursor.NextFeature();
                if (fcRoute == null)
                {
                    return(null);
                }

                IPolyline geoRoute           = fcRoute.ShapeCopy as IPolyline;
                IPoint    facilityQueryPoint = geoRoute.FromPoint;

                int         id          = FindFacilityID(facilityQueryPoint);
                SupplyRoute resultRoute = new SupplyRoute()
                {
                    RepoID = id, Route = geoRoute
                };
                return(resultRoute);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ComReleaser.ReleaseCOMObject(cursor);
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// 开始路径查询
        /// </summary>
        private void menuOKRoute_Click(object sender, EventArgs e)
        {
            try
            {
                pPathFinder.loadNANetworkLocations("Stops", pPathFinder.inputFClass, 80);
                IGPMessages gpMessages = new GPMessagesClass();
                bool        flag       = pPathFinder.m_NAContext.Solver.Solve(pPathFinder.m_NAContext, gpMessages, null);

                IFeatureClass routesFC      = pPathFinder.m_NAContext.NAClasses.get_ItemByName("Routes") as IFeatureClass;
                IFeatureLayer pRouteFeature = new FeatureLayerClass();
                pRouteFeature.FeatureClass = routesFC;
                pRouteFeature.Name         = routesFC.AliasName;
                axMapControl1.AddLayer(pRouteFeature, 0);

                axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
            }
            catch
            {
                MessageBox.Show("无路径分析结果", "提示");
                return;
            }
        }
Exemplo n.º 12
0
        //gp的执行
        private void ExecuteGP(IVariantArray parameters, string strToolName)
        {
            ITrackCancel pTrackCancel = null;

            //找到tool
            ESRI.ArcGIS.Geoprocessing.GeoProcessor _geoPro = new GeoProcessor();
            pTrackCancel = new TrackCancelClass();
            IVariantArray pVArray = new VarArrayClass();

            IGPEnvironmentManager pgpEnv = new GPEnvironmentManager();
            IGPMessages           pGpMessages; //= _geoPro.Validate(parameters, false, pgpEnv);
            IGPComHelper          pGPCOMHelper = new GpDispatch();

            //这里是关键,如果不赋值的话,那么就会报错
            IGPEnvironmentManager pEnvMgr = pGPCOMHelper.EnvironmentManager;

            pgpEnv.PersistAll = true;
            pGpMessages       = new GPMessagesClass();

            // Execute the model tool by name.
            _geoPro.Execute(strToolName, parameters, pTrackCancel);
        }
Exemplo n.º 13
0
        private void button1_Click(object sender, System.EventArgs e)
        {
            bool IsPartialSolution;

            IGPMessages pGPMessages=new GPMessagesClass();

             IsPartialSolution = m_pNAContext.Solver.Solve(m_pNAContext, pGPMessages, null);
            if(IsPartialSolution==false){
              //���ҳɹ�

            }

             IGeoDataset pGDS;
             IEnvelope pEnv;

            pGDS=m_pNAContext.NAClasses.get_ItemByName("Routes") as IGeoDataset;
            pEnv = pGDS.Extent;
            pEnv.Expand(1.1, 1.1,true);

            pMainFrm.getMapControl().Extent = pEnv;

               pMainFrm.getMapControl().Refresh();
        }
Exemplo n.º 14
0
        private void button1_Click(object sender, System.EventArgs e)
        {
            bool IsPartialSolution;

            IGPMessages pGPMessages = new GPMessagesClass();

            IsPartialSolution = m_pNAContext.Solver.Solve(m_pNAContext, pGPMessages, null);
            if (IsPartialSolution == false)
            {
                //查找成功
            }

            IGeoDataset pGDS;
            IEnvelope   pEnv;

            pGDS = m_pNAContext.NAClasses.get_ItemByName("Routes") as IGeoDataset;
            pEnv = pGDS.Extent;
            pEnv.Expand(1.1, 1.1, true);

            pMainFrm.getMapControl().Extent = pEnv;

            pMainFrm.getMapControl().Refresh();
        }
        protected override void OnClick()
        {
            try
            {
                //Set a reference to the IGPCommandHelper2 interface.

                IGPToolCommandHelper2 pToolHelper = new GPToolCommandHelperClass() as IGPToolCommandHelper2;

                //Set the tool you want to invoke.
                string toolboxName = GetAssemblyPath() + "\\Parser\\NWI Tools.tbx";
                pToolHelper.SetToolByName(toolboxName, "NWIAttributeParser");

                //Create the messages object and a bool to pass to the InvokeModal method.
                IGPMessages msgs;
                msgs = new GPMessagesClass();
                bool pok = true;

                //Invoke the tool.
                pToolHelper.InvokeModal(0, null, out pok, out msgs);
            }
            catch (Exception e)
            {
            }
        }
		//*********************************************************************************
		// Read the solver settings from the user and solve the Location-Allocation problem
		//*********************************************************************************
		private void cmdSolve_Click(object sender, EventArgs e)
		{
            IGPMessages gpMessages = new GPMessagesClass();
            try
			{
				lstOutput.Items.Clear();
				lstOutput.Items.Add("Solving...");

				SetSolverSettings();

				// Solve
				if (!m_NAContext.Solver.Solve(m_NAContext, gpMessages, null))
				{
					GetLAFacilitiesOutput("Facilities");
					GetLALinesOutput("LALines");
				}
				else
					lstOutput.Items.Add("Partial Result");

				//Zoom to the extent of the route
				IGeoDataset geoDataset = m_NAContext.NAClasses.get_ItemByName("LALines") as IGeoDataset;
				IEnvelope envelope = geoDataset.Extent;
				if (!envelope.IsEmpty)
					envelope.Expand(1.1, 1.1, true);
				axMapControl.Extent = envelope;
				axMapControl.Refresh();
			}

			catch (Exception ee)
			{
                lstOutput.Items.Add("Failure: " + ee.Message);
            }

            lstOutput.Items.Add(GetGPMessagesAsString(gpMessages));
            cmdSolve.Text = "Solve";
        }
        /// <summary>
        /// 最短路径分析
        /// </summary>
        /// <param name="mapControl">地图控件</param>
        /// <param name="gdbfileName">数据库文件</param>
        /// <param name="featureDatasetName">要素集名字</param>
        /// <param name="ndsName">网络数据集名字</param>
        /// <param name="featureClasses">参数要素类及其阈值,其中键值包括:Stops(路线经过结点),Barriers,PolylineBarriers,PolygonBarriers</param>
        /// <param name="isShowDataBase">是否显示网络数据集</param>
        ///  <param name="isShowNalayer">是否显示网络分析图层</param>
        ///  <param name="routeLayer">最近路线图层</param>
        public static bool Short_Path(AxMapControl mapControl, string gdbfileName, string featureDatasetName, string ndsName, IDictionary <string, DecorateRouteFeatureClass> featureClasses, bool isShowDataBase, bool isShowNalayer, ref ILayer routeLayer)
        {
            //首先判断输入的参数要素类是否合法
            if (!FeatureClassKeyIsRight(featureClasses))
            {
                throw new Exception("参数字典错误");
            }
            // mapControl.ClearLayers();
            //打开工作空间
            IFeatureWorkspace pFeatureWorkspace = OpenWorkspace(gdbfileName) as IFeatureWorkspace;

            if (pFeatureWorkspace == null)
            {
                return(false);
            }
            //获取网络数据集
            INetworkDataset pNetworkDataset = OpenNetworkDataset(pFeatureWorkspace as IWorkspace, featureDatasetName, ndsName);

            if (pNetworkDataset == null)
            {
                Debug.Print("无法获取网络数据集");
                return(false);
            }
            //获取网络分析上下文
            INAContext pNAContext = CreateNAContext(pNetworkDataset);
            //打开节点图层 一般和网络数据集放置在一起 名称是xxx_Junctions
            IFeatureClass pVertexFC = pFeatureWorkspace.OpenFeatureClass(ndsName + "_Junctions");
            ILayer        pLayer    = null;

            // 显示网络数据集图层
            if (isShowDataBase)
            {
                INetworkLayer pNetworkLayer = new NetworkLayerClass();
                pNetworkLayer.NetworkDataset = pNetworkDataset;
                pLayer      = pNetworkLayer as ILayer;
                pLayer.Name = "网络数据集";
                mapControl.AddLayer(pLayer, 0);
            }
            //创建网络分析图层
            INALayer naLayer = pNAContext.Solver.CreateLayer(pNAContext);

            //显示网络分析图层
            if (isShowNalayer)
            {
                pLayer                  = naLayer as ILayer;
                pLayer.Name             = pNAContext.Solver.DisplayName;
                pLayer.SpatialReference = mapControl.SpatialReference;
                mapControl.AddLayer(pLayer, 0);
                IActiveView        pActiveView        = mapControl.ActiveView;
                IMap               pMap               = pActiveView.FocusMap;
                IGraphicsContainer pGraphicsContainer = pMap as IGraphicsContainer;
                mapControl.Refresh();
            }
            INASolver naSolver = pNAContext.Solver;

            //插入相关数据
            foreach (var value in featureClasses)
            {
                LoadNANetWorkLocations(pNAContext, value.Key, value.Value.FeatureClass, value.Value.SnapTolerance);
            }
            //插入经过点
            //LoadNANetWorkLocations(pNAContext,"Stops", stopFeatureClass, 30);
            //插入障碍点
            //    LoadNANetWorkLocations(pNAContext, "Barriers", barriesFeatureClass, 30);
            IGPMessages gpMessages = new GPMessagesClass();

            //  SetSolverSettings(pNAContext);
            //寻找最短路径
            try
            {
                pNAContext.Solver.Solve(pNAContext, gpMessages, new CancelTrackerClass());
                routeLayer = naLayer.get_LayerByNAClassName("Routes");
            }
            catch (Exception e)
            {
                Debug.Print("无法找到最短路径:" + e.Message);
                return(false);
            }
            mapControl.Refresh();
            if (gpMessages != null)
            {
                for (int i = 0; i < gpMessages.Count; i++)
                {
                    switch (gpMessages.GetMessage(i).Type)
                    {
                    case esriGPMessageType.esriGPMessageTypeError:
                        Debug.Print("错误 " + gpMessages.GetMessage(i).ErrorCode.ToString() + " " + gpMessages.GetMessage(i).Description);
                        break;

                    case esriGPMessageType.esriGPMessageTypeWarning:
                        Debug.Print("警告 " + gpMessages.GetMessage(i).Description);
                        break;

                    default:
                        Debug.Print("信息 " + gpMessages.GetMessage(i).Description);
                        break;
                    }
                }
            }
            return(true);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Occurs when this command is clicked
        /// </summary>
        public override void OnClick()
        {
            // TODO: Add ShortPathSolveCommand.OnClick implementation
            string            name        = NetWorkAnalysClass.getPath(path) + "\\data\\Geodatabase.gdb";
            IFeatureWorkspace pFWorkspace = NetWorkAnalysClass.OpenWorkspace(name) as IFeatureWorkspace;

            //"RouteNetwork", "BaseData"参数不可更改
            networkDataset = NetWorkAnalysClass.OpenPathNetworkDataset(pFWorkspace as IWorkspace, "RouteNetwork", "BaseData");
            m_NAContext    = NetWorkAnalysClass.CreatePathSolverContext(networkDataset);
            //通过网络数据集创建网络分析上下文
            //打开要素数据集
            inputFClass   = pFWorkspace.OpenFeatureClass("Stops");
            barriesFClass = pFWorkspace.OpenFeatureClass("Barries");
            if (IfLayerExist("NetworkDataset") == false)
            {
                ILayer        layer;
                INetworkLayer networkLayer;
                networkLayer = new NetworkLayerClass();
                networkLayer.NetworkDataset = networkDataset;
                layer      = networkLayer as ILayer;
                layer.Name = "NetworkDataset";
                m_hookHelper.ActiveView.FocusMap.AddLayer(layer);
                layer.Visible = false;
            }
            if (IfLayerExist(m_NAContext.Solver.DisplayName) == true)
            {
                for (int i = 0; i < m_hookHelper.FocusMap.LayerCount; i++)
                {
                    if (m_hookHelper.FocusMap.get_Layer(i).Name == m_NAContext.Solver.DisplayName)
                    {
                        m_hookHelper.FocusMap.DeleteLayer(m_hookHelper.FocusMap.get_Layer(i));
                    }
                }
            }
            INALayer naLayer = m_NAContext.Solver.CreateLayer(m_NAContext);
            ILayer   pLayer  = naLayer as ILayer;

            pLayer.Name = m_NAContext.Solver.DisplayName;
            m_hookHelper.ActiveView.FocusMap.AddLayer(pLayer);
            if (inputFClass.FeatureCount(null) < 2)
            {
                MessageBox.Show("只有一个站点,不能进行路径分析!");
                return;
            }
            IGPMessages gpMessages = new GPMessagesClass();

            //加载站点要素,并设置容差
            NetWorkAnalysClass.LoadNANetworkLocations("Stops", inputFClass, m_NAContext, 80);
            //加载障碍点要素,并设置容差
            NetWorkAnalysClass.LoadNANetworkLocations("Barriers", barriesFClass, m_NAContext, 5);
            INASolver naSolver = m_NAContext.Solver;//创建网络分析对象

            try
            {
                naSolver.Solve(m_NAContext, gpMessages, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show("未能找到有效路径" + ex.Message, "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                return;
            }
            for (int i = 0; i < m_hookHelper.FocusMap.LayerCount; i++)
            {
                if (m_hookHelper.FocusMap.get_Layer(i).Name == m_NAContext.Solver.DisplayName)
                {
                    ICompositeLayer pCompositeLayer = m_hookHelper.FocusMap.get_Layer(i) as ICompositeLayer;
                    {
                        for (int t = 0; t < pCompositeLayer.Count; t++)
                        {
                            ILayer pResultLayer = pCompositeLayer.get_Layer(t);
                            if (pResultLayer.Name == "Stops" || pResultLayer.Name == "Barriers")
                            {
                                pResultLayer.Visible = false;
                                continue;
                            }
                        }
                    }
                }
            }
            IGeoDataset geoDataset;
            IEnvelope   envelope;

            geoDataset = m_NAContext.NAClasses.get_ItemByName("Routes") as IGeoDataset;
            envelope   = geoDataset.Extent;
            if (!envelope.IsEmpty)
            {
                envelope.Expand(1.1, 1.1, true);
            }
            m_hookHelper.ActiveView.Extent = envelope;
            m_hookHelper.ActiveView.Refresh();
        }
Exemplo n.º 19
0
        public override void OnClick()
        {
            // TODO: Add ShortPathSolveCommand.OnClick implementation
            //string name = NetWorkAnalysClass.getPath(path) + "\\data\\HuanbaoGeodatabase.gdb";
            IFeatureWorkspace pFWorkspace = NetWorkAnalysClass.OpenWorkspace(_name) as IFeatureWorkspace;

            //"RouteNetwork", "BaseData"�������ɸ���
            networkDataset = NetWorkAnalysClass.OpenPathNetworkDataset(pFWorkspace as IWorkspace, _networkDatasetName, _featureDatasetName);
            m_NAContext    = NetWorkAnalysClass.CreatePathSolverContext(networkDataset);
            //ͨ���������ݼ������������������
            //��Ҫ�����ݼ�
            inputFClass   = pFWorkspace.OpenFeatureClass("Stops");
            barriesFClass = pFWorkspace.OpenFeatureClass("Barries");
            if (IfLayerExist("NetworkDataset") == false)
            {
                ILayer        layer;
                INetworkLayer networkLayer;
                networkLayer = new NetworkLayerClass();
                networkLayer.NetworkDataset = networkDataset;
                layer      = networkLayer as ILayer;
                layer.Name = "NetworkDataset";
                m_hookHelper.ActiveView.FocusMap.AddLayer(layer);
                layer.Visible = false;
            }
            if (IfLayerExist(m_NAContext.Solver.DisplayName) == true)
            {
                for (int i = 0; i < m_hookHelper.FocusMap.LayerCount; i++)
                {
                    if (m_hookHelper.FocusMap.get_Layer(i).Name == m_NAContext.Solver.DisplayName)
                    {
                        m_hookHelper.FocusMap.DeleteLayer(m_hookHelper.FocusMap.get_Layer(i));
                    }
                }
            }
            INALayer naLayer = m_NAContext.Solver.CreateLayer(m_NAContext);
            ILayer   pLayer  = naLayer as ILayer;

            pLayer.Name = m_NAContext.Solver.DisplayName;
            m_hookHelper.ActiveView.FocusMap.AddLayer(pLayer);
            if (inputFClass.FeatureCount(null) < 2)
            {
                MessageBox.Show("Only one point, can not execute !");
                return;
            }
            IGPMessages gpMessages = new GPMessagesClass();

            //����վ��Ҫ�أ��������ݲ�
            NetWorkAnalysClass.LoadNANetworkLocations("Stops", inputFClass, m_NAContext, 80);
            //�����ϰ���Ҫ�أ��������ݲ�
            NetWorkAnalysClass.LoadNANetworkLocations("Barriers", barriesFClass, m_NAContext, 5);
            INASolver naSolver = m_NAContext.Solver;//���������������

            try
            {
                naSolver.Solve(m_NAContext, gpMessages, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show("δ���ҵ���Ч·��" + ex.Message, "��ʾ", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                return;
            }
            for (int i = 0; i < m_hookHelper.FocusMap.LayerCount; i++)
            {
                if (m_hookHelper.FocusMap.get_Layer(i).Name == m_NAContext.Solver.DisplayName)
                {
                    ICompositeLayer pCompositeLayer = m_hookHelper.FocusMap.get_Layer(i) as ICompositeLayer;
                    {
                        for (int t = 0; t < pCompositeLayer.Count; t++)
                        {
                            ILayer pResultLayer = pCompositeLayer.get_Layer(t);
                            if (pResultLayer.Name == "Stops" || pResultLayer.Name == "Barriers")
                            {
                                pResultLayer.Visible = false;
                                continue;
                            }
                        }
                    }
                }
            }
            IGeoDataset geoDataset;

            //IEnvelope envelope;
            geoDataset = m_NAContext.NAClasses.get_ItemByName("Routes") as IGeoDataset;
            var envelope = geoDataset.Extent;

            if (!envelope.IsEmpty)
            {
                envelope.Expand(1.1, 1.1, true);
            }
            m_hookHelper.ActiveView.Extent = envelope;
            m_hookHelper.ActiveView.Refresh();
        }
Exemplo n.º 20
0
        private void btnGO_Click(object sender, System.EventArgs e)
        {
            int facilityCount=0,cutOffVal=0;

            if(txtFacilityCount.Text.Length>0)
                facilityCount=Convert.ToInt32(txtFacilityCount.Text);

            if(txtCutOff.Text.Length>0)
                cutOffVal=Convert.ToInt32(txtCutOff.Text);

            pGISHelper.SetSolverSettings(ref m_pNAContext,cutOffVal,facilityCount,cmbCost.Text,chkOneWay.Checked,chkHierachy.Checked);

            IGPMessages pGPMessages=new GPMessagesClass();

            IGPMessage pGPMessage=null;

            if(m_pNAContext.Solver.Solve(m_pNAContext, pGPMessages, null)==false){

                for(int ii=0;ii<pGPMessages.Count;ii++)
                {
                    pGPMessage=pGPMessages.GetMessage(ii);

                    MessageBox.Show(pGPMessage.Description);
                }

                pGISHelper.GetCFOutput("CFRoutes",ref m_pNAContext);

            }

              //'Zoom to the extent of the route
            IGeoDataset pGDS;
            IEnvelope pEnv;

             pGDS = m_pNAContext.NAClasses.get_ItemByName("CFRoutes") as IGeoDataset;

             pEnv = pGDS.Extent;
            if(!pEnv.IsEmpty)
            {
                 pEnv.Expand(1.1, 1.1, true);
                 pMainFrm.getMapControl().Extent = pEnv;
             }

            pMainFrm.getMapControl().Refresh();
        }
Exemplo n.º 21
0
        //利用quickexport进行数据转换  dwg-->mdb
        private void QuickImportTopdb(string strSrcDwg, string strdesPdb)
        {
            ITrackCancel pTrackCancel = null;

            //找到tool
            ESRI.ArcGIS.Geoprocessor.Geoprocessor _geoPro = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();
            //ESRI.ArcGIS.Geoprocessing.IGeoProcessor _geoPro = new ESRI.ArcGIS.Geoprocessing.GeoProcessorClass();
            pTrackCancel = new TrackCancelClass();
            IVariantArray pVArray    = new VarArrayClass();
            IVariantArray parameters = new VarArrayClass();

            parameters.Add("ACAD," + strSrcDwg);
            string strtoolName = "";

            //parameters.Add("RUNTIME_MACROS,");
            //parameters.Add("METAFILE,acad,_EXPAND_BLOCKS,yes,ACAD_IN_USE_BLOCK_HEADER_LAYER,yes,"
            //+ "ACAD_IN_RESOLVE_ENTITY_COLOR,yes,_EXPAND_VISIBLE,yes,_READ_AS_2_5D,no,"
            //+ "_BULGES_AS_ARCS,no,_STORE_BULGE_INFO,no,_READ_PAPER_SPACE,no,"
            //+ "ACAD_IN_READ_GROUPS,no,_IGNORE_UCS,no,_ACADPreserveComplexHatches,no,"
            //+ "_MERGE_SCHEMAS,YES,");
            //parameters.Add("META_MACROS,");
            //parameters.Add("Source_EXPAND_BLOCKS,yes,"
            //+ "SourceACAD_IN_USE_BLOCK_HEADER_LAYER,yes,SourceACAD_IN_RESOLVE_ENTITY_COLOR,yes"
            //+ ",Source_EXPAND_VISIBLE,yes,Source_READ_AS_2_5D,no,Source_BULGES_AS_ARCS,no,"
            //+ "Source_STORE_BULGE_INFO,no,Source_READ_PAPER_SPACE,no,SourceACAD_IN_READ_GROUPS,no"
            //+ ",Source_IGNORE_UCS,no,Source_ACADPreserveComplexHatches,no,METAFILE,acad,COORDSYS,,IDLIST,,");
            //parameters.Add("__FME_DATASET_IS_SOURCE__,true");
            //string param = "__FME_DATASET_IS_SOURCE__,true";
            //parameters.Add(param);
            parameters.Add(strdesPdb + "\\..\\tmp.mdb");


            strtoolName = "QuickImport_interop";

            IGPEnvironmentManager pgpEnv = new GPEnvironmentManager();
            IGPMessages           pGpMessages; //= _geoPro.Validate(parameters, false, pgpEnv);
            IGPComHelper          pGPCOMHelper = new GpDispatch();

            //这里是关键,如果不赋值的话,那么就会报错
            IGPEnvironmentManager pEnvMgr = pGPCOMHelper.EnvironmentManager;

            pgpEnv.PersistAll       = true;
            pGpMessages             = new GPMessagesClass();
            _geoPro.OverwriteOutput = true;
            //Execute the model tool by name.
            _geoPro.Execute(strtoolName, parameters, pTrackCancel);
            //QuickImport qi = new QuickImport();
            //qi.Input = txtSource.Text;
            //qi.Output = txtTarget.Text;
            //_geoPro.Execute(qi, pTrackCancel);
            ESRI.ArcGIS.ConversionTools.FeatureClassToShapefile FCTS = new ESRI.ArcGIS.ConversionTools.FeatureClassToShapefile();
            FCTS.Output_Folder = strdesPdb;
            IWorkspaceFactory pWF        = new AccessWorkspaceFactoryClass();
            IWorkspace        pWorkSpace = pWF.OpenFromFile(strdesPdb + "\\..\\tmp.mdb", 0);
            IEnumDatasetName  pED        = pWorkSpace.get_DatasetNames(esriDatasetType.esriDTFeatureClass);
            IDatasetName      pDataSet   = pED.Next();

            while (pDataSet != null)
            {
                if ((pWorkSpace as IFeatureWorkspace).OpenFeatureClass(pDataSet.Name).FeatureType != esriFeatureType.esriFTSimple)//排除注记等
                {
                    pDataSet = pED.Next();
                    continue;
                }
                //_geoPro = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();
                //_geoPro.OverwriteOutput = true;
                FCTS.Input_Features = pWorkSpace.PathName + "\\" + pDataSet.Name;
                _geoPro.Execute(FCTS, pTrackCancel);
                pDataSet = pED.Next();
            }


            Stream       s  = new System.IO.FileStream("d:\\qimport.txt", FileMode.Create);
            StreamWriter sw = new StreamWriter(s);

            for (int i = 0; i < _geoPro.MessageCount; i++)
            {
                sw.WriteLine(_geoPro.GetMessage(i));
            }
            sw.Close();
            s.Close();
        }
Exemplo n.º 22
0
        /// <summary>
        /// Call the OD cost matrix solver and display the results
        /// </summary>
        /// <param name="sender">Sender of the event</param>
        /// <param name="e">Event</param>
        private void cmdSolve_Click(object sender, EventArgs e)
        {
            this.toolStripStatusLabel1.Text = "Working...";
            Initialize();
            try
            {
                lbOutput.Items.Clear();
                cmdSolve.Text = "Solving...";

                SetSolverSettings();

                // Solve
                IGPMessages gpMessages = new GPMessagesClass();
                if (!m_NAContext.Solver.Solve(m_NAContext, gpMessages, null))
                {
                    // Get the ODLines output
                    GetODOutput();
                }
                else
                {
                    lbOutput.Items.Add("Partial Result");
                }

                // Display Error/Warning/Informative messages
                if (gpMessages != null)
                {
                    for (int i = 0; i < gpMessages.Count; i++)
                    {
                        switch (gpMessages.GetMessage(i).Type)
                        {
                        case esriGPMessageType.esriGPMessageTypeError:
                            lbOutput.Items.Add("Error " + gpMessages.GetMessage(i).ErrorCode.ToString() + " " + gpMessages.GetMessage(i).Description);
                            break;

                        case esriGPMessageType.esriGPMessageTypeWarning:
                            lbOutput.Items.Add("Warning " + gpMessages.GetMessage(i).Description);
                            break;

                        default:
                            lbOutput.Items.Add("Information " + gpMessages.GetMessage(i).Description);
                            break;
                        }
                    }
                }

                // Zoom to the extent of the route
                IGeoDataset gDataset = m_NAContext.NAClasses.get_ItemByName("ODLines") as IGeoDataset;
                IEnvelope   envelope = gDataset.Extent;
                if (!envelope.IsEmpty)
                {
                    envelope.Expand(1.1, 1.1, true);
                    axMapControl.Extent = envelope;
                }

                axMapControl.Refresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                cmdSolve.Text = "Find OD Cost Matrix";
            }
            this.toolStripStatusLabel1.Text = "Done!";
        }
		/// <summary>
		/// Call the OD cost matrix solver and display the results
		/// </summary>
		/// <param name="sender">Sender of the event</param>
		/// <param name="e">Event</param>
		private void cmdSolve_Click(object sender, EventArgs e)
		{
            IGPMessages gpMessages = new GPMessagesClass();
            try
			{
				lstOutput.Items.Clear();
				cmdSolve.Text = "Solving...";

				SetSolverSettings();

				// Solve
				if (!m_NAContext.Solver.Solve(m_NAContext, gpMessages, null))
					lstOutput.Items.Add("Partial Result");

				DisplayOutput();

				// Zoom to the extent of the route
				IGeoDataset gDataset = m_NAContext.NAClasses.get_ItemByName("ODLines") as IGeoDataset;
				IEnvelope envelope = gDataset.Extent;
				if (!envelope.IsEmpty)
				{
					envelope.Expand(1.1, 1.1, true);
					axMapControl.Extent = envelope;
				}

				axMapControl.Refresh();
			}
			catch (Exception ex)
			{
                lstOutput.Items.Add("Failure: " + ex.Message);
            }

            lstOutput.Items.Add(GetGPMessagesAsString(gpMessages));
            cmdSolve.Text = "Find OD Cost Matrix";
		}
		/// <summary>
		/// Call VRP solver and display the results
		/// </summary>
		/// <param name="sender">Sender of the event</param>
		/// <param name="e">Event</param>
		private void cmdSolve_Click(object sender, EventArgs e)
		{
            this.Cursor = Cursors.WaitCursor;
            listOutput.Items.Clear();

            IGPMessages gpMessages = new GPMessagesClass();
            try
			{
                listOutput.Items.Add("Solving...");

				SetSolverSettings();

				// Solve
				m_NAContext.Solver.Solve(m_NAContext, gpMessages, null);

				// Get the VRP output
                DisplayOutput();
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}

            listOutput.Items.Add(GetGPMessagesAsString(gpMessages));
            cmdSolve.Text = "Find VRP Solution";

            RefreshMapDisplay();

            this.Cursor = Cursors.Default;
        }
Exemplo n.º 25
0
        /// <summary>
        /// Called when a step of this type is executed in the workflow.
        /// </summary>
        /// <param name="JobID">ID of the job being executed</param>
        /// <param name="StepID">ID of the step being executed</param>
        /// <param name="argv">Array of arguments passed into the step's execution</param>
        /// <param name="ipFeedback">Feedback object to return status messages and files</param>
        /// <returns>Return code of execution for workflow path traversal</returns>
        public int Execute(int jobID, int stepID, ref object[] argv, ref IJTXCustomStepFeedback ipFeedback)
        {
#if (!SERVER)
            StatusForm sfd = null;
#endif
            bool success = true;

            // Reset the message logging
            this.ClearCachedLogMessages();

            try
            {
                Log("ExecuteGPTool.Execute beginning..");

                // Define variables
                string strToolboxPath = "";
                string strTool = "";
                string strToolboxRoot = "";
                string strToolboxName = "";

                // Get the toolbox name (check for errors)
                if (!StepUtilities.GetArgument(ref argv, "toolboxpath", true, out strToolboxPath) || strToolboxPath.Equals(String.Empty))
                {
                    success = false;
                    Log("Error getting 'toolboxpath' argument");
#if (!SERVER)
                    MessageBox.Show("Missing toolbox argument.");
#endif
                }
                // Get the tool name (check for errors)
                else if (!StepUtilities.GetArgument(ref argv, "tool", true, out strTool) || strTool.Equals(String.Empty))
                {
                    success = false;
                    Log("Error getting 'tool' argument");
#if (!SERVER)
                    MessageBox.Show("Missing tool argument.");
#endif
                }
                else
                {
#if (!SERVER)
                    // Display status dialog
                    sfd = new StatusForm();
                    sfd.ToolName = strTool;
                    sfd.Show();
                    sfd.Refresh();
#endif

                    // Get directory of toolbox
                    strToolboxRoot = Path.GetDirectoryName(strToolboxPath);
                    // Get toolbox name without .tbx extension
                    strToolboxName = Path.GetFileNameWithoutExtension(strToolboxPath);

                    // Open toolbox and tool
                    IWorkspaceFactory pToolboxWorkspaceFactory = new ToolboxWorkspaceFactoryClass();
                    IToolboxWorkspace pToolboxWorkspace = pToolboxWorkspaceFactory.OpenFromFile(strToolboxRoot, 0) as IToolboxWorkspace;
                    IGPToolbox pGPToolbox = pToolboxWorkspace.OpenToolbox(strToolboxName);
                    IGPTool pGPTool = pGPToolbox.OpenTool(strTool);

                    Log("ExecuteGPTool.Execute successfully opened Tool " + strTool + " in Toolbox " + strToolboxPath + "..");

                    // Generate the arrays for parameters
                    IVariantArray parameters = new VarArrayClass();  // For Execute method
                    ESRI.ArcGIS.esriSystem.IArray pParameterArray = pGPTool.ParameterInfo;  // For Validate and InvokeModal methods

                    // Get parameter "pairs"; "GetDoubleArguments" supports the GP-style,
                    // two-colon argument strings, like "/param:tool_param_name:tool_param_value"
                    string[] argNames;
                    string[] argValues;
                    if (StepUtilities.GetDoubleArguments(ref argv, "param", true, out argNames, out argValues))
                    {
                        // Stash away the variables that were passed in
                        Dictionary<string, string> argTable = new Dictionary<string, string>();
                        for (int i = 0; i < argNames.Length; i++)
                        {
                            string uppercaseName = argNames[i].ToUpper();
                            argTable[uppercaseName] = argValues[i];
                        }

                        // The GP tool's parameter list may include parameters that weren't specified in the
                        // JTX step arguments.  So iterate through the tool's parameters, setting the values
                        // from the input where you can.  Where no value was passed in, just skip the
                        // parameter and go with the default.
                        for (int i = 0; i < pParameterArray.Count; i++)
                        {
                            IGPParameter pGPParam = (IGPParameter)pParameterArray.get_Element(i);
                            IGPParameterEdit pGPParamEdit = (IGPParameterEdit)pGPParam;
                            string uppercaseName = pGPParam.Name.ToUpper();

                            // Override the default value, if something was passed in
                            if (argTable.ContainsKey(uppercaseName))
                            {
                                IGPDataType pGPType = pGPParam.DataType;
                                string strValue = argTable[uppercaseName];
                                pGPParamEdit.Value = pGPType.CreateValue(strValue);

                                Log("ExecuteGPTool.Execute Tool Parameter = " + uppercaseName + ", Value = " + strValue + "..");
                            }

                            // Always stash away the current parameter value, since we need the complete list
                            // for "Execute" below.
                            parameters.Add(pGPParam.Value);
                        }
                    }

                    Log("ExecuteGPTool.Execute successfully setup parameter values..");


                    // Initialize the geoprocessor
                    IGeoProcessor pGP = new GeoProcessorClass();

                    // Create callback object for GP messages
                    JTXGPCallback pCallback = new JTXGPCallback();

                    // Set up the geoprocessor
                    pGP.AddToolbox(strToolboxPath);
                    pGP.RegisterGeoProcessorEvents(pCallback);

                    Log("ExecuteGPTool.Execute created and registered GeoProcessor..");

                    // Create the messages object and a bool to pass to InvokeModal method
                    IGPMessages pGPMessages = pGPTool.Validate(pParameterArray, true, null);
                    IGPMessages pInvokeMessages = new GPMessagesClass();
                    string strMessage = "";

                    // Check for error messages
                    if (pGPMessages.MaxSeverity == esriGPMessageSeverity.esriGPMessageSeverityError)
                    {
#if (!SERVER)
                        // Only want to invoke a modal dialog if we're running on a workstation
                        // Set a reference to IGPCommandHelper2 interface
                        IGPToolCommandHelper2 pToolHelper = new GPToolCommandHelperClass() as IGPToolCommandHelper2;
                        pToolHelper.SetTool(pGPTool);
                        bool pOK = true;

                        // Open tool GUI
                        pToolHelper.InvokeModal(0, pParameterArray, out pOK, out pInvokeMessages);
                        if (pOK == true)
                        {
                            bool bFailureMessages;
                            strMessage = ConvertGPMessagesToString(pInvokeMessages, out bFailureMessages);
                            success = !bFailureMessages;
                        }
                        else
                        {
                            success = false;
                        }
#else
                        Log("ExecuteGPTool.Execute Tool Validate failed..");

                        // If we're running on a server, then just indicate a failure.  (Someone will
                        // have to use the JTX application to fix the step arguments, if they can be
                        // fixed.)
                        success = false;
#endif
                    }
                    else  // If there are no error messages, execute the tool
                    {
                        Log("ExecuteGPTool.Execute successfully validated parameter values, About to Execute..");
                        IGPMessages ipMessages = new GPMessagesClass();
                        try
                        {
                            pGPTool.Execute(pParameterArray, null, new GPEnvironmentManagerClass(), ipMessages);
                            Log("ExecuteGPTool.Execute completed call to pGPTool.Execute()");
                        }
                        catch (System.Runtime.InteropServices.COMException ex)
                        {
                            success = false;
                            Log("ExecuteGPTool.Execute Tool Execute failed, Message = " + ex.Message + ", DataCode = " + ex.ErrorCode + ", Data = " + ex.StackTrace);
                        }

                        // Get Messages
                        bool bFailureMessages = false;
                        strMessage += this.ConvertGPMessagesToString(ipMessages, out bFailureMessages);

                        Log("ExecuteGPTool.Execute got messages from tool");
                        Log("*** GP MESSAGES ***" + System.Environment.NewLine + strMessage + System.Environment.NewLine);
                        Log("*** END GP MESSAGES ***");

                        // If tool failed during execution, indicate a failure
                        if (pGP.MaxSeverity == (int)esriGPMessageSeverity.esriGPMessageSeverityError)
                        {
                            success = false;
                            Log("ExecuteGPTool.Execute Found Error messages from the tool..");
                        }
                    }

                    // Call AttachMsg
                    try
                    {
                        IJTXJobManager ipJobManager = m_ipDatabase.JobManager;
                        IJTXJob ipJob = ipJobManager.GetJob(jobID);
                        AttachMsg(ipJob, strTool, this.GetCachedLogMessages());
                        this.ClearCachedLogMessages();
                    }
                    catch (Exception ex)
                    {
                        string strEx = ex.Message;
                        Log("Caught exception: " + ex.Message);
                    }
                    
                    pGP.UnRegisterGeoProcessorEvents(pCallback);
                }
            }
            catch (Exception ex2)
            {
                success = false;
                Log("Caught exception: " + ex2.Message);
#if (!SERVER)
                string msg = "";
                if (ex2.InnerException == null)
                {
                    msg = "Inner Exception is null";
                }
                else
                {
                    msg = "Inner Exception is not null";
                }

                MessageBox.Show("Stack Trace: " + ex2.StackTrace + Environment.NewLine + "Message: " + ex2.Message + Environment.NewLine + "Source: " + ex2.Source + Environment.NewLine + msg);
#endif
            }

            // Clean up
#if (!SERVER)
            if (sfd != null)
            {
                sfd.Close();
            }
#endif

            // Indicate success or failure
            if (success == true)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Occurs when this command is clicked
        /// </summary>
        public override void OnClick()
        {
            string            name        = NetWorkAnalysClass.getPath(path) + "\\data\\HuanbaoGeodatabase.gdb"; //得到数据库文件路径
            IFeatureWorkspace pFWorkspace = NetWorkAnalysClass.OpenWorkspace(name) as IFeatureWorkspace;         //打开要素工作空间

            //"RouteNetwork","BaseData"参数不可更改
            networkDataset = NetWorkAnalysClass.OpenPathNetworkDataset(pFWorkspace as IWorkspace,
                                                                       "RouteNetwork", "BaseData"); //打开网络数据集
            m_NAContext = NetWorkAnalysClass.CreatePathSolverContext(networkDataset);               //通过网络数据集创建网络分析上下文


            inputFClass   = pFWorkspace.OpenFeatureClass("Stops");   //根据名字打开站点要素类
            barriesFClass = pFWorkspace.OpenFeatureClass("Barries"); //根据名字打开障碍点要素类
            if (IFLayerExist("NetworkDataset") == false)             //若不存在NetworkDataset图层就执行
            {
                //创建名为“NetworkDataset”的图层
                ILayer        layer;
                INetworkLayer networkLayer;
                networkLayer = new NetworkLayerClass();
                networkLayer.NetworkDataset = networkDataset;
                layer      = networkLayer as ILayer;
                layer.Name = "NetworkDataset";
                m_hookHelper.ActiveView.FocusMap.AddLayer(layer);
                layer.Visible = false;
            }
            //检查是否存在名为“Route”的图层。若存在则删除
            if (IFLayerExist(m_NAContext.Solver.DisplayName) == true)
            {
                for (int i = 0; i < m_hookHelper.FocusMap.LayerCount; i++)
                {
                    if (m_hookHelper.FocusMap.get_Layer(i).Name == m_NAContext.Solver.DisplayName)
                    {
                        m_hookHelper.FocusMap.DeleteLayer(m_hookHelper.FocusMap.get_Layer(i));
                    }
                }
            }
            INALayer naLayer = m_NAContext.Solver.CreateLayer(m_NAContext);
            ILayer   pLayer  = naLayer as ILayer;

            pLayer.Name = m_NAContext.Solver.DisplayName;
            m_hookHelper.ActiveView.FocusMap.AddLayer(pLayer);//往当前地图中添加该图层


            int featureCount = inputFClass.FeatureCount(null); //得到站点要素类中要素的个数

            if (featureCount < 2)                              //若少于两个则不能进行分析
            {
                MessageBox.Show("只有一个站点,不能进行路径分析!");
                return;
            }
            IGPMessages gpMessages = new GPMessagesClass();//定义一个地理处理结果信息返回对象

            //加载站点要素,并设置容差
            NetWorkAnalysClass.LoadNANetworkLocations("Stops", inputFClass, m_NAContext, 80);
            //加载障碍点要素,并设置容差
            NetWorkAnalysClass.LoadNANetworkLocations("Barriers", barriesFClass, m_NAContext, 50);
            INASolver naSolver = m_NAContext.Solver;//创建网络分析对象

            try
            {
                naSolver.Solve(m_NAContext, gpMessages, null);//执行最短路径分析
            }
            catch (Exception ex)
            {
                MessageBox.Show("未能找到有效路径" + ex.Message, "提示",
                                MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                return;
            }
            //将“Routes”图层组下的“Stops”、“Point Barriers”图层设为不可见
            for (int i = 0; i < m_hookHelper.FocusMap.LayerCount; i++)
            {
                if (m_hookHelper.FocusMap.get_Layer(i).Name == m_NAContext.Solver.DisplayName)
                {
                    //ICompositeLayer Interface Provides access to members that work with a collection of layers that behaves like a single layer.
                    //CompositeLayer为图层组类型
                    ICompositeLayer pCompositeLayer = m_hookHelper.FocusMap.get_Layer(i) as ICompositeLayer;
                    for (int t = 0; t < pCompositeLayer.Count; t++)
                    {
                        ILayer pResultLayer = pCompositeLayer.get_Layer(t);
                        if (pResultLayer.Name == "Stops" || pResultLayer.Name == "Point Barriers")
                        {
                            pResultLayer.Visible = false;
                            continue;
                        }
                    }
                }
            }

            //接下来将地图的视图范围缩放至最短路径的显示范围
            IGeoDataset geoDataset; //地理数据集
            IEnvelope   envelope;   //最小边界矩形

            geoDataset = m_NAContext.NAClasses.get_ItemByName("Routes") as IGeoDataset;
            //The IGeoDataset::Extent property returns an envelope representing the maximum extent of data which has been stored in the dataset.
            envelope = geoDataset.Extent;
            if (!envelope.IsEmpty)
            {
                envelope.Expand(1.1, 1.1, true);
            }
            //将地图的显示的范围设置为“Routes”图层的数据范围
            m_hookHelper.ActiveView.Extent = envelope;
            //刷新视图
            m_hookHelper.ActiveView.Refresh();
            //获取最短路径“Routes”要素
            ITable  table  = m_NAContext.NAClasses.get_ItemByName("Routes") as ITable;
            ICursor cursor = table.Search(null, false);
            IRow    row    = cursor.NextRow();

            for (int i = 0; i < table.Fields.FieldCount; i++)
            {
                if (table.Fields.get_Field(i).AliasName == "Total_Shape_Length")
                {
                    //获取最短路径的总长度
                    total_Length_str = row.get_Value(i).ToString();
                }
            }
        }
Exemplo n.º 27
0
        private void axMapControl1_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)
        {
            if(pFlag==1)//缓冲区空间查询
               {
               IActiveView pActView = axMapControl1.Map as IActiveView;

               IPoint pPoint = pActView.ScreenDisplay.DisplayTransformation.ToMapPoint(e.x, e.y);

               ITopologicalOperator pTopo = pPoint as ITopologicalOperator;

               IGeometry pGeo = pTopo.Buffer(500);

               ESRI.ArcGIS.Display.IRgbColor rgbColor = new ESRI.ArcGIS.Display.RgbColorClass();
               rgbColor.Red = 255;

               ESRI.ArcGIS.Display.IColor color = rgbColor; // Implicit Cast
               ESRI.ArcGIS.Display.ISimpleFillSymbol simpleFillSymbol = new ESRI.ArcGIS.Display.SimpleFillSymbolClass();
               simpleFillSymbol.Color = color;

               ESRI.ArcGIS.Display.ISymbol symbol = simpleFillSymbol as ESRI.ArcGIS.Display.ISymbol;

               pActView.ScreenDisplay.SetSymbol(symbol);

               pActView.ScreenDisplay.DrawPolygon(pGeo);

               axMapControl1.Map.SelectByShape(pGeo, null, false);

               axMapControl1.FlashShape(pGeo, 1000, 2, symbol);

               axMapControl1.ActiveView.Refresh();
               }
               if (pFlag == 2)
               {
               pNetMap = axMapControl1.Map;

               pGC = pNetMap as IGraphicsContainer;

               IActiveView pActView = pNetMap as IActiveView;

               IPoint pPoint = pActView.ScreenDisplay.DisplayTransformation.ToMapPoint(e.x, e.y);

               object o = Type.Missing;
               object o1 = Type.Missing;

               pPointC.AddPoint(pPoint, ref o, ref o1);

               IElement Element;

               ITextElement Textelement = new TextElementClass();

               Element = Textelement as IElement;

               pClickedCount++;

               Textelement.Text = pClickedCount.ToString();

               Element.Geometry = pActView.ScreenDisplay.DisplayTransformation.ToMapPoint(e.x, e.y);

               pGC.AddElement(Element, 0);

               pActView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);

               IFeatureClass pFeatureClass = pNaContext.NAClasses.get_ItemByName("Stops") as IFeatureClass;

               NASolve(pNaContext, pFeatureClass, pPointC, 5000);

               IGPMessages gpMessages = new GPMessagesClass();

               bool pBool = pNASolveClass.Solve(pNaContext, gpMessages, null);

               }

               if (pFlag == 3)//有向网络
               {
               IWorkspace pWs = GetMDBWorkspace(@".\data\Geometric.mdb");

               IFeatureWorkspace pFtWs = pWs as IFeatureWorkspace;

               IFeatureDataset pFtDataset = pFtWs.OpenFeatureDataset("work");

               double s = 0;

               IPolyline pPolyline = new PolylineClass();

               SolvePath(axMapControl1.Map, GetGeometricNetwork(pFtDataset, "TestGeometric"), "Weight", pPointC, 1000, ref pPolyline, ref s);

               IRgbColor pColor = new RgbColorClass();
               pColor.Red = 255;
               IElement pElement = new LineElementClass();
               ILineSymbol linesymbol = new SimpleLineSymbolClass();
               linesymbol.Color = pColor as IColor;
               linesymbol.Width = 100;

               pElement.Geometry = pPolyline;

               pGC.AddElement(pElement, 2);

               axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
               }
               if (pFlag == 4)
               {
               if(axMapControl1.Map.get_Layer(0)!=null)
               {
                   IRasterLayer pRasterLayer = axMapControl1.Map.get_Layer(0) as IRasterLayer;

                   IRasterSurface pRasterSurface = new RasterSurfaceClass();

                   pRasterSurface.PutRaster(pRasterLayer.Raster, 0);

                   ISurface pSurface = pRasterSurface as ISurface;

                  IPolyline pPolyline = axMapControl1.TrackLine() as  IPolyline;

                   IPoint pPoint =null ;

                    IPolyline pVPolyline =null;

                   IPolyline pInPolyline= null;

                   object pRef=0.13;

                   bool pBool =true;

                   double pZ1 = pSurface.GetElevation(pPolyline.FromPoint);

                   double pZ2= pSurface.GetElevation(pPolyline.ToPoint);

                   IPoint pPoint1 = new PointClass();

                   pPoint1.Z = pZ1;

                   pPoint1.X = pPolyline.FromPoint.X;

                   pPoint1.Y = pPolyline.FromPoint.Y;

                   IPoint pPoint2 = new PointClass();

                   pPoint2.Z = pZ2;

                   pPoint2.X = pPolyline.ToPoint.X;

                   pPoint2.Y = pPolyline.ToPoint.Y;

                   pSurface.GetLineOfSight(pPoint1, pPoint2, out pPoint, out pVPolyline,
                       out pInPolyline, out pBool, false, false, ref pRef);//大爷的,设置为true居然通不过bApplyCurvature和bApplyRefraction两项设置为true,surface必须定义成具有ZUnits的投影坐标

                   //This member should not be used in .NET. As a substitute, .NET developers must use IGeoDatabaseBridge2.GetLineOfSight.

                         //楼主,用IGeoDatabaseBridge2.GetLineOfSight.方法试试
                   if (pVPolyline != null)
                   {

                       IElement pLineElementV = new LineElementClass();

                       pLineElementV.Geometry = pVPolyline;

                       ILineSymbol pLinesymbolV = new SimpleLineSymbolClass();

                       pLinesymbolV.Width = 2;

                       IRgbColor pColorV = new RgbColorClass();

                       pColorV.Green =255;

                       pLinesymbolV.Color = pColorV;

                       ILineElement pLineV = pLineElementV as ILineElement;

                       pLineV.Symbol = pLinesymbolV;

                       axMapControl1.ActiveView.GraphicsContainer.AddElement(pLineElementV, 0);
                   }

                   if (pInPolyline != null)
                   {

                       IElement pLineElementIn = new LineElementClass();

                       pLineElementIn.Geometry = pInPolyline;

                       ILineSymbol pLinesymbolIn = new SimpleLineSymbolClass();

                       pLinesymbolIn.Width = 2;

                       IRgbColor pColorIn = new RgbColorClass();
                       pColorIn.Red = 255;

                       pLinesymbolIn.Color = pColorIn;
                       ILineElement pLineIn = pLineElementIn as ILineElement;

                       pLineIn.Symbol = pLinesymbolIn;

                       axMapControl1.ActiveView.GraphicsContainer.AddElement(pLineElementIn, 1);

                   }

                   axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);

                   axMapControl1.TrackCancel.Cancel();

               }
               }
        }
Exemplo n.º 28
0
        //��ʼ���������������
        private void NetworkSolve()
        {
            try
            {
                IGPMessages gpMessages = new GPMessagesClass();
                IFeatureClass pFeatCls = null;
                IGeoDataset geoDataset = null;
                if (!m_NAContext.Solver.Solve(m_NAContext, gpMessages, null))
                {
                    for (int i = 0; i <= m_NAContext.NAClasses.Count - 1; i++)
                    {
                        string sName = m_NAContext.NAClasses.get_Name(i);
                        if (sName == "Routes")
                        {
                            geoDataset = m_NAContext.NAClasses.get_ItemByName("Routes") as IGeoDataset;
                            pFeatCls = geoDataset as IFeatureClass;
                           // LoadNANetworkLocations("Routes", pFeatCls, 5000);
                        }
                        if (sName == "CFRoutes")
                        {
                            geoDataset = m_NAContext.NAClasses.get_ItemByName("CFRoutes") as IGeoDataset;
                            pFeatCls = geoDataset as IFeatureClass;
                        }

                    }

                    IEnvelope pEnvelope = geoDataset.Extent;
                    if (!pEnvelope.IsEmpty)
                        pEnvelope.Expand(1.1, 1.1, true);
                    axMapControl1.Extent = pEnvelope;
                    axMapControl1.Refresh();
                }
                else
                {
                    if (gpMessages != null)
                    {
                        for (int i = 0; i < gpMessages.Count; i++)
                        {
                            switch (gpMessages.GetMessage(i).Type)
                            {

                                case esriGPMessageType.esriGPMessageTypeError:
                                    MessageBox.Show("Error " + gpMessages.GetMessage(i).ErrorCode.ToString() + " " + gpMessages.GetMessage(i).Description);
                                    break;
                                case esriGPMessageType.esriGPMessageTypeWarning:
                                    MessageBox.Show("Warning " + gpMessages.GetMessage(i).Description);
                                    break;
                                default:
                                    MessageBox.Show("Information " + gpMessages.GetMessage(i).Description);
                                    break;
                            }
                        }
                    }
                }
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);

            }
        }
Exemplo n.º 29
0
        //路径分析
        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            if (global.networkAnalysis && global.clickedcount > 1)
            {
                global.networkAnalysis = false;
                listBox1.Items.Add("开始进行路径分析求解...");

                IGPMessages gpMessages = new GPMessagesClass();
                loadNANetworkLocations("Stops", global.inputFClass, 80);
                naSolver = global.m_NAContext.Solver;
                naSolver.Solve(global.m_NAContext, gpMessages, null);
                listBox1.Items.Add("done!");

                //获取路径结果
                INAStreetDirectionsAgent2 streetAgent;
                streetAgent = global.m_NAContext.Agents.get_ItemByName("StreetDirectionsAgent") as INAStreetDirectionsAgent2;
                //设置处理结果为中文
                //streetAgent.Language = "zh-CN";
                streetAgent.Execute(null, null);

                INAStreetDirectionsContainer directionsContainer;
                directionsContainer = streetAgent.DirectionsContainer as INAStreetDirectionsContainer;
                //directionsContainer.SaveAsXML("route.xml");

                int    directionsCount = directionsContainer.DirectionsCount;
                string routeIdName     = string.Empty;
                string routeString;
                for (int index = 0; index < directionsCount; index++)
                {
                    INAStreetDirections naStreetDirections = directionsContainer.get_Directions(index);
                    routeString = getDirectionsString(naStreetDirections);
                    getDataTableFromRouteString(routeString);
                }

                //解决完后,删除图层内容
                ITable pTable_inputFClass = global.inputFClass as ITable;
                pTable_inputFClass.DeleteSearchedRows(null);
                (global.p2DMap as IActiveView).Refresh();

                if (gpMessages != null)
                {
                    for (int i = 0; i < gpMessages.Count; i++)
                    {
                        switch (gpMessages.GetMessage(i).Type)
                        {
                        case esriGPMessageType.esriGPMessageTypeError:
                            listBox1.Items.Add("错误 " + gpMessages.GetMessage(i).ErrorCode.ToString() + " " + gpMessages.GetMessage(i).Description);
                            break;

                        case esriGPMessageType.esriGPMessageTypeWarning:
                            listBox1.Items.Add("警告 " + gpMessages.GetMessage(i).Description);
                            break;

                        default:
                            listBox1.Items.Add("信息 " + gpMessages.GetMessage(i).Description);
                            break;
                        }
                    }
                }

                (global.p2DMap as IActiveView).Refresh();
            }
            else if (global.clickedcount == 1)
            {
                MessageBox.Show("未选取终点,请继续定位!");
            }
            else
            {
                MessageBox.Show("未选取或更新起点和终点,请重新定位!");
            }
        }