Example #1
0
        private INALayer CreateRouteAnalysisLayer(string sName, INetworkDataset pNetworkDataset)
        {
            INARouteSolver    solver   = new NARouteSolverClass();
            INASolverSettings settings = solver as INASolverSettings;
            INASolver         solver2  = solver as INASolver;

            solver.FindBestSequence  = true;
            solver.PreserveFirstStop = true;
            solver.PreserveLastStop  = false;
            solver.UseTimeWindows    = false;
            solver.OutputLines       = esriNAOutputLineType.esriNAOutputLineTrueShapeWithMeasure;
            IStringArray restrictionAttributeNames = settings.RestrictionAttributeNames;

            restrictionAttributeNames.Add("Oneway");
            settings.RestrictionAttributeNames = restrictionAttributeNames;
            IDatasetComponent component   = pNetworkDataset as IDatasetComponent;
            IDENetworkDataset dataElement = component.DataElement as IDENetworkDataset;
            INAContext        context     = solver2.CreateContext(dataElement, sName);

            (context as INAContextEdit).Bind(pNetworkDataset, new GPMessagesClass());
            INALayer layer = solver2.CreateLayer(context);

            (layer as ILayer).Name = sName;
            return(layer);
        }
Example #2
0
        /// <summary>
        /// Create the analysis layer, load the locations, solve the analysis, and write to disk
        /// </summary>
        public void SolveRoute()
        {
            // Open the feature workspace, input feature class, and network dataset
            // As Workspace Factories are Singleton objects, they must be instantiated with the Activator
            IWorkspaceFactory workspaceFactory = System.Activator.CreateInstance(System.Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory")) as IWorkspaceFactory;
            IFeatureWorkspace featureWorkspace = workspaceFactory.OpenFromFile(Application.StartupPath + FGDB_WORKSPACE, 0) as IFeatureWorkspace;
            IFeatureClass     inputStopsFClass = featureWorkspace.OpenFeatureClass(INPUT_STOPS_FC);

            // Obtain the dataset container from the workspace
            ESRI.ArcGIS.Geodatabase.IFeatureDataset featureDataset = featureWorkspace.OpenFeatureDataset(FEATURE_DATASET);
            var featureDatasetExtensionContainer = featureDataset as ESRI.ArcGIS.Geodatabase.IFeatureDatasetExtensionContainer;

            ESRI.ArcGIS.Geodatabase.IFeatureDatasetExtension featureDatasetExtension = featureDatasetExtensionContainer.FindExtension(ESRI.ArcGIS.Geodatabase.esriDatasetType.esriDTNetworkDataset);
            var datasetContainer3 = featureDatasetExtension as ESRI.ArcGIS.Geodatabase.IDatasetContainer3;

            // Use the container to open the network dataset.
            ESRI.ArcGIS.Geodatabase.IDataset dataset = datasetContainer3.get_DatasetByName(ESRI.ArcGIS.Geodatabase.esriDatasetType.esriDTNetworkDataset, NETWORK_DATASET);
            INetworkDataset networkDataset           = dataset as INetworkDataset;

            // Create the Route NALayer
            INALayer      naLayer      = CreateRouteAnalysisLayer("Route", networkDataset);
            INAContext    naContext    = naLayer.Context;
            INAClass      stopsNAClass = naContext.NAClasses.get_ItemByName("Stops") as INAClass;
            IFeatureClass routesFC     = naContext.NAClasses.get_ItemByName("Routes") as IFeatureClass;

            // Load the Stops
            INAClassFieldMap naClassFieldMap = new NAClassFieldMapClass();

            naClassFieldMap.set_MappedField("Name", INPUT_NAME_FIELD);

            INAClassLoader naLoader = new NAClassLoaderClass();

            naLoader.Locator  = naContext.Locator;
            naLoader.NAClass  = stopsNAClass;
            naLoader.FieldMap = naClassFieldMap;

            // Avoid loading network locations onto non-traversable portions of elements
            INALocator3 locator = naContext.Locator as INALocator3;

            locator.ExcludeRestrictedElements = true;
            locator.CacheRestrictedElements(naContext);

            int rowsInCursor = 0;
            int rowsLocated  = 0;

            naLoader.Load(inputStopsFClass.Search(new QueryFilterClass(), false) as ICursor, new CancelTrackerClass(), ref rowsInCursor, ref rowsLocated);

            //Message all of the network analysis agents that the analysis context has changed
            ((INAContextEdit)naContext).ContextChanged();

            //Solve
            INASolver naSolver = naContext.Solver;

            naSolver.Solve(naContext, new GPMessagesClass(), new CancelTrackerClass());

            //Save the layer to disk
            SaveLayerToDisk(naLayer as ILayer, System.Environment.CurrentDirectory + @"\Route.lyr");
        }
        /// <summary>
        /// Set solver settings
        /// </summary>
        public void SetSolverSettings()
        {
            // Set OD solver specific settings
            INASolver solver = m_NAContext.Solver;

            INAODCostMatrixSolver odSolver = solver as INAODCostMatrixSolver;

            if (textCutoff.Text.Length > 0 && IsNumeric(textCutoff.Text.Trim()))
            {
                odSolver.DefaultCutoff = textCutoff.Text;
            }
            else
            {
                odSolver.DefaultCutoff = null;
            }

            if (textTargetFacility.Text.Length > 0 && IsNumeric(textTargetFacility.Text.Trim()))
            {
                odSolver.DefaultTargetDestinationCount = textTargetFacility.Text;
            }
            else
            {
                odSolver.DefaultTargetDestinationCount = null;
            }

            odSolver.OutputLines = esriNAOutputLineType.esriNAOutputLineStraight;

            // Set generic solver settings
            // Set the impedance attribute
            INASolverSettings solverSettings = solver as INASolverSettings;

            solverSettings.ImpedanceAttributeName = comboCostAttribute.Text;

            // Set the OneWay restriction if necessary
            IStringArray restrictions = solverSettings.RestrictionAttributeNames;

            restrictions.RemoveAll();
            if (checkUseRestriction.Checked)
            {
                restrictions.Add("oneway");
            }
            solverSettings.RestrictionAttributeNames = restrictions;

            // Restrict UTurns
            solverSettings.RestrictUTurns         = esriNetworkForwardStarBacktrack.esriNFSBNoBacktrack;
            solverSettings.IgnoreInvalidLocations = true;

            // Set the hierarchy attribute
            solverSettings.UseHierarchy = checkUseHierarchy.Checked;
            if (solverSettings.UseHierarchy)
            {
                solverSettings.HierarchyAttributeName = "HierarchyMultiNet";
            }

            // Do not forget to update the context after you set your impedance
            solver.UpdateContext(m_NAContext, GetDENetworkDataset(m_NAContext.NetworkDataset), new GPMessagesClass());
        }
Example #4
0
        public void SetSolverSettings()
        {
            INASolver solver = this.m_pNAContext.Solver;
            INAClosestFacilitySolver solver2 = solver as INAClosestFacilitySolver;

            if ((this.txtCutOff.Text.Length > 0) && this.IsNumeric(this.txtCutOff.Text.Trim()))
            {
                solver2.DefaultCutoff = this.txtCutOff.Text;
            }
            else
            {
                solver2.DefaultCutoff = null;
            }
            if ((this.txtTargetFacility.Text.Length > 0) && this.IsNumeric(this.txtTargetFacility.Text))
            {
                solver2.DefaultTargetFacilityCount = int.Parse(this.txtTargetFacility.Text);
            }
            else
            {
                solver2.DefaultTargetFacilityCount = 1;
            }
            solver2.OutputLines     = esriNAOutputLineType.esriNAOutputLineTrueShapeWithMeasure;
            solver2.TravelDirection = esriNATravelDirection.esriNATravelDirectionToFacility;
            INASolverSettings settings = solver as INASolverSettings;

            settings.ImpedanceAttributeName = this.cboCostAttribute.Text;
            IStringArray restrictionAttributeNames = settings.RestrictionAttributeNames;

            restrictionAttributeNames.RemoveAll();
            if (this.chkUseRestriction.Checked)
            {
                restrictionAttributeNames.Add("oneway");
            }
            settings.RestrictionAttributeNames = restrictionAttributeNames;
            settings.RestrictUTurns            = esriNetworkForwardStarBacktrack.esriNFSBNoBacktrack;
            settings.IgnoreInvalidLocations    = true;
            settings.UseHierarchy = this.chkUseHierarchy.Checked;
            if (settings.UseHierarchy)
            {
                settings.HierarchyAttributeName = "hierarchy";
                settings.HierarchyLevelCount    = 3;
                settings.set_MaxValueForHierarchy(1, 1);
                settings.set_NumTransitionToHierarchy(1, 9);
                settings.set_MaxValueForHierarchy(2, 2);
                settings.set_NumTransitionToHierarchy(2, 9);
            }
            solver.UpdateContext(this.m_pNAContext, this.GetDENetworkDataset(this.m_pNAContext.NetworkDataset),
                                 new GPMessagesClass());
        }
 /// <summary>
 /// 设置解决器 暂时没有使用到
 /// 有问题待修正
 /// </summary>
 /// <param name="pNAContext"></param>
 private static void SetSolverSettings(INAContext pNAContext)
 {
     if (pNAContext.Solver.CanAccumulateAttributes)
     {
         INASolver      naSolver      = pNAContext.Solver;
         INARouteSolver naRouteSolver = naSolver as INARouteSolver;
         naRouteSolver.FindBestSequence  = true;
         naRouteSolver.PreserveFirstStop = true;
         naRouteSolver.PreserveLastStop  = false;
         naRouteSolver.UseTimeWindows    = false;
         naRouteSolver.OutputLines       = esriNAOutputLineType.esriNAOutputLineTrueShapeWithMeasure;
         INASolverSettings2 naSolverSettings = naSolver as INASolverSettings2;
         IStringArray       restrictions     = naSolverSettings.RestrictionAttributeNames;
         restrictions.Add("Oneway");
         naSolverSettings.RestrictionAttributeNames = restrictions;
         //基于上述设置更新Solver
         naSolver.UpdateContext(pNAContext, GetDENetworkDataset(pNAContext.NetworkDataset), new GPMessagesClass());
     }
 }
Example #6
0
        /// <summary>
        /// Create a new network analysis layer and set some solver settings
        /// </summary>
        private INALayer CreateRouteAnalysisLayer(String layerName, INetworkDataset networkDataset)
        {
            INARouteSolver    naRouteSolver    = new NARouteSolverClass();
            INASolverSettings naSolverSettings = naRouteSolver as INASolverSettings;
            INASolver         naSolver         = naRouteSolver as INASolver;

            //Get the NetworkDataset's Data Element
            IDatasetComponent datasetComponent = networkDataset as IDatasetComponent;
            IDENetworkDataset deNetworkDataset = datasetComponent.DataElement as IDENetworkDataset;

            //Create the NAContext and bind to it
            INAContext naContext;

            naContext = naSolver.CreateContext(deNetworkDataset, layerName);
            INAContextEdit naContextEdit = naContext as INAContextEdit;

            naContextEdit.Bind(networkDataset, new GPMessagesClass());

            //Create the NALayer
            INALayer naLayer;

            naLayer = naSolver.CreateLayer(naContext);
            (naLayer as ILayer).Name = layerName;

            //Set properties on the route solver interface
            naRouteSolver.FindBestSequence  = true;
            naRouteSolver.PreserveFirstStop = true;
            naRouteSolver.PreserveLastStop  = false;
            naRouteSolver.UseTimeWindows    = false;
            naRouteSolver.OutputLines       = esriNAOutputLineType.esriNAOutputLineTrueShapeWithMeasure;

            //Set some properties on the general INASolverSettings interface
            IStringArray restrictions = naSolverSettings.RestrictionAttributeNames;

            restrictions.Add("Oneway");
            naSolverSettings.RestrictionAttributeNames = restrictions;

            // Update the context based on the changes made to the solver settings
            naSolver.UpdateContext(naContext, deNetworkDataset, new GPMessagesClass());

            //Return the layer
            return(naLayer);
        }
Example #7
0
		public INAContext CreateRouteSolverContext(INetworkDataset pNetDataset)
		{
			
			INAContextEdit pContextEdit;
			IDENetworkDataset pDENDS= GetDENetworkDataset(pNetDataset);
			INASolver pNASolver=(new NARouteSolverClass()) as INASolver;

			pContextEdit = pNASolver.CreateContext(pDENDS, "Route") as INAContextEdit;

			pContextEdit.Bind(pNetDataset,new GPMessagesClass());



			return pContextEdit as INAContext;
			
			


		}
Example #8
0
        public static INALayer CreateNetworkAnalysisLayer(string name, INetworkDataset networkDataset,
                                                          INASolver naSolver)
        {
            if (naSolver is INARouteSolver)
            {
                return(CreateRouteAnalysisLayer(name, networkDataset, naSolver as INARouteSolver));
            }
            if (naSolver is INAClosestFacilitySolver)
            {
                return(CreateClosestFacilityLayer(name, networkDataset, naSolver as INAClosestFacilitySolver));
            }
            IDatasetComponent component   = (IDatasetComponent)networkDataset;
            IDENetworkDataset dataElement = (IDENetworkDataset)component.DataElement;
            INAContext        context     = naSolver.CreateContext(dataElement, name);

            ((INAContextEdit)context).Bind(networkDataset, null);
            INALayer layer = naSolver.CreateLayer(context);

            ((ILayer)layer).Name = name;
            return(layer);
        }
Example #9
0
        public static INALayer CreateClosestFacilityLayer(string layerName, INetworkDataset networkDataset,
                                                          INAClosestFacilitySolver naClosesFacilitySolver)
        {
            INASolverSettings settings    = naClosesFacilitySolver as INASolverSettings;
            INASolver         solver      = naClosesFacilitySolver as INASolver;
            IDatasetComponent component   = networkDataset as IDatasetComponent;
            IDENetworkDataset dataElement = component.DataElement as IDENetworkDataset;
            INAContext        context     = solver.CreateContext(dataElement, layerName);

            (context as INAContextEdit).Bind(networkDataset, new GPMessagesClass());
            INALayer layer = solver.CreateLayer(context);

            (layer as ILayer).Name = layerName;
            naClosesFacilitySolver.CreateTraversalResult = true;
            naClosesFacilitySolver.TravelDirection       = esriNATravelDirection.esriNATravelDirectionFromFacility;
            naClosesFacilitySolver.OutputLines           = esriNAOutputLineType.esriNAOutputLineTrueShapeWithMeasure;
            IStringArray restrictionAttributeNames = settings.RestrictionAttributeNames;

            restrictionAttributeNames.Add("Oneway");
            settings.RestrictionAttributeNames = restrictionAttributeNames;
            solver.UpdateContext(context, dataElement, new GPMessagesClass());
            return(layer);
        }
Example #10
0
        /// <summary>
        /// Set solver settings
        /// </summary>
        public void SetSolverSettings(string attributeName)
        {
            //Set Route specific Settings
            INASolver naSolver = m_NAContext.Solver;

            INAClosestFacilitySolver cfSolver = naSolver as INAClosestFacilitySolver;

            cfSolver.OutputLines     = esriNAOutputLineType.esriNAOutputLineTrueShapeWithMeasure;
            cfSolver.TravelDirection = esriNATravelDirection.esriNATravelDirectionFromFacility;

            // Set generic solver settings
            // Set the impedance attribute
            INASolverSettings naSolverSettings;

            naSolverSettings = naSolver as INASolverSettings;
            naSolverSettings.ImpedanceAttributeName = attributeName;

            // Set the OneWay Restriction if necessary
            IStringArray restrictions;

            restrictions = naSolverSettings.RestrictionAttributeNames;
            restrictions.RemoveAll();
            naSolverSettings.RestrictionAttributeNames = restrictions;

            //Restrict UTurns
            naSolverSettings.RestrictUTurns         = esriNetworkForwardStarBacktrack.esriNFSBNoBacktrack;
            naSolverSettings.IgnoreInvalidLocations = true;

            // Set the Hierarchy attribute
            if (naSolverSettings.UseHierarchy)
            {
                naSolverSettings.HierarchyAttributeName = "HierarchyMultiNet";
            }

            // Do not forget to update the context after you set your impedance
            naSolver.UpdateContext(m_NAContext, GetDENetworkDataset(m_NAContext.NetworkDataset), new GPMessagesClass());
        }
        //*********************************************************************************
        // Set Solver Settings for the Location-Allocation Solver
        //*********************************************************************************
        public void SetSolverSettings()
        {
            //Set Location-Allocation specific Settings
            INASolver naSolver = m_NAContext.Solver;

            INALocationAllocationSolver2 laSolver = naSolver as INALocationAllocationSolver2;

            // Set number of facilities to locate
            if (txtFacilitiesToLocate.Text.Length > 0 && IsNumeric(txtFacilitiesToLocate.Text))
            {
                laSolver.NumberFacilitiesToLocate = int.Parse(txtFacilitiesToLocate.Text);
            }
            else
            {
                laSolver.NumberFacilitiesToLocate = 1;
            }

            // Set impedance cutoff
            if (txtCutOff.Text.Length > 0 && IsNumeric(txtCutOff.Text.Trim()))
            {
                laSolver.DefaultCutoff = txtCutOff.Text;
            }
            else
            {
                laSolver.DefaultCutoff = null;
            }

            // Set up Location-Allocation problem type
            if (cboProblemType.Text.Equals("Maximize Attendance"))
            {
                laSolver.ProblemType = esriNALocationAllocationProblemType.esriNALAPTMaximizeAttendance;
            }
            else if (cboProblemType.Text.Equals("Maximize Coverage"))
            {
                laSolver.ProblemType = esriNALocationAllocationProblemType.esriNALAPTMaximizeCoverage;
            }
            else if (cboProblemType.Text.Equals("Maximize Capacitated Coverage"))
            {
                laSolver.ProblemType = esriNALocationAllocationProblemType.esriNALAPTMaximizeCapacitatedCoverage;
            }
            else if (cboProblemType.Text.Equals("Minimize Facilities"))
            {
                laSolver.ProblemType = esriNALocationAllocationProblemType.esriNALAPTMaximizeCoverageMinimizeFacilities;
            }
            else if (cboProblemType.Text.Equals("Maximize Market Share"))
            {
                laSolver.ProblemType = esriNALocationAllocationProblemType.esriNALAPTMaximizeMarketShare;
            }
            else if (cboProblemType.Text.Equals("Minimize Impedance"))
            {
                laSolver.ProblemType = esriNALocationAllocationProblemType.esriNALAPTMinimizeWeightedImpedance;
            }
            else if (cboProblemType.Text.Equals("Target Market Share"))
            {
                laSolver.ProblemType = esriNALocationAllocationProblemType.esriNALAPTTargetMarketShare;
            }
            else
            {
                laSolver.ProblemType = esriNALocationAllocationProblemType.esriNALAPTMinimizeWeightedImpedance;
            }

            // Set Impedance Transformation type
            if (cboImpTransformation.Text.Equals("Linear"))
            {
                laSolver.ImpedanceTransformation = esriNAImpedanceTransformationType.esriNAITTLinear;
            }
            else if (cboImpTransformation.Text.Equals("Power"))
            {
                laSolver.ImpedanceTransformation = esriNAImpedanceTransformationType.esriNAITTPower;
            }
            else if (cboImpTransformation.Text.Equals("Exponential"))
            {
                laSolver.ImpedanceTransformation = esriNAImpedanceTransformationType.esriNAITTExponential;
            }

            // Set Impedance Transformation Parameter (distance decay beta)
            if (txtImpParameter.Text.Length > 0 && IsNumeric(txtCutOff.Text.Trim()))
            {
                laSolver.TransformationParameter = double.Parse(txtImpParameter.Text);
            }
            else
            {
                laSolver.TransformationParameter = 1.0;
            }

            // Set target market share percentage (should be between 0.0 and 100.0)
            if (txtTargetMarketShare.Text.Length > 0 && IsNumeric(txtCutOff.Text.Trim()))
            {
                double targetPercentage;
                targetPercentage = double.Parse(txtTargetMarketShare.Text);

                if ((targetPercentage <= 0.0) || (targetPercentage > 100.0))
                {
                    targetPercentage = 10.0;
                    lstOutput.Items.Add("Target percentage out of range. Reset to 10%");
                }
                laSolver.TargetMarketSharePercentage = targetPercentage;
                txtTargetMarketShare.Text            = laSolver.TargetMarketSharePercentage.ToString();
            }
            else
            {
                laSolver.TargetMarketSharePercentage = 10.0;
            }

            // Set default capacity
            if (txtDefaultCapacity.Text.Length > 0 && IsNumeric(txtDefaultCapacity.Text.Trim()))
            {
                double defaultCapacity;
                defaultCapacity = double.Parse(txtDefaultCapacity.Text);

                if ((defaultCapacity <= 0.0))
                {
                    defaultCapacity = 1.0;
                    lstOutput.Items.Add("Default capacity must be greater than zero.");
                }
                laSolver.DefaultCapacity = defaultCapacity;
                txtDefaultCapacity.Text  = laSolver.DefaultCapacity.ToString();
            }
            else
            {
                laSolver.DefaultCapacity = 1.0;
            }


            // Set any other solver settings
            laSolver.OutputLines     = esriNAOutputLineType.esriNAOutputLineStraight;
            laSolver.TravelDirection = esriNATravelDirection.esriNATravelDirectionFromFacility;

            // Set the impedance attribute
            INASolverSettings naSolverSettings = naSolver as INASolverSettings;

            naSolverSettings.ImpedanceAttributeName = cboCostAttribute.Text;

            naSolverSettings.IgnoreInvalidLocations = true;

            // Do not forget to update the context after you set your impedance
            naSolver.UpdateContext(m_NAContext, GetDENetworkDataset(m_NAContext.NetworkDataset), new GPMessagesClass());
        }
Example #12
0
        /// <summary>
        /// Set solver settings
        /// </summary>
        public void SetSolverSettings()
        {
            // Set VRP solver specific settings
            INASolver    solver    = m_NAContext.Solver;
            INAVRPSolver vrpSolver = solver as INAVRPSolver;

            // Both orders and routes have capacity count of 2 in the input shape files. User can modify the input data and update this value accordingly.
            vrpSolver.CapacityCount = 2;

            // Read the time and distance unit from comboBox
            vrpSolver.DistanceFieldUnits = (esriNetworkAttributeUnits)m_unitDistList[comboDistUnits.Items[comboDistUnits.SelectedIndex].ToString()];
            vrpSolver.TimeFieldUnits     = (esriNetworkAttributeUnits)m_unitTimeList[comboTimeUnits.Items[comboTimeUnits.SelectedIndex].ToString()];

            // The value of time window violation penalty factor can be adjusted in terms of the user's preference.
            string importance = comboTWImportance.Items[comboTWImportance.SelectedIndex].ToString();

            if (importance == "Low")
            {
                vrpSolver.TimeWindowViolationPenaltyFactor = 0;
            }
            else if (importance == "Medium")
            {
                vrpSolver.TimeWindowViolationPenaltyFactor = 1;
            }
            else if (importance == "High")
            {
                vrpSolver.TimeWindowViolationPenaltyFactor = 10;
            }

            // Set output line type
            vrpSolver.OutputLines = esriNAOutputLineType.esriNAOutputLineStraight;

            // Set generic solver settings
            // Set the impedance attribute
            INASolverSettings solverSettings = solver as INASolverSettings;

            solverSettings.ImpedanceAttributeName = comboTimeAttribute.Text;

            // Set the accumulated attribute
            IStringArray accumulatedAttributes = solverSettings.AccumulateAttributeNames;

            accumulatedAttributes.RemoveAll();
            accumulatedAttributes.Insert(0, comboDistanceAttribute.Text);
            solverSettings.AccumulateAttributeNames = accumulatedAttributes;

            // Set the oneway restriction if necessary
            IStringArray restrictions = solverSettings.RestrictionAttributeNames;

            restrictions.RemoveAll();
            if (checkUseRestriction.Checked)
            {
                restrictions.Add("oneway");
            }
            solverSettings.RestrictionAttributeNames = restrictions;

            // Restrict UTurns
            solverSettings.RestrictUTurns = esriNetworkForwardStarBacktrack.esriNFSBNoBacktrack;

            // Set the hierarchy attribute
            solverSettings.UseHierarchy = checkUseHierarchy.Checked;
            if (solverSettings.UseHierarchy)
            {
                solverSettings.HierarchyAttributeName = "HierarchyMultiNet";
            }

            // Do not forget to update the context after you set your impedance
            solver.UpdateContext(m_NAContext, GetDENetworkDataset(m_NAContext.NetworkDataset), new GPMessagesClass());
        }
        private void 加载网络ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            IWorkspace pWs = GetMDBWorkspace(@".\data\Geometric.mdb");

             IFeatureWorkspace pFtWs = pWs as IFeatureWorkspace;

             INetworkDataset pNetWorkDataset = GetNetDataset(pFtWs, "network", "network_ND");

             pNASolveClass = new NARouteSolverClass();

             loadNet(axMapControl1.Map, pNetWorkDataset);

             pNaContext = GetSolverContext(pNASolveClass, pNetWorkDataset);

             pNALayer = GetNaLayer(pNASolveClass, pNaContext);

             axMapControl1.Map.AddLayer(pNALayer as ILayer);
        }
        /// <summary>
        /// 获取网络分析上下文,这个接口是网络分析中很重要的一个
        /// </summary>
        /// <param name="_pNaSolver"></param>
        /// <param name="_pNetworkDataset"></param>
        /// <returns></returns>
        public INAContext GetSolverContext(INASolver _pNaSolver, INetworkDataset _pNetworkDataset)
        {
            //Get the Data Element

            IDatasetComponent pDataComponent = _pNetworkDataset as IDatasetComponent;

            IDEDataset pDeDataset = pDataComponent.DataElement;

            INAContextEdit pContextEdit = _pNaSolver.CreateContext(pDeDataset as IDENetworkDataset, _pNaSolver.Name) as INAContextEdit;

            //Prepare the context for analysis based upon the current network dataset schema.
            pContextEdit.Bind(_pNetworkDataset, new GPMessagesClass());
            return pContextEdit as INAContext;
        }
Example #15
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();
                }
            }
        }
Example #16
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            INASolver naSolver = pMainFrm.m_NAContext.Solver;
            //开始进行设置
            INAClosestFacilitySolver cfSolver = naSolver as INAClosestFacilitySolver;

            if (numericUpDownCutoff.Value == 0)
            {
                cfSolver.DefaultCutoff = null;
            }
            else
            {
                cfSolver.DefaultCutoff = numericUpDownCutoff.Value;
            }
            if (numericUpDownFCount.Value == 0)
            {
                cfSolver.DefaultTargetFacilityCount = 1;
            }
            else
            {
                cfSolver.DefaultTargetFacilityCount = int.Parse(numericUpDownFCount.Value.ToString());
            }
            //设置输出线的形状
            switch (cboOutShapeType.Text)
            {
            case "无":
                cfSolver.OutputLines = esriNAOutputLineType.esriNAOutputLineNone;
                break;

            case "直线":
                cfSolver.OutputLines = esriNAOutputLineType.esriNAOutputLineStraight;
                break;

            case "True Shape":
                cfSolver.OutputLines = esriNAOutputLineType.esriNAOutputLineTrueShape;
                break;

            case "True Shape(无测量)":
                cfSolver.OutputLines = esriNAOutputLineType.esriNAOutputLineTrueShapeWithMeasure;
                break;
            }
            //设置查找方向
            if (rbnItoF.Checked == true)
            {
                cfSolver.TravelDirection = esriNATravelDirection.esriNATravelDirectionToFacility;
            }
            else
            {
                cfSolver.TravelDirection = esriNATravelDirection.esriNATravelDirectionFromFacility;
            }

            //设置SOLVER的参数
            //设置Impedance的属性
            INASolverSettings naSolverSetting = naSolver as INASolverSettings;

            naSolverSetting.ImpedanceAttributeName = cboImpedance.Text;
            //设置OneWay限制
            IStringArray restriction = naSolverSetting.RestrictionAttributeNames;

            restriction.RemoveAll();
            int i = 0;

            for (i = 0; i <= listView1.SelectedItems.Count - 1; i++)
            {
                restriction.Add(listView1.SelectedItems.ToString());
            }
            naSolverSetting.RestrictionAttributeNames = restriction;
            //设置拐点
            switch (cboAllowedTurn.Text)
            {
            case "无":
                naSolverSetting.RestrictUTurns = esriNetworkForwardStarBacktrack.esriNFSBNoBacktrack;
                break;

            case "任何端点":
                naSolverSetting.RestrictUTurns = esriNetworkForwardStarBacktrack.esriNFSBAllowBacktrack;
                break;

            case "仅在末端":
                naSolverSetting.RestrictUTurns = esriNetworkForwardStarBacktrack.esriNFSBAtDeadEndsOnly;
                break;
            }
            naSolverSetting.IgnoreInvalidLocations = chkIgnoreInvalidValue.Checked;
            naSolver.UpdateContext(pMainFrm.m_NAContext, Utility.GetDENetworkDataset(pMainFrm.m_pNetDataset), new GPMessagesClass());
            ToolBarButton toolbarbutton1 = pMainFrm.returnToolbarButton();

            toolbarbutton1.Enabled = true;
            this.Dispose();
        }
        public static void PushParameterValuesToNetwork(INetworkAnalystExtension nax)
        {
            try
            {
                if (nax == null)
                {
                    return;
                }

                bool             naxEnabled = false;
                IExtensionConfig naxConfig  = nax as IExtensionConfig;
                naxEnabled = naxConfig.State == esriExtensionState.esriESEnabled;

                if (!naxEnabled)
                {
                    return;
                }

                INAWindow       naWindow  = nax.NAWindow;
                INALayer        naLayer   = null;
                INAContext      naContext = null;
                INetworkDataset nds       = null;

                naLayer = naWindow.ActiveAnalysis;
                if (naLayer != null)
                {
                    naContext = naLayer.Context;
                }

                if (naContext != null)
                {
                    nds = naContext.NetworkDataset;
                }

                if (nds == null)
                {
                    return;
                }

                IDatasetComponent dsComponent = nds as IDatasetComponent;
                IDENetworkDataset deNet       = dsComponent.DataElement as IDENetworkDataset;

                INASolver          naSolver          = naContext.Solver;
                INASolverSettings2 naSolverSettings2 = naSolver as INASolverSettings2;

                if (naSolverSettings2 == null)
                {
                    return;
                }

                INetworkAttribute2 netAttribute;
                string             attributeName;

                IArray netParameters;
                INetworkAttributeParameter netParameter;
                string paramName;
                int    cParameters;

                object paramValue;

                int cAttributes = nds.AttributeCount;
                for (int a = 0; a < cAttributes; ++a)
                {
                    netAttribute  = nds.get_Attribute(a) as INetworkAttribute2;
                    attributeName = netAttribute.Name;
                    netParameters = netAttribute.Parameters;

                    cParameters = netParameters.Count;
                    for (int p = 0; p < cParameters; ++p)
                    {
                        netParameter = netParameters.get_Element(p) as INetworkAttributeParameter;
                        paramName    = netParameter.Name;

                        paramValue         = naSolverSettings2.get_AttributeParameterValue(attributeName, paramName);
                        netParameter.Value = paramValue;
                    }

                    netAttribute.Refresh();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Push Parameter Values To Network");
            }
        }
 /// <summary>
 /// 获取NALayer
 /// </summary>
 /// <param name="_pNaSover"></param>
 /// <param name="_pNaContext"></param>
 /// <returns></returns>
 INALayer GetNaLayer(INASolver _pNaSover,INAContext _pNaContext)
 {
     return _pNaSover.CreateLayer(_pNaContext);
 }
        /// <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);
        }
Example #20
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();
        }
Example #21
0
        /// <summary>
        /// Set controls based on the current NALayer settings
        /// This function takes the current NALayer and determines what type of solver it's pointing to
        /// and populates the corresponding controls and hides the tabs for the other solvers.
        /// </summary>
        private void PopulateControls(INALayer naLayer)
        {
            ILayer                      layer            = naLayer as ILayer;
            INAContext                  naContext        = naLayer.Context;
            INetworkDataset             networkDataset   = naContext.NetworkDataset;
            INALocator2                 naLocator        = naContext.Locator as INALocator2;
            INASolver                   naSolver         = naContext.Solver;
            INASolverSettings           naSolverSettings = naSolver as INASolverSettings2;
            INARouteSolver2             routeSolver      = naSolver as INARouteSolver2;
            INAClosestFacilitySolver    cfSolver         = naSolver as INAClosestFacilitySolver;
            INAODCostMatrixSolver       odSolver         = naSolver as INAODCostMatrixSolver;
            INAServiceAreaSolver2       saSolver         = naSolver as INAServiceAreaSolver2;
            INAVRPSolver                vrpSolver        = naSolver as INAVRPSolver;
            INALocationAllocationSolver laSolver         = naSolver as INALocationAllocationSolver;

            // Populate general Layer controls
            txtLayerName.Text          = layer.Name;
            txtMaxSearchTolerance.Text = naLocator.MaxSnapTolerance.ToString();
            cboMaxSearchToleranceUnits.SelectedIndex = Convert.ToInt32(naLocator.SnapToleranceUnits);

            // Populate controls for the particular solver

            if (routeSolver != null)  // ROUTE LAYER
            {
                // Remove unnecessary tabs
                tabPropPages.TabPages.Remove(tabClosestFacility);
                tabPropPages.TabPages.Remove(tabODCostMatrix);
                tabPropPages.TabPages.Remove(tabServiceArea);
                tabPropPages.TabPages.Remove(tabVRP);
                tabPropPages.TabPages.Remove(tabLocationAllocation);

                // INARouteSolver2
                chkRouteFindBestSequence.Checked  = routeSolver.FindBestSequence;
                chkRoutePreserveFirstStop.Checked = routeSolver.PreserveFirstStop;
                chkRoutePreserveLastStop.Checked  = routeSolver.PreserveLastStop;
                chkRouteUseTimeWindows.Checked    = routeSolver.UseTimeWindows;
                chkRouteUseStartTime.Checked      = routeSolver.UseStartTime;
                txtRouteStartTime.Text            = routeSolver.StartTime.ToShortTimeString();
                cboRouteOutputLines.SelectedIndex = System.Convert.ToInt32(routeSolver.OutputLines);

                // INASolverSettings
                PopulateImpedanceNameControl(cboRouteImpedance, networkDataset, naSolverSettings.ImpedanceAttributeName);
                chkRouteUseHierarchy.Enabled           = (naSolverSettings.HierarchyAttributeName.Length > 0);
                chkRouteUseHierarchy.Checked           = (chkRouteUseHierarchy.Enabled && naSolverSettings.UseHierarchy);
                chkRouteIgnoreInvalidLocations.Checked = naSolverSettings.IgnoreInvalidLocations;
                cboRouteRestrictUTurns.SelectedIndex   = System.Convert.ToInt32(naSolverSettings.RestrictUTurns);
                PopulateAttributeControl(chklstRouteAccumulateAttributeNames, networkDataset, naSolverSettings.AccumulateAttributeNames, esriNetworkAttributeUsageType.esriNAUTCost);
                PopulateAttributeControl(chklstRouteRestrictionAttributeNames, networkDataset, naSolverSettings.RestrictionAttributeNames, esriNetworkAttributeUsageType.esriNAUTRestriction);
            }
            else if (cfSolver != null)  // CLOSEST FACILITY LAYER
            {
                // Remove unnecessary tabs
                tabPropPages.TabPages.Remove(tabRoute);
                tabPropPages.TabPages.Remove(tabODCostMatrix);
                tabPropPages.TabPages.Remove(tabServiceArea);
                tabPropPages.TabPages.Remove(tabVRP);
                tabPropPages.TabPages.Remove(tabLocationAllocation);

                // INAClosestFacilitySolver
                txtCFDefaultCutoff.Text = GetStringFromObject(cfSolver.DefaultCutoff);
                txtCFDefaultTargetFacilityCount.Text = cfSolver.DefaultTargetFacilityCount.ToString();
                cboCFTravelDirection.SelectedIndex   = Convert.ToInt32(cfSolver.TravelDirection);
                cboCFOutputLines.SelectedIndex       = Convert.ToInt32(cfSolver.OutputLines);

                // INASolverSettings
                PopulateImpedanceNameControl(cboCFImpedance, networkDataset, naSolverSettings.ImpedanceAttributeName);
                chkCFUseHierarchy.Enabled           = (naSolverSettings.HierarchyAttributeName.Length > 0);
                chkCFUseHierarchy.Checked           = (chkCFUseHierarchy.Enabled && naSolverSettings.UseHierarchy);
                chkCFIgnoreInvalidLocations.Checked = naSolverSettings.IgnoreInvalidLocations;
                cboCFRestrictUTurns.SelectedIndex   = System.Convert.ToInt32(naSolverSettings.RestrictUTurns);
                PopulateAttributeControl(chklstCFAccumulateAttributeNames, networkDataset, naSolverSettings.AccumulateAttributeNames, esriNetworkAttributeUsageType.esriNAUTCost);
                PopulateAttributeControl(chklstCFRestrictionAttributeNames, networkDataset, naSolverSettings.RestrictionAttributeNames, esriNetworkAttributeUsageType.esriNAUTRestriction);
            }
            else if (odSolver != null) // OD COST MATRIX LAYER
            {
                // Remove unnecessary tabs
                tabPropPages.TabPages.Remove(tabRoute);
                tabPropPages.TabPages.Remove(tabClosestFacility);
                tabPropPages.TabPages.Remove(tabServiceArea);
                tabPropPages.TabPages.Remove(tabVRP);

                // INAODCostMatrixSolver
                txtODDefaultCutoff.Text = GetStringFromObject(odSolver.DefaultCutoff);
                txtODDefaultTargetDestinationCount.Text = GetStringFromObject(odSolver.DefaultTargetDestinationCount);
                cboODOutputLines.SelectedIndex          = Convert.ToInt32(odSolver.OutputLines);

                // INASolverSettings
                PopulateImpedanceNameControl(cboODImpedance, networkDataset, naSolverSettings.ImpedanceAttributeName);
                chkODUseHierarchy.Enabled           = (naSolverSettings.HierarchyAttributeName.Length > 0);
                chkODUseHierarchy.Checked           = (chkODUseHierarchy.Enabled && naSolverSettings.UseHierarchy);
                chkODIgnoreInvalidLocations.Checked = naSolverSettings.IgnoreInvalidLocations;
                cboODRestrictUTurns.SelectedIndex   = System.Convert.ToInt32(naSolverSettings.RestrictUTurns);
                PopulateAttributeControl(chklstODAccumulateAttributeNames, networkDataset, naSolverSettings.AccumulateAttributeNames, esriNetworkAttributeUsageType.esriNAUTCost);
                PopulateAttributeControl(chklstODRestrictionAttributeNames, networkDataset, naSolverSettings.RestrictionAttributeNames, esriNetworkAttributeUsageType.esriNAUTRestriction);
            }
            else if (saSolver != null)  //SERVICE AREA SOLVER
            {
                // Remove unnecessary tabs
                tabPropPages.TabPages.Remove(tabRoute);
                tabPropPages.TabPages.Remove(tabClosestFacility);
                tabPropPages.TabPages.Remove(tabODCostMatrix);
                tabPropPages.TabPages.Remove(tabVRP);
                tabPropPages.TabPages.Remove(tabLocationAllocation);

                // INAServiceAreaSolver2
                txtSADefaultBreaks.Text = "";
                for (int iBreak = 0; iBreak < saSolver.DefaultBreaks.Count; iBreak++)
                {
                    txtSADefaultBreaks.Text = txtSADefaultBreaks.Text + " " + saSolver.DefaultBreaks.get_Element(iBreak).ToString();
                }
                cboSATravelDirection.SelectedIndex = Convert.ToInt32(saSolver.TravelDirection);

                cboSAOutputPolygons.SelectedIndex           = -1;
                cboSAOutputPolygons.SelectedIndex           = Convert.ToInt32(saSolver.OutputPolygons);
                chkSAOverlapPolygons.Checked                = saSolver.OverlapPolygons;
                chkSASplitPolygonsAtBreaks.Checked          = saSolver.SplitPolygonsAtBreaks;
                chkSAMergeSimilarPolygonRanges.Checked      = saSolver.MergeSimilarPolygonRanges;
                chkSATrimOuterPolygon.Checked               = saSolver.TrimOuterPolygon;
                txtSATrimPolygonDistance.Text               = saSolver.TrimPolygonDistance.ToString();
                cboSATrimPolygonDistanceUnits.SelectedIndex = Convert.ToInt32(saSolver.TrimPolygonDistanceUnits);

                cboSAOutputLines.SelectedIndex  = -1;
                cboSAOutputLines.SelectedIndex  = Convert.ToInt32(saSolver.OutputLines);
                chkSAOverlapLines.Checked       = saSolver.OverlapLines;
                chkSASplitLinesAtBreaks.Checked = saSolver.SplitLinesAtBreaks;
                chkSAIncludeSourceInformationOnLines.Checked = saSolver.IncludeSourceInformationOnLines;

                // INASolverSettings
                PopulateImpedanceNameControl(cboSAImpedance, networkDataset, naSolverSettings.ImpedanceAttributeName);
                chkSAIgnoreInvalidLocations.Checked = naSolverSettings.IgnoreInvalidLocations;
                cboSARestrictUTurns.SelectedIndex   = System.Convert.ToInt32(naSolverSettings.RestrictUTurns);
                PopulateAttributeControl(chklstSAAccumulateAttributeNames, networkDataset, naSolverSettings.AccumulateAttributeNames, esriNetworkAttributeUsageType.esriNAUTCost);
                PopulateAttributeControl(chklstSARestrictionAttributeNames, networkDataset, naSolverSettings.RestrictionAttributeNames, esriNetworkAttributeUsageType.esriNAUTRestriction);
            }
            else if (vrpSolver != null) // VRP Solver
            {
                // Remove unnecessary tabs
                tabPropPages.TabPages.Remove(tabRoute);
                tabPropPages.TabPages.Remove(tabClosestFacility);
                tabPropPages.TabPages.Remove(tabODCostMatrix);
                tabPropPages.TabPages.Remove(tabServiceArea);
                tabPropPages.TabPages.Remove(tabLocationAllocation);

                cboVRPOutputShapeType.SelectedIndex = Convert.ToInt32(vrpSolver.OutputLines);
                cboVRPAllowUTurns.SelectedIndex     = Convert.ToInt32(naSolverSettings.RestrictUTurns);
                // VRP cannot have unknown units, so the index is offset by 1 from the solver field units
                cboVRPDistanceFieldUnits.SelectedIndex = Convert.ToInt32(vrpSolver.DistanceFieldUnits) - 1;
                cboVRPTransitTime.SelectedIndex        = Convert.ToInt32(vrpSolver.ExcessTransitTimePenaltyFactor);
                cboVRPTimeWindow.SelectedIndex         = Convert.ToInt32(vrpSolver.TimeWindowViolationPenaltyFactor);
                cboVRPTimeFieldUnits.SelectedIndex     = Convert.ToInt32(vrpSolver.TimeFieldUnits - 20);

                txtVRPCapacityCount.Text = vrpSolver.CapacityCount.ToString();
                txtVRPDefaultDate.Text   = vrpSolver.DefaultDate.ToShortDateString();

                chkVRPUseHierarchy.Checked = naSolverSettings.UseHierarchy;

                PopulateAttributeControl(chklstVRPRestrictionAttributeNames, networkDataset, naSolverSettings.RestrictionAttributeNames, esriNetworkAttributeUsageType.esriNAUTRestriction);

                //populate the time attribute combo box
                cboVRPTimeAttribute.Items.Clear();

                for (int i = 0; i < networkDataset.AttributeCount; i++)
                {
                    INetworkAttribute networkAttribute = networkDataset.get_Attribute(i);

                    if (networkAttribute.UsageType == esriNetworkAttributeUsageType.esriNAUTCost &&
                        networkAttribute.Units >= esriNetworkAttributeUnits.esriNAUSeconds)
                    {
                        cboVRPTimeAttribute.Items.Add(networkAttribute.Name);
                    }
                }

                if (cboVRPTimeAttribute.Items.Count > 0)
                {
                    cboVRPTimeAttribute.Text = naSolverSettings.ImpedanceAttributeName;
                }


                // for VRP, the AccumulateAttributeNames hold the length, and it can only hold one length.
                //  Loop through the network dataset attributes
                cboVRPDistanceAttribute.Items.Clear();
                cboVRPDistanceAttribute.SelectedIndex = cboVRPDistanceAttribute.Items.Add("");

                for (int i = 0; i < networkDataset.AttributeCount; i++)
                {
                    INetworkAttribute networkAttribute = networkDataset.get_Attribute(i);
                    if (networkAttribute.UsageType == esriNetworkAttributeUsageType.esriNAUTCost &&
                        networkAttribute.Units < esriNetworkAttributeUnits.esriNAUSeconds)
                    {
                        string attributeName = networkAttribute.Name;

                        int cboindex = cboVRPDistanceAttribute.Items.Add(networkAttribute.Name);

                        // If the attribute is in the strArray, it should be the selected one
                        for (int j = 0; j < naSolverSettings.AccumulateAttributeNames.Count; j++)
                        {
                            if (naSolverSettings.AccumulateAttributeNames.get_Element(j) == attributeName)
                            {
                                cboVRPDistanceAttribute.SelectedIndex = cboindex;
                            }
                        }
                    }
                }
            }
            else if (laSolver != null)  // Location-Allocation LAYER
            {
                // Remove unnecessary tabs
                tabPropPages.TabPages.Remove(tabRoute);
                tabPropPages.TabPages.Remove(tabClosestFacility);
                tabPropPages.TabPages.Remove(tabODCostMatrix);
                tabPropPages.TabPages.Remove(tabServiceArea);
                tabPropPages.TabPages.Remove(tabVRP);

                // INALocationAllocationSolver
                txtLACutOff.Text             = GetStringFromObject(laSolver.DefaultCutoff);
                txtLAFacilitiesToLocate.Text = laSolver.NumberFacilitiesToLocate.ToString();
                txtLAImpParameter.Text       = laSolver.TransformationParameter.ToString();
                txtLATargetMarketShare.Text  = laSolver.TargetMarketSharePercentage.ToString();

                cboLAImpTransformation.SelectedIndex = Convert.ToInt32(laSolver.ImpedanceTransformation);
                cboLAProblemType.SelectedIndex       = Convert.ToInt32(laSolver.ProblemType);
                cboLAOutputLines.SelectedIndex       = Convert.ToInt32(laSolver.OutputLines);
                cboLATravelDirection.SelectedIndex   = Convert.ToInt32(laSolver.TravelDirection);

                //// INASolverSettings
                PopulateImpedanceNameControl(cboLAImpedance, networkDataset, naSolverSettings.ImpedanceAttributeName);
                PopulateAttributeControl(chklstLAAccumulateAttributeNames, networkDataset, naSolverSettings.AccumulateAttributeNames, esriNetworkAttributeUsageType.esriNAUTCost);
                PopulateAttributeControl(chklstLARestrictionAttributeNames, networkDataset, naSolverSettings.RestrictionAttributeNames, esriNetworkAttributeUsageType.esriNAUTRestriction);
                chkLAUseHierarchy.Enabled           = (naSolverSettings.HierarchyAttributeName.Length > 0);
                chkLAUseHierarchy.Checked           = (chkCFUseHierarchy.Enabled && naSolverSettings.UseHierarchy);
                chkLAIgnoreInvalidLocations.Checked = naSolverSettings.IgnoreInvalidLocations;
            }
            else  // Unknown type of layer
            {
                // Remove unnecessary tabs
                tabPropPages.TabPages.Remove(tabRoute);
                tabPropPages.TabPages.Remove(tabClosestFacility);
                tabPropPages.TabPages.Remove(tabODCostMatrix);
                tabPropPages.TabPages.Remove(tabServiceArea);
                tabPropPages.TabPages.Remove(tabVRP);
                tabPropPages.TabPages.Remove(tabLocationAllocation);
            }
        }
Example #22
0
        /// <summary>
        /// Updates the NALayer based on the current controls.
        /// This will update the solver settings for the solver referenced by the NALayer.
        /// </summary>
        private void UpdateNALayer(INALayer naLayer)
        {
            ILayer                      layer            = naLayer as ILayer;
            INAContext                  naContext        = naLayer.Context;
            INetworkDataset             networkDataset   = naContext.NetworkDataset;
            INALocator2                 naLocator        = naContext.Locator as INALocator2;
            INASolver                   naSolver         = naContext.Solver;
            INASolverSettings           naSolverSettings = naSolver as INASolverSettings2;
            INARouteSolver2             routeSolver      = naSolver as INARouteSolver2;
            INAClosestFacilitySolver    cfSolver         = naSolver as INAClosestFacilitySolver;
            INAODCostMatrixSolver       odSolver         = naSolver as INAODCostMatrixSolver;
            INAServiceAreaSolver2       saSolver         = naSolver as INAServiceAreaSolver2;
            INAVRPSolver                vrpSolver        = naSolver as INAVRPSolver;
            INALocationAllocationSolver laSolver         = naSolver as INALocationAllocationSolver;

            // Set Layer properties
            layer.Name = txtLayerName.Text;
            naLocator.MaxSnapTolerance   = Convert.ToDouble(txtMaxSearchTolerance.Text);
            naLocator.SnapToleranceUnits = (esriUnits)cboMaxSearchToleranceUnits.SelectedIndex;

            // Set Solver properties
            if (routeSolver != null)  // ROUTE LAYER
            {
                // INARouteSolver
                routeSolver.FindBestSequence  = chkRouteFindBestSequence.Checked;
                routeSolver.PreserveFirstStop = chkRoutePreserveFirstStop.Checked;
                routeSolver.PreserveLastStop  = chkRoutePreserveLastStop.Checked;
                routeSolver.UseTimeWindows    = chkRouteUseTimeWindows.Checked;
                routeSolver.UseStartTime      = chkRouteUseStartTime.Checked;
                routeSolver.StartTime         = System.Convert.ToDateTime(txtRouteStartTime.Text);
                routeSolver.OutputLines       = (esriNAOutputLineType)cboRouteOutputLines.SelectedIndex;

                // INASolverSettings
                naSolverSettings.ImpedanceAttributeName    = cboRouteImpedance.Text;
                naSolverSettings.UseHierarchy              = chkRouteUseHierarchy.Checked;
                naSolverSettings.IgnoreInvalidLocations    = chkRouteIgnoreInvalidLocations.Checked;
                naSolverSettings.RestrictUTurns            = (esriNetworkForwardStarBacktrack)cboRouteRestrictUTurns.SelectedIndex;
                naSolverSettings.AccumulateAttributeNames  = GetCheckedAttributeNamesFromControl(chklstRouteAccumulateAttributeNames);
                naSolverSettings.RestrictionAttributeNames = GetCheckedAttributeNamesFromControl(chklstRouteRestrictionAttributeNames);
            }

            else if (cfSolver != null)  // CLOSEST FACILITY LAYER
            {
                if (txtCFDefaultCutoff.Text.Length == 0)
                {
                    cfSolver.DefaultCutoff = null;
                }
                else
                {
                    cfSolver.DefaultCutoff = Convert.ToDouble(txtCFDefaultCutoff.Text);
                }

                if (txtCFDefaultTargetFacilityCount.Text.Length == 0)
                {
                    cfSolver.DefaultTargetFacilityCount = 1;
                }
                else
                {
                    cfSolver.DefaultTargetFacilityCount = Convert.ToInt32(txtCFDefaultTargetFacilityCount.Text);
                }

                cfSolver.TravelDirection = (esriNATravelDirection)cboCFTravelDirection.SelectedIndex;
                cfSolver.OutputLines     = (esriNAOutputLineType)cboCFOutputLines.SelectedIndex;

                // INASolverSettings
                naSolverSettings.ImpedanceAttributeName    = cboCFImpedance.Text;
                naSolverSettings.UseHierarchy              = chkCFUseHierarchy.Checked;
                naSolverSettings.IgnoreInvalidLocations    = chkCFIgnoreInvalidLocations.Checked;
                naSolverSettings.RestrictUTurns            = (esriNetworkForwardStarBacktrack)cboCFRestrictUTurns.SelectedIndex;
                naSolverSettings.AccumulateAttributeNames  = GetCheckedAttributeNamesFromControl(chklstCFAccumulateAttributeNames);
                naSolverSettings.RestrictionAttributeNames = GetCheckedAttributeNamesFromControl(chklstCFRestrictionAttributeNames);
            }

            else if (odSolver != null)  // OD COST MATRIX LAYER
            {
                if (txtODDefaultCutoff.Text.Length == 0)
                {
                    odSolver.DefaultCutoff = null;
                }
                else
                {
                    odSolver.DefaultCutoff = Convert.ToDouble(txtODDefaultCutoff.Text);
                }

                if (txtODDefaultTargetDestinationCount.Text.Length == 0)
                {
                    odSolver.DefaultTargetDestinationCount = null;
                }
                else
                {
                    odSolver.DefaultTargetDestinationCount = Convert.ToInt32(txtODDefaultTargetDestinationCount.Text);
                }

                odSolver.OutputLines = (esriNAOutputLineType)cboODOutputLines.SelectedIndex;

                // INASolverSettings
                naSolverSettings.ImpedanceAttributeName    = cboODImpedance.Text;
                naSolverSettings.UseHierarchy              = chkODUseHierarchy.Checked;
                naSolverSettings.IgnoreInvalidLocations    = chkODIgnoreInvalidLocations.Checked;
                naSolverSettings.RestrictUTurns            = (esriNetworkForwardStarBacktrack)cboODRestrictUTurns.SelectedIndex;
                naSolverSettings.AccumulateAttributeNames  = GetCheckedAttributeNamesFromControl(chklstODAccumulateAttributeNames);
                naSolverSettings.RestrictionAttributeNames = GetCheckedAttributeNamesFromControl(chklstODRestrictionAttributeNames);
            }

            else if (saSolver != null)  // SERVICE AREA SOLVER
            {
                IDoubleArray defaultBreaks = saSolver.DefaultBreaks;
                defaultBreaks.RemoveAll();
                string breaks = txtSADefaultBreaks.Text.Trim();
                breaks.Replace("  ", " ");
                string[] values = breaks.Split(' ');
                for (int iBreak = values.GetLowerBound(0); iBreak <= values.GetUpperBound(0); iBreak++)
                {
                    defaultBreaks.Add(System.Convert.ToDouble(values.GetValue(iBreak)));
                }
                saSolver.DefaultBreaks   = defaultBreaks;
                saSolver.TravelDirection = (esriNATravelDirection)cboSATravelDirection.SelectedIndex;

                saSolver.OutputPolygons            = (esriNAOutputPolygonType)cboSAOutputPolygons.SelectedIndex;
                saSolver.OverlapPolygons           = chkSAOverlapPolygons.Checked;
                saSolver.SplitPolygonsAtBreaks     = chkSASplitPolygonsAtBreaks.Checked;
                saSolver.MergeSimilarPolygonRanges = chkSAMergeSimilarPolygonRanges.Checked;
                saSolver.TrimOuterPolygon          = chkSATrimOuterPolygon.Checked;
                saSolver.TrimPolygonDistance       = Convert.ToDouble(this.txtSATrimPolygonDistance.Text);
                saSolver.TrimPolygonDistanceUnits  = (esriUnits)cboSATrimPolygonDistanceUnits.SelectedIndex;

                if (cboSAOutputLines.SelectedIndex == 0)
                {
                    saSolver.OutputLines = (esriNAOutputLineType)cboSAOutputLines.SelectedIndex;
                }
                else // Does not support Straight lines, so not in combobox, up by one to account for this
                {
                    saSolver.OutputLines = (esriNAOutputLineType)(cboSAOutputLines.SelectedIndex + 1);
                }

                saSolver.OverlapLines       = chkSAOverlapLines.Checked;
                saSolver.SplitLinesAtBreaks = chkSASplitLinesAtBreaks.Checked;
                saSolver.IncludeSourceInformationOnLines = this.chkSAIncludeSourceInformationOnLines.Checked;

                // INASolverSettings
                naSolverSettings.ImpedanceAttributeName    = cboSAImpedance.Text;
                naSolverSettings.IgnoreInvalidLocations    = chkSAIgnoreInvalidLocations.Checked;
                naSolverSettings.RestrictUTurns            = (esriNetworkForwardStarBacktrack)cboSARestrictUTurns.SelectedIndex;
                naSolverSettings.AccumulateAttributeNames  = GetCheckedAttributeNamesFromControl(chklstSAAccumulateAttributeNames);
                naSolverSettings.RestrictionAttributeNames = GetCheckedAttributeNamesFromControl(chklstSARestrictionAttributeNames);
            }
            else if (vrpSolver != null)
            {
                naSolverSettings.ImpedanceAttributeName = cboVRPTimeAttribute.Text;
                naSolverSettings.AccumulateAttributeNames.RemoveAll();
                IStringArray strArray = naSolverSettings.AccumulateAttributeNames;
                strArray.RemoveAll();
                strArray.Add(cboVRPDistanceAttribute.Text);
                naSolverSettings.AccumulateAttributeNames = strArray;

                vrpSolver.CapacityCount  = Convert.ToInt32(txtVRPCapacityCount.Text);
                vrpSolver.DefaultDate    = Convert.ToDateTime(txtVRPDefaultDate.Text);
                vrpSolver.TimeFieldUnits = ((esriNetworkAttributeUnits)cboVRPTimeFieldUnits.SelectedIndex) + 20;

                // there cannot be unknown units for a VRP, so the index is offset by 1
                vrpSolver.DistanceFieldUnits               = (esriNetworkAttributeUnits)cboVRPDistanceFieldUnits.SelectedIndex + 1;
                naSolverSettings.RestrictUTurns            = (esriNetworkForwardStarBacktrack)cboVRPAllowUTurns.SelectedIndex;
                vrpSolver.OutputLines                      = (esriNAOutputLineType)cboVRPOutputShapeType.SelectedIndex;
                vrpSolver.TimeWindowViolationPenaltyFactor = cboVRPTimeWindow.SelectedIndex;
                vrpSolver.ExcessTransitTimePenaltyFactor   = cboVRPTransitTime.SelectedIndex;

                naSolverSettings.UseHierarchy = chkVRPUseHierarchy.Checked;

                naSolverSettings.RestrictionAttributeNames = GetCheckedAttributeNamesFromControl(chklstVRPRestrictionAttributeNames);
            }
            else if (laSolver != null)  // Location-Allocation LAYER
            {
                if (txtLACutOff.Text.Length == 0)
                {
                    laSolver.DefaultCutoff = null;
                }
                else if (Convert.ToDouble(txtLACutOff.Text) == 0.0)
                {
                    laSolver.DefaultCutoff = null;
                }
                else
                {
                    laSolver.DefaultCutoff = Convert.ToDouble(txtLACutOff.Text);
                }

                if (txtLAFacilitiesToLocate.Text.Length == 0)
                {
                    laSolver.NumberFacilitiesToLocate = 1;
                }
                else
                {
                    laSolver.NumberFacilitiesToLocate = Convert.ToInt32(txtLAFacilitiesToLocate.Text);
                }

                laSolver.ProblemType                 = (esriNALocationAllocationProblemType)cboLAProblemType.SelectedIndex;
                laSolver.ImpedanceTransformation     = (esriNAImpedanceTransformationType)cboLAImpTransformation.SelectedIndex;
                laSolver.TransformationParameter     = Convert.ToDouble(txtLAImpParameter.Text);
                laSolver.TargetMarketSharePercentage = Convert.ToDouble(txtLATargetMarketShare.Text);
                laSolver.TravelDirection             = (esriNATravelDirection)cboLATravelDirection.SelectedIndex;
                laSolver.OutputLines                 = (esriNAOutputLineType)cboLAOutputLines.SelectedIndex;

                //// INASolverSettings
                naSolverSettings.ImpedanceAttributeName    = cboLAImpedance.Text;
                naSolverSettings.UseHierarchy              = chkLAUseHierarchy.Checked;
                naSolverSettings.AccumulateAttributeNames  = GetCheckedAttributeNamesFromControl(chklstLAAccumulateAttributeNames);
                naSolverSettings.RestrictionAttributeNames = GetCheckedAttributeNamesFromControl(chklstLARestrictionAttributeNames);
                naSolverSettings.IgnoreInvalidLocations    = chkLAIgnoreInvalidLocations.Checked;
            }
        }
Example #23
0
        /// <summary>
        /// Set solver settings
        /// </summary>
        public void SetSolverSettings()
        {
            //Set Route specific Settings
            INASolver naSolver = m_NAContext.Solver;

            INAClosestFacilitySolver cfSolver = naSolver as INAClosestFacilitySolver;

            if (txtCutOff.Text.Length > 0 && IsNumeric(txtCutOff.Text.Trim()))
            {
                cfSolver.DefaultCutoff = txtCutOff.Text;
            }
            else
            {
                cfSolver.DefaultCutoff = null;
            }

            if (txtTargetFacility.Text.Length > 0 && IsNumeric(txtTargetFacility.Text))
            {
                cfSolver.DefaultTargetFacilityCount = int.Parse(txtTargetFacility.Text);
            }
            else
            {
                cfSolver.DefaultTargetFacilityCount = 1;
            }

            cfSolver.OutputLines     = esriNAOutputLineType.esriNAOutputLineTrueShapeWithMeasure;
            cfSolver.TravelDirection = esriNATravelDirection.esriNATravelDirectionToFacility;

            // Set generic solver settings
            // Set the impedance attribute
            INASolverSettings naSolverSettings;

            naSolverSettings = naSolver as INASolverSettings;
            naSolverSettings.ImpedanceAttributeName = cboCostAttribute.Text;

            // Set the OneWay Restriction if necessary
            IStringArray restrictions;

            restrictions = naSolverSettings.RestrictionAttributeNames;
            restrictions.RemoveAll();
            if (chkUseRestriction.Checked)
            {
                restrictions.Add("oneway");
            }

            naSolverSettings.RestrictionAttributeNames = restrictions;

            //Restrict UTurns
            naSolverSettings.RestrictUTurns         = esriNetworkForwardStarBacktrack.esriNFSBNoBacktrack;
            naSolverSettings.IgnoreInvalidLocations = true;

            // Set the Hierarchy attribute
            naSolverSettings.UseHierarchy = chkUseHierarchy.Checked;
            if (naSolverSettings.UseHierarchy)
            {
                naSolverSettings.HierarchyAttributeName = "HierarchyMultiNet";
            }

            // Do not forget to update the context after you set your impedance
            naSolver.UpdateContext(m_NAContext, GetDENetworkDataset(m_NAContext.NetworkDataset), new GPMessagesClass());
        }
        public static void UpdateEIDArrayParameterValuesFromEIDLists(INetworkAnalystExtension nax, Dictionary <string, List <int> > eidsBySourceName, string baseName)
        {
            if (nax == null)
            {
                return;
            }

            bool             naxEnabled = false;
            IExtensionConfig naxConfig  = nax as IExtensionConfig;

            naxEnabled = naxConfig.State == esriExtensionState.esriESEnabled;

            if (!naxEnabled)
            {
                return;
            }

            INAWindow       naWindow  = nax.NAWindow;
            INALayer        naLayer   = null;
            INAContext      naContext = null;
            INetworkDataset nds       = null;

            naLayer = naWindow.ActiveAnalysis;
            if (naLayer != null)
            {
                naContext = naLayer.Context;
            }

            if (naContext != null)
            {
                nds = naContext.NetworkDataset;
            }

            if (nds == null)
            {
                return;
            }

            IDatasetComponent dsComponent = nds as IDatasetComponent;
            IDENetworkDataset deNet       = dsComponent.DataElement as IDENetworkDataset;

            INASolver          naSolver          = naContext.Solver;
            INASolverSettings2 naSolverSettings2 = naSolver as INASolverSettings2;

            if (naSolverSettings2 == null)
            {
                return;
            }

            string  prefix = GetEIDArrayPrefixFromBaseName(baseName);
            VarType vt     = GetEIDArrayParameterType();

            int cAttributes = nds.AttributeCount;

            for (int a = 0; a < cAttributes; ++a)
            {
                INetworkAttribute2 netAttribute = nds.get_Attribute(a) as INetworkAttribute2;
                IArray             netParams    = netAttribute.Parameters;
                int    cParams = netParams.Count;
                object paramValue;
                for (int p = 0; p < cParams; ++p)
                {
                    INetworkAttributeParameter param = netParams.get_Element(p) as INetworkAttributeParameter;
                    if (param.VarType != (int)vt)
                    {
                        continue;
                    }

                    string paramName  = param.Name;
                    string sourceName = GetSourceNameFromParameterName(prefix, paramName);
                    if (sourceName.Length == 0)
                    {
                        continue;
                    }

                    List <int> eids = null;
                    if (eidsBySourceName.TryGetValue(sourceName, out eids))
                    {
                        if (eids != null)
                        {
                            if (eids.Count == 0)
                            {
                                eids = null;
                            }
                        }
                    }

                    paramValue = (eids != null) ? eids.ToArray() : null;
                    naSolverSettings2.set_AttributeParameterValue(netAttribute.Name, param.Name, paramValue);
                }
            }
        }
Example #25
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();
        }
Example #26
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("未选取或更新起点和终点,请重新定位!");
            }
        }