示例#1
0
        private void FormMain_Load(object sender, EventArgs e)
        {
            Ctrl_Tab.SelectedIndex = 1;
            Ctrl_Tab.SelectedIndex = 0;

            IFeatureWorkspace pFWorkspace    = OpenWorkspace(@"data.gdb") as IFeatureWorkspace;
            INetworkDataset   networkDataset = OpenNetworkDataset(pFWorkspace as IWorkspace, "rdCenLineDataSet_ND", "rdCenLineDataSet");

            m_NAContext = CreateSolverContext(networkDataset);
            INetworkLayer pNetworkLayer = new NetworkLayerClass();

            pNetworkLayer.NetworkDataset = networkDataset;
            ILayer pLayer = pNetworkLayer as ILayer;

            pLayer.Name = "NetworkLayer";
            Ctrl_Map.AddLayer(pLayer, 0);

            IFeatureLayer pJunctionLayer = new FeatureLayerClass();

            pJunctionLayer.FeatureClass = pFWorkspace.OpenFeatureClass("rdCenLineDataSet_ND_Junctions");
            pJunctionLayer.Name         = pJunctionLayer.FeatureClass.AliasName;
            Ctrl_Map.AddLayer(pJunctionLayer, 0);
            IFeatureLayer pRoadLayer = new FeatureLayerClass();

            pRoadLayer.FeatureClass = pFWorkspace.OpenFeatureClass("road_toLine");
            pRoadLayer.Name         = pRoadLayer.FeatureClass.AliasName;
            Ctrl_Map.AddLayer(pRoadLayer, 0);

            INALayer pNALayer = m_NAContext.Solver.CreateLayer(m_NAContext);

            (pNALayer as ILayer).Name = m_NAContext.Solver.DisplayName;
            Ctrl_Map.AddLayer(pNALayer as ILayer, 0);
        }
示例#2
0
        //加载参与分析的点要素
        public static void LoadNANetworkLocations(string strNAClassName,
                                                  IFeatureClass inputFC, INAContext m_NAContext, double snapTolerance)
        {
            //ITable b1 = inputFC as ITable;//将传入的要素类转化为一个Table对象,这个要素类如站点类、障碍点类等。
            //int i1 = b1.RowCount(null);//获取行数
            INAClass  naClass;
            INamedSet classes;

            classes = m_NAContext.NAClasses;                              //上下文对象的有关网络分析类的对象集合NamedSet属性
            naClass = classes.get_ItemByName(strNAClassName) as INAClass; //通过传入的名称参数,往classes中获取对应的NAClass
            naClass.DeleteAllRows();                                      //删除naClass中的所有要素
            INAClassLoader classLoader = new NAClassLoader();             //新建一个NAClassLoader对象

            classLoader.Locator = m_NAContext.Locator;                    //将上下文对象的locator属性赋给classLoader,locator用于确定网络上要加载的要素的位置。
            if (snapTolerance > 0)
            {
                classLoader.Locator.SnapTolerance = snapTolerance; //设置容差
            }
            classLoader.NAClass = naClass;                         //给classLoader对象的NAClass属性赋值

            //设置字段映射
            INAClassFieldMap fieldMap = null;

            fieldMap = new NAClassFieldMap();
            fieldMap.set_MappedField("FID", "FID"); //set_MappedField方法用于建立源数据到NAClass类的映射
            classLoader.FieldMap = fieldMap;        //给classLoader对象的FieldMap属性赋值
            int            rowsIn        = 0;
            int            rowLocated    = 0;
            IFeatureCursor featureCursor = inputFC.Search(null, true);

            classLoader.Load((ICursor)featureCursor, null, ref rowsIn, ref rowLocated);//ref类型关键字表示对于该参数,在函数过程中可以读也可以写,相当于引用传递。引用传递参数允许函数成员更改参数的值,并保持该更改。
            ((INAContextEdit)m_NAContext).ContextChanged();
        }
示例#3
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);
        }
示例#5
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);
        }
示例#6
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");
        }
		public EditorForm(IApplication app, INAContext context, IFeature barrier)
		{
			m_barrier = barrier;
			m_app = app;
			m_context = context;

			InitializeComponent();
			LoadDatagrids();
		}
        public EditorForm(IApplication app, INAContext context, IFeature barrier)
        {
            m_barrier = barrier;
            m_app     = app;
            m_context = context;

            InitializeComponent();
            LoadDatagrids();
        }
        /// <summary>
		/// Initialize the solver by calling the ArcGIS Network Analyst extension functions.
		/// </summary>
		private void Initialize()
		{
			IFeatureWorkspace featureWorkspace = null;
			INetworkDataset networkDataset = null;
			try
			{
				// Open the Network Dataset
				IWorkspace workspace = OpenWorkspace(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), @"ArcGIS\data\SanFrancisco\SanFrancisco.gdb"));
                networkDataset = OpenNetworkDataset(workspace, "Transportation", "Streets_ND");
				featureWorkspace = workspace as IFeatureWorkspace;
			}
			catch (Exception ex)
			{
				System.Windows.Forms.MessageBox.Show("Unable to open dataset. Error Message: " + ex.Message);
				this.Close();
				return;
			}

			// Create NAContext and NASolver
			m_NAContext = CreateSolverContext(networkDataset);

			// Get available cost attributes from the network dataset
			INetworkAttribute networkAttribute;
			for (int i = 0; i < networkDataset.AttributeCount - 1; i++)
			{
				networkAttribute = networkDataset.get_Attribute(i);
				if (networkAttribute.UsageType == esriNetworkAttributeUsageType.esriNAUTCost)
				{
					comboCostAttribute.Items.Add(networkAttribute.Name);
				}
			}
			comboCostAttribute.SelectedIndex = 0;

			textTargetFacility.Text = "";
			textCutoff.Text = "";

			// Load locations from feature class
			IFeatureClass inputFClass = featureWorkspace.OpenFeatureClass("Stores");
			LoadNANetworkLocations("Origins", inputFClass, 100);
			inputFClass = featureWorkspace.OpenFeatureClass("Hospitals");
			LoadNANetworkLocations("Destinations", inputFClass, 5100);

			// Create layer for network dataset and add to ArcMap
			INetworkLayer networkLayer = new NetworkLayerClass();
			networkLayer.NetworkDataset = networkDataset;
			var layer = networkLayer as ILayer;
			layer.Name = "Network Dataset";
			axMapControl.AddLayer(layer, 0);

			// Create a network analysis layer and add to ArcMap
			INALayer naLayer = m_NAContext.Solver.CreateLayer(m_NAContext);
			layer = naLayer as ILayer;
			layer.Name = m_NAContext.Solver.DisplayName;
			axMapControl.AddLayer(layer, 0);
		}
        /// <summary>
		/// Initialize the solver by calling the ArcGIS Network Analyst extension functions.
		/// </summary>
		private void Initialize()
		{
			IFeatureWorkspace featureWorkspace = null;
			INetworkDataset networkDataset = null;
			try
			{
				// Open the Network Dataset
				IWorkspace workspace = OpenWorkspace(Application.StartupPath + @"\..\..\..\..\..\Data\SanFrancisco\SanFrancisco.gdb");
                networkDataset = OpenNetworkDataset(workspace, "Transportation", "Streets_ND");
				featureWorkspace = workspace as IFeatureWorkspace;
			}
			catch (Exception ex)
			{
				System.Windows.Forms.MessageBox.Show("Unable to open dataset. Error Message: " + ex.Message);
				this.Close();
				return;
			}

			// Create NAContext and NASolver
			m_NAContext = CreateSolverContext(networkDataset);

			// Get available cost attributes from the network dataset
			INetworkAttribute networkAttribute;
			for (int i = 0; i < networkDataset.AttributeCount - 1; i++)
			{
				networkAttribute = networkDataset.get_Attribute(i);
				if (networkAttribute.UsageType == esriNetworkAttributeUsageType.esriNAUTCost)
				{
					comboCostAttribute.Items.Add(networkAttribute.Name);
				}
			}
			comboCostAttribute.SelectedIndex = 0;

			textTargetFacility.Text = "";
			textCutoff.Text = "";

			// Load locations from feature class
			IFeatureClass inputFClass = featureWorkspace.OpenFeatureClass("Stores");
			LoadNANetworkLocations("Origins", inputFClass, 100);
			inputFClass = featureWorkspace.OpenFeatureClass("Hospitals");
			LoadNANetworkLocations("Destinations", inputFClass, 5100);

			// Create layer for network dataset and add to ArcMap
			INetworkLayer networkLayer = new NetworkLayerClass();
			networkLayer.NetworkDataset = networkDataset;
			var layer = networkLayer as ILayer;
			layer.Name = "Network Dataset";
			axMapControl.AddLayer(layer, 0);

			// Create a network analysis layer and add to ArcMap
			INALayer naLayer = m_NAContext.Solver.CreateLayer(m_NAContext);
			layer = naLayer as ILayer;
			layer.Name = m_NAContext.Solver.DisplayName;
			axMapControl.AddLayer(layer, 0);
		}
示例#11
0
        /// <summary>
        /// Create NASolver and NAContext
        /// </summary>
        /// <param name="networkDataset">Input network dataset</param>
        /// <returns>NAContext</returns>
        public void CreateSolverContext(INetworkDataset networkDataset)
        {
            if (networkDataset == null)
            {
                return;
            }

            //Get the Data Element
            IDENetworkDataset deNDS = GetDENetworkDataset(networkDataset);

            INASolver naSolver = new NAClosestFacilitySolver();

            m_NAContext = naSolver.CreateContext(deNDS, naSolver.Name);
            ((INAContextEdit)m_NAContext).Bind(networkDataset, new GPMessagesClass());
        }
示例#12
0
        private void CreateContextAndSolver(INetworkDataset networkDataset)
        {
            if (networkDataset == null)
            {
                return;
            }

            IDatasetComponent datasetComponent = networkDataset as IDatasetComponent;
            IDENetworkDataset deNetworkDataset = datasetComponent.DataElement as IDENetworkDataset;

            INASolver naSolver = new NAServiceAreaSolverClass();

            m_naContext = naSolver.CreateContext(deNetworkDataset, "ServiceArea");
            INAContextEdit naContextEdit = m_naContext as INAContextEdit;

            naContextEdit.Bind(networkDataset, new GPMessagesClass());
        }
示例#13
0
        public string Solve(INAContext pNAContext, IGPMessages pGPMessages)
        {
            string str = "";

            try
            {
                str = "Error when solving";
                if (!pNAContext.Solver.Solve(pNAContext, pGPMessages, null))
                {
                    return("OK");
                }
                return("Partial Solution");
            }
            catch (Exception exception)
            {
                return(str + " Error Description " + exception.Message);
            }
        }
示例#14
0
		// Get the Impedance Cost form the CFRoute Class Output

		public void GetCFOutput(string strNAClass,ref INAContext _m_pNAContext )
		{
			int IncidentID;
			int FacilityID;
			int FacilityRank;
			ICursor pCursor;
			IRow pRow;

			ITable ptable;
            
			ptable=_m_pNAContext.NAClasses.get_ItemByName(strNAClass) as ITable;
			//ptable=_m_pNAContext.NAClasses.get_Item(3) as ITable;
			//ptable.ToString

			

			
			//    for(int ii=0;ii<4;ii++)
			//	MessageBox.Show(_m_pNAContext.NAClasses.get_Name(ii));

			if(ptable==null)
			{
				return;
			}
			
			if(ptable.RowCount(null)>0)
			{

				pCursor = ptable.Search(null, false);
				pRow = pCursor.NextRow();
				while(pRow!=null)
				{
					IncidentID = Convert.ToInt32(pRow.get_Value(ptable.FindField("IncidentID")).ToString());
					FacilityID =Convert.ToInt32(pRow.get_Value(ptable.FindField("FacilityID")).ToString());
					FacilityRank = Convert.ToInt32(pRow.get_Value(ptable.FindField("FacilityRank")).ToString());
					pRow=pCursor.NextRow();
				
				}

			
			}

		
		}
 /// <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());
     }
 }
示例#16
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);
        }
示例#17
0
        // Get the Impedance Cost form the CFRoute Class Output
        public void GetCFOutput(string strNAClass,ref INAContext _m_pNAContext )
        {
            int IncidentID;
            int FacilityID;
            int FacilityRank;
            ICursor pCursor;
            IRow pRow;

            ITable ptable;

            ptable=_m_pNAContext.NAClasses.get_ItemByName(strNAClass) as ITable;
            //ptable=_m_pNAContext.NAClasses.get_Item(3) as ITable;
            //ptable.ToString

            //    for(int ii=0;ii<4;ii++)
            //	MessageBox.Show(_m_pNAContext.NAClasses.get_Name(ii));

            if(ptable==null)
            {
                return;
            }

            if(ptable.RowCount(null)>0)
            {

                pCursor = ptable.Search(null, false);
                pRow = pCursor.NextRow();
                while(pRow!=null)
                {
                    IncidentID = Convert.ToInt32(pRow.get_Value(ptable.FindField("IncidentID")).ToString());
                    FacilityID =Convert.ToInt32(pRow.get_Value(ptable.FindField("FacilityID")).ToString());
                    FacilityRank = Convert.ToInt32(pRow.get_Value(ptable.FindField("FacilityRank")).ToString());
                    pRow=pCursor.NextRow();

                }

            }
        }
        private void UpdateSelectionEIDArrayParameterValues()
        {
            IMap map = ActiveMap;

            if (map == null)
            {
                return;
            }

            INAWindow       naWindow  = m_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;
            }

            string  baseName = SubsetHelperUI.SelectionEIDArrayBaseName;
            VarType vt       = SubsetHelperUI.GetEIDArrayParameterType();

            List <string> sourceNames = SubsetHelperUI.FindParameterizedSourceNames(nds, baseName, vt);
            Dictionary <string, ILongArray> oidArraysBySourceName = SubsetHelperUI.GetOIDArraysBySourceNameFromMapSelection(map, sourceNames);

            SubsetHelperUI.UpdateEIDArrayParameterValuesFromOIDArrays(m_nax, oidArraysBySourceName, baseName);
        }
        private void UpdateGraphicsEIDArrayParameterValues()
        {
            IGraphicsContainer graphics = ActiveGraphics;

            if (graphics == null)
            {
                return;
            }

            INAWindow       naWindow  = m_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;
            }

            string  baseName = SubsetHelperUI.GraphicsEIDArrayBaseName;
            VarType vt       = SubsetHelperUI.GetEIDArrayParameterType();

            List <string> sourceNames    = SubsetHelperUI.FindParameterizedSourceNames(nds, baseName, vt);
            IGeometry     searchGeometry = SubsetHelperUI.GetSearchGeometryFromGraphics(graphics);

            SubsetHelperUI.UpdateEIDArrayParameterValuesFromGeometry(m_nax, searchGeometry, baseName);
        }
示例#20
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);
        }
示例#21
0
        private void Solve()
        {
            INALayer         layer     = this.CreateRouteAnalysisLayer("Route", this.m_pNetworkDataset);
            INAContext       nAContext = layer.Context;
            INAClass         class2    = nAContext.NAClasses.get_ItemByName("Stops") as INAClass;
            IFeatureClass    class3    = nAContext.NAClasses.get_ItemByName("Routes") as IFeatureClass;
            INAClassFieldMap map       = new NAClassFieldMapClass();

            map.set_MappedField("Name", this.SHAPE_INPUT_NAME_FIELD);
            INAClassLoader loader = new NAClassLoaderClass
            {
                Locator  = nAContext.Locator,
                NAClass  = class2,
                FieldMap = map
            };
            int rowsInCursor = 0;
            int rowsLocated  = 0;

            loader.Load(this.m_pInputStopsFClass.Search(new QueryFilterClass(), false) as ICursor,
                        new CancelTrackerClass(), ref rowsInCursor, ref rowsLocated);
            nAContext.Solver.Solve(nAContext, new GPMessagesClass(), new CancelTrackerClass());
            this.SaveLayerToDisk(layer as ILayer, Environment.CurrentDirectory + @"\Route.lyr");
        }
        public static void ClearEIDArrayParameterValues(INetworkAnalystExtension nax, string baseName)
        {
            try
            {
                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;
                }

                VarType       vt          = SubsetHelperUI.GetEIDArrayParameterType();
                List <string> sourceNames = SubsetHelperUI.FindParameterizedSourceNames(nds, baseName, vt);

                SubsetHelperUI.ClearEIDArrayParameterValues(nax, sourceNames, baseName);
                SubsetHelperUI.PushParameterValuesToNetwork(nax);
            }
            catch (Exception ex)
            {
                string msg = SubsetHelperUI.GetFullExceptionMessage(ex);
                MessageBox.Show(msg, "Clear Network Element Array Parameters");
            }
        }
        public override void OnClick()
        {
            IEngineNetworkAnalystEnvironment naEnv    = new EngineNetworkAnalystEnvironmentClass();
            IEngineNetworkAnalystHelper      naHelper = naEnv as IEngineNetworkAnalystHelper;
            IEngineNAWindow naWindow = naEnv.NAWindow;

            // Get the NALayer and corresponding NAContext of the layer that
            // was right-clicked on in the table of contents
            // m_MapControl.CustomProperty was set in frmMain.axTOCControl1_OnMouseDown
            INALayer   naLayer   = (INALayer)m_mapControl.CustomProperty;
            INAContext naContext = naLayer.Context;

            // Set the active Analysis layer
            if (naWindow.ActiveAnalysis != naLayer)
            {
                naWindow.ActiveAnalysis = naLayer;
            }

            // Remember what the current category is
            IEngineNAWindowCategory currentCategory = naWindow.ActiveCategory;

            // Loop through deleting all the items from all the categories
            INamedSet naClasses = naContext.NAClasses;

            for (int i = 0; i < naClasses.Count; i++)
            {
                IEngineNAWindowCategory category = naWindow.get_CategoryByNAClassName(naClasses.get_Name(i));
                naWindow.ActiveCategory = category;
                naHelper.DeleteAllNetworkLocations();
            }

            //Reset to the original category
            naWindow.ActiveCategory = currentCategory;

            m_mapControl.Refresh(esriViewDrawPhase.esriViewGeography, naLayer, m_mapControl.Extent);
        }
        /// <summary>
        /// 以图层的方法插入相关元素 如经过站点、障碍点、障碍线、障碍多边形等
        /// </summary>
        /// <param name="pNAContext">网络分析上下文</param>
        /// <param name="strNAClassName">Routes,Stops、Barriers、PolylineBarriers\PolygonBarriers</param>
        /// <param name="inputFeatuerClass">要素类</param>
        /// <param name="dSnapTolerance">阈值</param>
        public static void LoadNANetWorkLocations(INAContext pNAContext, string strNAClassName, IFeatureClass inputFeatuerClass, double dSnapTolerance)
        {
            INAClass  pNAClass;
            INamedSet pNamedSet;

            pNamedSet = pNAContext.NAClasses;
            pNAClass  = pNamedSet.get_ItemByName(strNAClassName) as INAClass;
            ISpatialFilter filer = new SpatialFilterClass();

            filer.WhereClause = "";
            int count = inputFeatuerClass.FeatureCount(filer as IQueryFilter);

            //删除已存在的元素
            pNAClass.DeleteAllRows();
            //创建NAClassLoader,设置捕捉容限值
            INAClassLoader pNAClassLoader = new NAClassLoaderClass();

            pNAClassLoader.Locator = pNAContext.Locator;
            if (dSnapTolerance > 0)
            {
                pNAClassLoader.Locator.SnapTolerance = dSnapTolerance;
            }
            pNAClassLoader.NAClass = pNAClass;
            //字段匹配
            INAClassFieldMap pNAClassFieldMap = new NAClassFieldMapClass();

            pNAClassFieldMap.CreateMapping(pNAClass.ClassDefinition, inputFeatuerClass.Fields);
            pNAClassLoader.FieldMap = pNAClassFieldMap;
            //加载要素类数据
            int            iRows          = 0;
            int            iRowsLocated   = 0;
            IFeatureCursor pFeatureCursor = inputFeatuerClass.Search(null, true);

            pNAClassLoader.Load((ICursor)pFeatureCursor, null, ref iRows, ref iRowsLocated);
            ((INAContextEdit)pNAContext).ContextChanged();
        }
示例#25
0
        public bool ShowModal(IMapControl3 mapControl, IEngineNetworkAnalystEnvironment naEnv)
        {
            // Initialize variables
            m_okClicked        = false;
            m_listDisplayTable = new System.Collections.ArrayList();

            // Get the NALayer and NAContext
            INALayer   naLayer   = naEnv.NAWindow.ActiveAnalysis;
            INAContext naContext = naLayer.Context;

            //Get the active category
            IEngineNAWindowCategory2 activeCategory = naEnv.NAWindow.ActiveCategory as IEngineNAWindowCategory2;

            if (activeCategory == null)
            {
                return(false);
            }

            INAClass   naClass    = activeCategory.NAClass;
            IDataset   naDataset  = naClass as IDataset;
            IDataLayer pDataLayer = activeCategory.DataLayer;

            ILayer           pLayer           = pDataLayer as ILayer;
            IFeatureLayer    pFeatureLayer    = pDataLayer as IFeatureLayer;
            IStandaloneTable pStandaloneTable = pDataLayer as IStandaloneTable;

            esriGeometryType targetGeoType = esriGeometryType.esriGeometryNull;

            String dataLayerName = "";

            if (pFeatureLayer != null)
            {
                if (pLayer.Valid)
                {
                    IFeatureClass pFeatureClass = pFeatureLayer.FeatureClass;
                    if (pFeatureClass != null)
                    {
                        targetGeoType = pFeatureClass.ShapeType;
                        dataLayerName = pLayer.Name;
                    }
                }
            }
            else if (pStandaloneTable != null)
            {
                dataLayerName = pStandaloneTable.Name;
            }

            if (dataLayerName.Length == 0)
            {
                return(false);
            }

            this.Text = "Load Items into " + dataLayerName;

            // Loop through all the sourcedisplayTables having targetGeoType to the combo box and the
            // list of displayTables

            IEnumLayer    sourceLayers       = null;
            ILayer        sourceLayer        = null;
            IDisplayTable sourceDisplayTable = null;
            UID           searchInterfaceUID = new UID();

            if (targetGeoType != esriGeometryType.esriGeometryNull)
            {
                searchInterfaceUID.Value = typeof(IFeatureLayer).GUID.ToString("B");
                sourceLayers             = mapControl.Map.get_Layers(searchInterfaceUID, true);

                sourceLayer = sourceLayers.Next();
                while (sourceLayer != null)
                {
                    IFeatureLayer sourceFeatureLayer = sourceLayer as IFeatureLayer;
                    sourceDisplayTable = sourceLayer as IDisplayTable;

                    if ((sourceFeatureLayer != null) && (sourceDisplayTable != null))
                    {
                        IFeatureClass    sourceFeatureClass = sourceFeatureLayer.FeatureClass;
                        esriGeometryType sourceGeoType      = sourceFeatureClass.ShapeType;
                        if ((sourceGeoType == targetGeoType) ||
                            (targetGeoType == esriGeometryType.esriGeometryPoint && sourceGeoType == esriGeometryType.esriGeometryMultipoint))
                        {
                            // Add the layer name to the combobox and the layer to the list
                            cboInputData.Items.Add(sourceLayer.Name);
                            m_listDisplayTable.Add(sourceDisplayTable);
                        }
                    }

                    sourceLayer = sourceLayers.Next();
                }
            }
            else //if (targetGeoType == esriGeometryType.esriGeometryNull)
            {
                IStandaloneTableCollection sourceStandaloneTables = mapControl.Map as IStandaloneTableCollection;
                IStandaloneTable           sourceStandaloneTable  = null;
                sourceDisplayTable = null;

                int count = 0;
                if (sourceStandaloneTables != null)
                {
                    count = sourceStandaloneTables.StandaloneTableCount;
                }

                for (int i = 0; i < count; ++i)
                {
                    sourceStandaloneTable = sourceStandaloneTables.get_StandaloneTable(i);
                    sourceDisplayTable    = sourceStandaloneTable as IDisplayTable;

                    if ((sourceStandaloneTable != null) && (sourceDisplayTable != null))
                    {
                        // Add the table name to the combobox and the layer to the list
                        cboInputData.Items.Add(sourceStandaloneTable.Name);
                        m_listDisplayTable.Add(sourceDisplayTable);
                    }
                }

                searchInterfaceUID.Value = typeof(INALayer).GUID.ToString("B");
                sourceLayers             = mapControl.Map.get_Layers(searchInterfaceUID, true);

                sourceLayer = sourceLayers.Next();
                while (sourceLayer != null)
                {
                    INALayer sourceNALayer = sourceLayer as INALayer;
                    if (sourceNALayer != null)
                    {
                        sourceStandaloneTables = sourceNALayer as IStandaloneTableCollection;
                        sourceStandaloneTable  = null;
                        sourceDisplayTable     = null;

                        count = 0;
                        if (sourceStandaloneTables != null)
                        {
                            count = sourceStandaloneTables.StandaloneTableCount;
                        }

                        for (int i = 0; i < count; ++i)
                        {
                            sourceStandaloneTable = sourceStandaloneTables.get_StandaloneTable(i);
                            sourceDisplayTable    = sourceStandaloneTable as IDisplayTable;

                            if ((sourceStandaloneTable != null) && (sourceDisplayTable != null))
                            {
                                // Add the table name to the combobox and the layer to the list
                                cboInputData.Items.Add(sourceStandaloneTable.Name);
                                m_listDisplayTable.Add(sourceDisplayTable);
                            }
                        }
                    }

                    sourceLayer = sourceLayers.Next();
                }
            }

            //Select the first display table from the list
            if (cboInputData.Items.Count > 0)
            {
                cboInputData.SelectedIndex = 0;
            }

            // Show the window
            this.ShowDialog();

            // If we selected a layer and clicked OK, load the locations
            if (m_okClicked && (cboInputData.SelectedIndex >= 0))
            {
                // Get a cursor on the source display table (either though the selection set or table)
                // Use IDisplayTable because it accounts for joins, querydefs, etc.
                // IDisplayTable is implemented by FeatureLayers and StandaloneTables.
                //
                IDisplayTable displayTable = m_listDisplayTable[cboInputData.SelectedIndex] as IDisplayTable;
                ICursor       cursor;
                if (chkUseSelection.Checked)
                {
                    ISelectionSet selSet;
                    selSet = displayTable.DisplaySelectionSet;
                    selSet.Search(null, false, out cursor);
                }
                else
                {
                    cursor = displayTable.SearchDisplayTable(null, false);
                }

                // Setup NAClassLoader and Load Locations
                INAClassLoader2 naClassLoader = new NAClassLoader() as INAClassLoader2;
                naClassLoader.Initialize(naContext, naDataset.Name, cursor);

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

                int rowsIn      = 0;
                int rowsLocated = 0;
                naClassLoader.Load(cursor, null, ref rowsIn, ref rowsLocated);

                return(true);
            }

            return(false);
        }
示例#26
0
        //LoadNANetworkLocations
        public void LoadNANetworkLocations(string strNAClassName,IFeatureClass pInputFC,double SnapTolerance,ref INAContext m_pNAContext)
        {
            INAClass pNAClass;
            INamedSet pClasses;
            //get The collection of classes associated with the analysis
            pClasses = m_pNAContext.NAClasses;

            /*
            for(int ii=0;ii<pClasses.Count;ii++)
            {
                MessageBox.Show(pClasses.get_Name(ii));

            }
            */

            pNAClass = pClasses.get_ItemByName(strNAClassName) as INAClass;

            //Remove all items added to the class (for example, stops or incidents).
            pNAClass.DeleteAllRows();

            // Create a NAClassLoader and set the snap tolerance (meters unit)
            //NAClassLoader to populate stop locations from a point feature class.

            INAClassLoader pLoader=new NAClassLoaderClass();

            pLoader.Locator = m_pNAContext.Locator;

            if( SnapTolerance > 0)
            {
                pLoader.Locator.SnapTolerance = SnapTolerance;

            }
            pLoader.NAClass = pNAClass;

            //Create field map to automatically map fields from input class to naclass
            INAClassFieldMap pFieldMap=new NAClassFieldMapClass();

            //pFieldMap.CreateMapping pNAClass.ClassDefinition, pInputFC.Fields;

            pFieldMap.CreateMapping(pNAClass.ClassDefinition,pInputFC.Fields);

            pLoader.FieldMap=pFieldMap;

            int rowsIn=0,rowsLocated=0;

            pLoader.Load(pInputFC.Search(null,true) as ICursor,null,ref rowsIn,ref rowsLocated);
        }
        //*********************************************************************************
        // Initialize the form, create a NA context, load some locations and draw the map
        //*********************************************************************************
        private void Initialize()
        {
            // Open Geodatabase and network dataset
            IFeatureWorkspace featureWorkspace = OpenWorkspace(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), @"ArcGIS\data\SanFrancisco\SanFrancisco.gdb")) as IFeatureWorkspace;
            INetworkDataset   networkDataset   = OpenNetworkDataset(featureWorkspace as IWorkspace, "Transportation", "Streets_ND");

            // Create NAContext and NASolver
            m_NAContext = CreateSolverContext(networkDataset);

            // Get Cost Attributes and populate the combo drop down box
            INetworkAttribute networkAttribute;

            for (int i = 0; i < networkDataset.AttributeCount - 1; i++)
            {
                networkAttribute = networkDataset.get_Attribute(i);
                if (networkAttribute.UsageType == esriNetworkAttributeUsageType.esriNAUTCost)
                {
                    cboCostAttribute.Items.Add(networkAttribute.Name);
                    cboCostAttribute.SelectedIndex = 0;
                }
            }

            // Set the default number of facilities to solve for
            txtFacilitiesToLocate.Text = "1";

            // Set up the no cutoff for the Minimize Impedance case.
            // See the cboProblemType_SelectedIndexChanged routine for how this is managed for other problem types
            txtCutOff.Text = "<None>";

            // Populate combo box with Location-Allocation problem types
            cboProblemType.Items.Add("Minimize Impedance");
            cboProblemType.Items.Add("Maximize Coverage");
            cboProblemType.Items.Add("Maximize Capacitated Coverage");
            cboProblemType.Items.Add("Minimize Facilities");
            cboProblemType.Items.Add("Maximize Attendance");
            cboProblemType.Items.Add("Maximize Market Share");
            cboProblemType.Items.Add("Target Market Share");
            cboProblemType.Text = "Minimize Impedance";
            m_ProblemType       = "Minimize Impedance";

            // Populate combo box with Impedance Transformation choices
            cboImpTransformation.Items.Add("Linear");
            cboImpTransformation.Items.Add("Power");
            cboImpTransformation.Items.Add("Exponential");
            cboImpTransformation.Text = "Linear";

            // Set the default impedance transformation parameter
            txtImpParameter.Text = "1.0";

            // Set up the default percentage for the Target Market Share problem type
            txtTargetMarketShare.Text = "10.0";

            // Set up the default capacity
            txtDefaultCapacity.Text = "1.0";

            // Load facility locations from feature class
            IFeatureClass inputFClass = featureWorkspace.OpenFeatureClass("CandidateStores");

            LoadNANetworkLocations("Facilities", inputFClass, 500);

            // Load demand point locations from feature class
            inputFClass = featureWorkspace.OpenFeatureClass("TractCentroids");
            LoadNANetworkLocations("DemandPoints", inputFClass, 500);

            // Create Layer for Network Dataset and add to Ax Map Control
            ILayer        layer;
            INetworkLayer networkLayer;

            networkLayer = new NetworkLayerClass();
            networkLayer.NetworkDataset = networkDataset;
            layer      = networkLayer as ILayer;
            layer.Name = "Network Dataset";
            axMapControl.AddLayer(layer, 0);

            // Create a Network Analysis Layer and add to Ax Map Control
            INALayer naLayer = m_NAContext.Solver.CreateLayer(m_NAContext);

            layer      = naLayer as ILayer;
            layer.Name = m_NAContext.Solver.DisplayName;
            axMapControl.AddLayer(layer, 0);
        }
示例#28
0
        /// <summary>
        /// Initialize the solver by calling the ArcGIS Network Analyst extension functions.
        /// </summary>
        private void Initialize()
        {
            IFeatureWorkspace featureWorkspace = null;
            INetworkDataset   networkDataset   = null;

            try
            {
                // Open Geodatabase and network dataset
                IWorkspace workspace = OpenWorkspace(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), @"ArcGIS\data\SanFrancisco\SanFrancisco.gdb"));
                networkDataset   = OpenNetworkDataset(workspace, "Transportation", "Streets_ND");
                featureWorkspace = workspace as IFeatureWorkspace;
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Unable to open dataset. Error Message: " + ex.Message);
                this.Close();
                return;
            }

            // Create NAContext and NASolver
            m_NAContext = CreateSolverContext(networkDataset);

            // Get available cost attributes from the network dataset
            INetworkAttribute networkAttribute;

            for (int i = 0; i < networkDataset.AttributeCount; i++)
            {
                networkAttribute = networkDataset.get_Attribute(i);
                if (networkAttribute.UsageType == esriNetworkAttributeUsageType.esriNAUTCost)
                {
                    string unitType = GetAttributeUnitType(networkAttribute.Units);
                    if (unitType == "Time")
                    {
                        comboTimeAttribute.Items.Add(networkAttribute.Name);
                    }
                    else if (unitType == "Distance")
                    {
                        comboDistanceAttribute.Items.Add(networkAttribute.Name);
                    }
                }
            }
            comboTimeAttribute.SelectedIndex     = 0;
            comboDistanceAttribute.SelectedIndex = 0;

            // Populate time field unit in comboBox
            m_unitTimeList = new System.Collections.Hashtable();
            m_unitTimeList.Add("Seconds", esriNetworkAttributeUnits.esriNAUSeconds);
            m_unitTimeList.Add("Minutes", esriNetworkAttributeUnits.esriNAUMinutes);
            foreach (System.Collections.DictionaryEntry timeUnit in m_unitTimeList)
            {
                comboTimeUnits.Items.Add(timeUnit.Key.ToString());
            }
            comboTimeUnits.SelectedIndex = 1;

            // Populate distance field unit in comboBox
            m_unitDistList = new System.Collections.Hashtable();
            m_unitDistList.Add("Miles", esriNetworkAttributeUnits.esriNAUMiles);
            m_unitDistList.Add("Meters", esriNetworkAttributeUnits.esriNAUMeters);
            foreach (System.Collections.DictionaryEntry distUnit in m_unitDistList)
            {
                comboDistUnits.Items.Add(distUnit.Key.ToString());
            }
            comboDistUnits.SelectedIndex = 0;

            // Populate time window importance attribute in comboBox
            comboTWImportance.Items.Add("High");
            comboTWImportance.Items.Add("Medium");
            comboTWImportance.Items.Add("Low");
            comboTWImportance.SelectedIndex = 0;

            // Load locations
            IFeatureClass inputFClass = featureWorkspace.OpenFeatureClass("Stores");

            LoadNANetworkLocations("Orders", inputFClass as ITable);
            inputFClass = featureWorkspace.OpenFeatureClass("DistributionCenter");
            LoadNANetworkLocations("Depots", inputFClass as ITable);
            inputFClass = featureWorkspace.OpenFeatureClass("Routes");
            LoadNANetworkLocations("Routes", inputFClass as ITable);
            ITable inputTable = featureWorkspace.OpenTable("Breaks");

            LoadNANetworkLocations("Breaks", inputTable);

            // Create layer for network dataset and add to ArcMap
            INetworkLayer networkLayer = new NetworkLayerClass();

            networkLayer.NetworkDataset = networkDataset;
            ILayer layer = networkLayer as ILayer;

            layer.Name = "Network Dataset";
            axMapControl.AddLayer(layer, 0);

            // Create a network analysis layer and add to ArcMap
            INALayer naLayer = m_NAContext.Solver.CreateLayer(m_NAContext);

            layer      = naLayer as ILayer;
            layer.Name = m_NAContext.Solver.DisplayName;
            axMapControl.AddLayer(layer, 0);
        }
示例#29
0
		//the rest of the class if for the best route

		/*
		 * '*********************************************************************************
			  ' Set Route Solver Settings
		   '*********************************************************************************
		 * */

		public void SetSolverSettings(ref INAContext pContext , string sImpedanceName,bool bOneWay ,bool bUseHierarchy)
		{
			
			INASolver pSolver;
            
			pSolver = pContext.Solver;
             
			INARouteSolver pRteSolver=pSolver as INARouteSolver;

			pRteSolver.OutputLines =esriNAOutputLineType.esriNAOutputLineTrueShapeWithMeasure;
			pRteSolver.CreateTraversalResult = true;
			pRteSolver.UseTimeWindows = false;
			pRteSolver.FindBestSequence = false;
			pRteSolver.PreserveFirstStop = false;
			pRteSolver.PreserveLastStop = false;


			//Set generic Solver settings
			// set the impedance attribute
			INASolverSettings pSolverSettings=pSolver as INASolverSettings;
            
			pSolverSettings.ImpedanceAttributeName = sImpedanceName;

			// Set the OneWay Restriction if necessary

			IStringArray restrictions;
			restrictions = pSolverSettings.RestrictionAttributeNames;
			restrictions.RemoveAll();
			if(bOneWay==true)
				restrictions.Add("oneway");
			pSolverSettings.RestrictionAttributeNames=restrictions;

			/*
			 *  'Restrict UTurns
			 * */
			pSolverSettings.RestrictUTurns =esriNetworkForwardStarBacktrack.esriNFSBNoBacktrack;

			//IgnoreInvalidLocations allows the network analyst solvers to ignore locations that have not snapped to a network edge
			pSolverSettings.IgnoreInvalidLocations=true;


			if(bUseHierarchy==true)
			{
				
				pSolverSettings.UseHierarchy=true;
				pSolverSettings.HierarchyAttributeName = "hierarchy";
				pSolverSettings.HierarchyLevelCount = 3;
                
				pSolverSettings.set_MaxValueForHierarchy(1,1);
				pSolverSettings.set_NumTransitionToHierarchy(1,9);

				pSolverSettings.set_MaxValueForHierarchy(2,2);
				pSolverSettings.set_NumTransitionToHierarchy(2,9);


			
			} 
			else
				pSolverSettings.UseHierarchy=false;


			// Do not forget to update the context after you set your impedance
			pSolver.UpdateContext(pContext, GetDENetworkDataset(pContext.NetworkDataset),new GPMessagesClass());

    
				   
		}
示例#30
0
        private void Form1_Load(object sender, EventArgs e)
        {
            j = 3;
            comboBox1.Items.Clear();

            string filePath = Application.StartupPath + "\\..\\..\\..\\..\\最新arcsense\\无标题11.sxd";
            if (axSceneControl1.CheckSxFile(filePath))
            {
                axSceneControl1.LoadSxFile(filePath);
                axTOCControl1.SetBuddyControl(axSceneControl1);
            }
            lyrCount = axSceneControl1.Scene.LayerCount;
            //MessageBox.Show(axSceneControl1.Scene.LayerCount.ToString());
            for (i = 0; i <= lyrCount - 1; i++)
            {
              //  MessageBox.Show(axSceneControl1.Scene.get_Layer(i).Name);
                comboBox1.Items.Add(axSceneControl1.Scene.get_Layer(i).Name);
            }
            String sFilename;
            sFilename = @"C:\Users\dull\Desktop\新文件\校园代码\最新底图制作\无标题.mxd";
            if (axMapControl1.CheckMxFile(sFilename))
            {
                axMapControl1.LoadMxFile(sFilename);
             //       axTOCControl1.SetBuddyControl(axMapControl1);
             }

            string path = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            int t;
            for (t = 0; t < path.Length; t++)
            {
                if (path.Substring(t, 24) == "WindowsFormsApplication1")
                {
                    break;
                }
            }
            string name = path.Substring(0, t - 1) + "\\WindowsFormsApplication1\\road.gdb";
            pFeatureWorkspace = OpenWorkspace(name) as IFeatureWorkspace;
            pNetworkDataset = OpenNetworkDataset_Other(pFeatureWorkspace as IWorkspace, "zhz_ND", "zhz");

            pNAContext = CreateNAContext(pNetworkDataset);
            pInputFC = pFeatureWorkspace.OpenFeatureClass("zhz_ND_Junctions");
            //pInputFC = pFeatureWorkspace.OpenFeatureClass("woqu");
            pVertexFC = pFeatureWorkspace.OpenFeatureClass("zhz_ND_Junctions");

            IFeatureLayer pVertexFL = new FeatureLayerClass();
            pVertexFL.FeatureClass = pFeatureWorkspace.OpenFeatureClass("zhz_ND_Junctions");
            pVertexFL.Name = pVertexFL.FeatureClass.AliasName;
            axMapControl2.AddLayer(pVertexFL, 0);

            IFeatureLayer pRoadFL = new FeatureLayerClass();
            pRoadFL.FeatureClass = pFeatureWorkspace.OpenFeatureClass("road1");
            pRoadFL.Name = pRoadFL.FeatureClass.AliasName;
            axMapControl2.AddLayer(pRoadFL, 0);

            ILayer pLayer;
            INetworkLayer pNetworkLayer = new NetworkLayerClass();
            pNetworkLayer.NetworkDataset = pNetworkDataset;
            pLayer = pNetworkLayer as ILayer;
            pLayer.Name = "Network Dataset";
            axMapControl2.AddLayer(pLayer, 0);

            //Create a Network Analysis Layer and add to ArcMap
            INALayer naLayer = pNAContext.Solver.CreateLayer(pNAContext);
            pLayer = naLayer as ILayer;
            pLayer.Name = pNAContext.Solver.DisplayName;
            axMapControl2.AddLayer(pLayer, 0);

            pActiveView = axMapControl2.ActiveView;
            pMap = pActiveView.FocusMap;
            pGraphicsContainer = pMap as IGraphicsContainer;

              //  string CurrentPath = Directory.GetCurrentDirectory();
             //   Directory.SetCurrentDirectory(CurrentPath + "\\..\\..\\..\\..\\最新底图制作");
             //   string FilePath = Directory.GetCurrentDirectory();
             //   axMapControl1.AddShapeFile(FilePath, "教学区.shp");
             //   axMapControl1.AddShapeFile(FilePath, "活动区.shp");
              //  axMapControl1.AddShapeFile(FilePath, "宿舍.shp");
              //  axMapControl1.AddShapeFile(FilePath, "场馆区.shp");
            //    axMapControl1.AddShapeFile(FilePath, "办公区.shp");
            //    axMapControl1.AddShapeFile(FilePath, "其他.shp");
             //   axMapControl1.AddShapeFile(FilePath, "底图.shp");
             //   axMapControl1.AddShapeFile(FilePath, "无标题.mxd");
        }
        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);
        }
示例#32
0
        /*
         * '*********************************************************************************
            ' Set Solver Settings
            '*********************************************************************************
         * */
        public void SetSolverSettings(ref INAContext _m_pNAContext,int CutOffVal,int facCount,string costField,bool isOneWay,bool isHierarchy)
        {
            //Set Route specific Settings
            INASolver pSolver;
            INAClosestFacilitySolver pCFSolver;
            INASolverSettings pSolverSettings;

            //�õ����resover

            pSolver = _m_pNAContext.Solver;

            pCFSolver=pSolver as INAClosestFacilitySolver;

            //һ��Ҫ����Ϊ�գ�������ó�0��鲻����
            if(CutOffVal==0)
                pCFSolver.DefaultCutoff=null;
            else
                pCFSolver.DefaultCutoff=CutOffVal;

            pCFSolver.DefaultTargetFacilityCount=facCount;

            pCFSolver.OutputLines = esriNAOutputLineType.esriNAOutputLineTrueShapeWithMeasure;

            pCFSolver.TravelDirection=esriNATravelDirection.esriNATravelDirectionToFacility;

            pSolverSettings=pSolver as INASolverSettings;

            //set the impedance attribute

            pSolverSettings.ImpedanceAttributeName=costField;

            //Set the OneWay Restriction if necessary

            IStringArray restrictions;
            restrictions = pSolverSettings.RestrictionAttributeNames;
            restrictions.RemoveAll();
            if(isOneWay==true)
                restrictions.Add("oneway");
            pSolverSettings.RestrictionAttributeNames=restrictions;

            /*
             *  'Restrict UTurns
             * */
            pSolverSettings.RestrictUTurns =esriNetworkForwardStarBacktrack.esriNFSBNoBacktrack;

            //IgnoreInvalidLocations allows the network analyst solvers to ignore locations that have not snapped to a network edge
            pSolverSettings.IgnoreInvalidLocations=true;

            // Set the Hierachy attribute

            if(isHierarchy==true)
            {

                pSolverSettings.UseHierarchy=true;
                pSolverSettings.HierarchyAttributeName = "hierarchy";
                pSolverSettings.HierarchyLevelCount = 3;

                pSolverSettings.set_MaxValueForHierarchy(1,1);
                pSolverSettings.set_NumTransitionToHierarchy(1,9);

                pSolverSettings.set_MaxValueForHierarchy(2,2);
                pSolverSettings.set_NumTransitionToHierarchy(2,9);

            }
            else
                pSolverSettings.UseHierarchy=false;

            // Do not forget to update the context after you set your impedance
            pSolver.UpdateContext(_m_pNAContext, GetDENetworkDataset(_m_pNAContext.NetworkDataset),new GPMessagesClass());
        }
        /// <summary>
        /// Create NASolver and NAContext
        /// </summary>
        /// <param name="networkDataset">Input network dataset</param>
        private void CreateSolverContext(INetworkDataset networkDataset)
		{
			if (networkDataset == null) return;

            //Get the Data Element
            IDENetworkDataset deNDS = GetDENetworkDataset(networkDataset);

            INASolver naSolver = new NAServiceAreaSolverClass();
            m_NAContext = naSolver.CreateContext(deNDS, naSolver.Name);
            ((INAContextEdit)m_NAContext).Bind(networkDataset, new GPMessagesClass());
        }
示例#34
0
        //the rest of the class if for the best route
        /*
         * '*********************************************************************************
              ' Set Route Solver Settings
           '*********************************************************************************
         * */
        public void SetSolverSettings(ref INAContext pContext , string sImpedanceName,bool bOneWay ,bool bUseHierarchy)
        {
            INASolver pSolver;

            pSolver = pContext.Solver;

            INARouteSolver pRteSolver=pSolver as INARouteSolver;

            pRteSolver.OutputLines =esriNAOutputLineType.esriNAOutputLineTrueShapeWithMeasure;
            pRteSolver.CreateTraversalResult = true;
            pRteSolver.UseTimeWindows = false;
            pRteSolver.FindBestSequence = false;
            pRteSolver.PreserveFirstStop = false;
            pRteSolver.PreserveLastStop = false;

            //Set generic Solver settings
            // set the impedance attribute
            INASolverSettings pSolverSettings=pSolver as INASolverSettings;

            pSolverSettings.ImpedanceAttributeName = sImpedanceName;

            // Set the OneWay Restriction if necessary

            IStringArray restrictions;
            restrictions = pSolverSettings.RestrictionAttributeNames;
            restrictions.RemoveAll();
            if(bOneWay==true)
                restrictions.Add("oneway");
            pSolverSettings.RestrictionAttributeNames=restrictions;

            /*
             *  'Restrict UTurns
             * */
            pSolverSettings.RestrictUTurns =esriNetworkForwardStarBacktrack.esriNFSBNoBacktrack;

            //IgnoreInvalidLocations allows the network analyst solvers to ignore locations that have not snapped to a network edge
            pSolverSettings.IgnoreInvalidLocations=true;

            if(bUseHierarchy==true)
            {

                pSolverSettings.UseHierarchy=true;
                pSolverSettings.HierarchyAttributeName = "hierarchy";
                pSolverSettings.HierarchyLevelCount = 3;

                pSolverSettings.set_MaxValueForHierarchy(1,1);
                pSolverSettings.set_NumTransitionToHierarchy(1,9);

                pSolverSettings.set_MaxValueForHierarchy(2,2);
                pSolverSettings.set_NumTransitionToHierarchy(2,9);

            }
            else
                pSolverSettings.UseHierarchy=false;

            // Do not forget to update the context after you set your impedance
            pSolver.UpdateContext(pContext, GetDENetworkDataset(pContext.NetworkDataset),new GPMessagesClass());
        }
		/// <summary>
		/// Initialize the solver by calling the ArcGIS Network Analyst extension functions.
		/// </summary>
		private void Initialize()
		{
			IFeatureWorkspace featureWorkspace = null;
			INetworkDataset networkDataset = null;

			try
			{
				// Open Geodatabase and network dataset
				IWorkspace workspace = OpenWorkspace(Application.StartupPath + @"\..\..\..\..\..\Data\SanFrancisco\SanFrancisco.gdb");
				networkDataset = OpenNetworkDataset(workspace, "Transportation", "Streets_ND");
				featureWorkspace = workspace as IFeatureWorkspace;
			}
			catch (Exception ex)
			{
				System.Windows.Forms.MessageBox.Show("Unable to open dataset. Error Message: " + ex.Message);
				this.Close();
				return;
			}

			// Create NAContext and NASolver
			m_NAContext = CreateSolverContext(networkDataset);

			// Get available cost attributes from the network dataset
			INetworkAttribute networkAttribute;
			for (int i = 0; i < networkDataset.AttributeCount; i++)
			{
				networkAttribute = networkDataset.get_Attribute(i);
				if (networkAttribute.UsageType == esriNetworkAttributeUsageType.esriNAUTCost)
				{
					string unitType = GetAttributeUnitType(networkAttribute.Units);
					if (unitType == "Time")
					{
						comboTimeAttribute.Items.Add(networkAttribute.Name);
					}
					else if (unitType == "Distance")
					{
						comboDistanceAttribute.Items.Add(networkAttribute.Name);
					}
				}
			}
			comboTimeAttribute.SelectedIndex = 0;
			comboDistanceAttribute.SelectedIndex = 0;

			// Populate time field unit in comboBox
			m_unitTimeList = new System.Collections.Hashtable();
			m_unitTimeList.Add("Seconds", esriNetworkAttributeUnits.esriNAUSeconds);
			m_unitTimeList.Add("Minutes", esriNetworkAttributeUnits.esriNAUMinutes);
			foreach (System.Collections.DictionaryEntry timeUnit in m_unitTimeList)
			{
				comboTimeUnits.Items.Add(timeUnit.Key.ToString());
			}
			comboTimeUnits.SelectedIndex = 1;

			// Populate distance field unit in comboBox
			m_unitDistList = new System.Collections.Hashtable();
			m_unitDistList.Add("Miles", esriNetworkAttributeUnits.esriNAUMiles);
			m_unitDistList.Add("Meters", esriNetworkAttributeUnits.esriNAUMeters);
			foreach (System.Collections.DictionaryEntry distUnit in m_unitDistList)
			{
				comboDistUnits.Items.Add(distUnit.Key.ToString());
			}
			comboDistUnits.SelectedIndex = 0;

			// Populate time window importance attribute in comboBox
			comboTWImportance.Items.Add("High");
			comboTWImportance.Items.Add("Medium");
			comboTWImportance.Items.Add("Low");
			comboTWImportance.SelectedIndex = 0;

			// Load locations 
			IFeatureClass inputFClass = featureWorkspace.OpenFeatureClass("Stores");
			LoadNANetworkLocations("Orders", inputFClass as ITable);
			inputFClass = featureWorkspace.OpenFeatureClass("DistributionCenter");
			LoadNANetworkLocations("Depots", inputFClass as ITable);
			inputFClass = featureWorkspace.OpenFeatureClass("Routes");
			LoadNANetworkLocations("Routes", inputFClass as ITable);
			ITable inputTable = featureWorkspace.OpenTable("Breaks");
			LoadNANetworkLocations("Breaks", inputTable);

			// Create layer for network dataset and add to ArcMap
			INetworkLayer networkLayer = new NetworkLayerClass();
			networkLayer.NetworkDataset = networkDataset;
			ILayer layer = networkLayer as ILayer;
			layer.Name = "Network Dataset";
			axMapControl.AddLayer(layer, 0);

			// Create a network analysis layer and add to ArcMap
			INALayer naLayer = m_NAContext.Solver.CreateLayer(m_NAContext);
			layer = naLayer as ILayer;
			layer.Name = m_NAContext.Solver.DisplayName;
			axMapControl.AddLayer(layer, 0);
		}
示例#36
0
        //�������
        //�������·��
        private void menuItem21_Click(object sender, EventArgs e)
        {
            treeViewListItem.Nodes.Clear();
            comboBoxNetList.Items.Clear();
            m_NAContext = Utility.CreateSolverContext(m_pNetDataset, "·��");
            m_sNAName = "·��";
            TreeNode node1;
            node1 = treeViewListItem.Nodes.Add("�¹�");
            node1 = treeViewListItem.Nodes.Add("Routes","·��");
            node1 = treeViewListItem.Nodes.Add("�ϰ�");
            string strClosetR = "���·��" + iClosetRCount.ToString();
            comboBoxNetList.Items.Add(strClosetR);
            comboBoxNetList.Text = strClosetR;
            iClosetRCount += 1;
            strNetAnalystContext = "���·��";
            //

            //Create Layer for Network Dataset and add to ArcMap
            //ILayer layer;
            //INetworkLayer networkLayer;
            //networkLayer = new NetworkLayerClass();
            //networkLayer.NetworkDataset = m_pNetDataset;
            //layer = networkLayer as ILayer;
            //layer.Name = "Network Dataset";
            AxMapControl axMap = getMapControl();
            //axMap.AddLayer(layer, 0);

            //Create a Network Analysis Layer and add to ArcMap
            INALayer naLayer = m_NAContext.Solver.CreateLayer(m_NAContext);
            ILayer layer = naLayer as ILayer;
            layer.Name = m_NAContext.Solver.DisplayName;
            axMap.AddLayer(layer, 0);
        }
        /// <summary>
        /// _pFtClass参数为Stops的要素类,_pPointC是用鼠标点的点生成的点的集合,最后一个参数是捕捉距离
        /// </summary>
        /// <param name="_pNaContext"></param>
        /// <param name="_pFtClass"></param>
        /// <param name="_pPointC"></param>
        /// <param name="_pDist"></param>
        void NASolve(INAContext _pNaContext,IFeatureClass _pFtClass, IPointCollection _pPointC, double _pDist)
        {
            INALocator pNAlocator = _pNaContext.Locator;
            for (int i = 0; i < _pPointC.PointCount; i++)
            {
                IFeature pFt = _pFtClass.CreateFeature();

                IRowSubtypes pRowSubtypes = pFt as IRowSubtypes;

                pRowSubtypes.InitDefaultValues();

                pFt.Shape = _pPointC.get_Point(i) as IGeometry;

                IPoint pPoint = null;

                 INALocation pNalocation = null;

                pNAlocator.QueryLocationByPoint(_pPointC .get_Point(i),ref pNalocation,ref pPoint,ref _pDist);

                INALocationObject pNAobject = pFt as INALocationObject;

                pNAobject.NALocation = pNalocation;

                int pNameFieldIndex = _pFtClass.FindField("Name");

                pFt.set_Value(pNameFieldIndex, pPoint.X.ToString() + "," + pPoint.Y.ToString());

                int pStatusFieldIndex = _pFtClass.FindField("Status");

                pFt.set_Value(pStatusFieldIndex, esriNAObjectStatus.esriNAObjectStatusOK);

                int pSequenceFieldIndex = _pFtClass.FindField("Sequence");

                pFt.set_Value(_pFtClass.FindField("Sequence"), ((ITable)_pFtClass).RowCount(null));

                pFt.Store();

            }
        }
示例#38
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();
        }
示例#39
0
        public bool ShowModal(IMapControl3 mapControl, IEngineNetworkAnalystEnvironment naEnv)
        {
            // Initialize variables
            m_okClicked        = false;
            m_listDisplayTable = new System.Collections.ArrayList();

            var activeCategory = naEnv.NAWindow.ActiveCategory as IEngineNAWindowCategory2;

            if (activeCategory == null)
            {
                return(false);
            }

            IDataLayer dataLayer = activeCategory.DataLayer;

            if (dataLayer == null)
            {
                return(false);
            }

            // Set up the title of this dialog
            String dataLayerName = GetDataLayerName(dataLayer);

            if (dataLayerName.Length == 0)
            {
                return(false);
            }

            this.Text = "Load Items into " + dataLayerName;

            // Make sure the combo box lists only the appropriate possible input data layers
            PopulateInputDataComboBox(mapControl, dataLayer);

            //Select the first display table from the list
            if (cboInputData.Items.Count > 0)
            {
                cboInputData.SelectedIndex = 0;
            }

            // Show the window
            this.ShowDialog();

            // If we selected a layer and clicked OK, load the locations
            if (m_okClicked && (cboInputData.SelectedIndex >= 0))
            {
                try
                {
                    // Get a cursor on the source display table (either though the selection set or table)
                    // Use IDisplayTable because it accounts for joins, querydefs, etc.
                    // IDisplayTable is implemented by FeatureLayers and StandaloneTables.
                    //
                    IDisplayTable displayTable = m_listDisplayTable[cboInputData.SelectedIndex] as IDisplayTable;
                    ICursor       cursor;
                    if (chkUseSelection.Checked)
                    {
                        ISelectionSet selSet;
                        selSet = displayTable.DisplaySelectionSet;
                        selSet.Search(null, false, out cursor);
                    }
                    else
                    {
                        cursor = displayTable.SearchDisplayTable(null, false);
                    }

                    // Get the NAContext from the active analysis layer
                    INAContext naContext = naEnv.NAWindow.ActiveAnalysis.Context;

                    // Get the dataset for the active NAClass
                    IDataset naDataset = activeCategory.NAClass as IDataset;

                    // Setup NAClassLoader and Load Locations
                    INAClassLoader2 naClassLoader = new NAClassLoader() as INAClassLoader2;
                    naClassLoader.Initialize(naContext, naDataset.Name, cursor);

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

                    int rowsIn      = 0;
                    int rowsLocated = 0;
                    naClassLoader.Load(cursor, null, ref rowsIn, ref rowsLocated);

                    // Let the user know if some of the rows failed to locate
                    if (rowsIn != rowsLocated)
                    {
                        MessageBox.Show("Out of " + rowsIn + " + rows, " + rowsLocated + " rows were located",
                                        "Loading locations", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message, "Loading locations failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                return(true);
            }

            return(false);
        }
示例#40
0
		/*
		 * '*********************************************************************************
			' Set Solver Settings
			'*********************************************************************************
		 * */

		public void SetSolverSettings(ref INAContext _m_pNAContext,int CutOffVal,int facCount,string costField,bool isOneWay,bool isHierarchy)
		{
			//Set Route specific Settings
			INASolver pSolver;
			INAClosestFacilitySolver pCFSolver;
			INASolverSettings pSolverSettings;
            
			//得到这个resover
  
			pSolver = _m_pNAContext.Solver;

			pCFSolver=pSolver as INAClosestFacilitySolver;
			  
			//一定要设置为空,如果设置成0会查不出来
			if(CutOffVal==0)
				pCFSolver.DefaultCutoff=null;
			else
				pCFSolver.DefaultCutoff=CutOffVal;
			  

			pCFSolver.DefaultTargetFacilityCount=facCount;

			pCFSolver.OutputLines = esriNAOutputLineType.esriNAOutputLineTrueShapeWithMeasure;

			pCFSolver.TravelDirection=esriNATravelDirection.esriNATravelDirectionToFacility;

			pSolverSettings=pSolver as INASolverSettings;

			//set the impedance attribute

			pSolverSettings.ImpedanceAttributeName=costField;

			//Set the OneWay Restriction if necessary

			IStringArray restrictions;
			restrictions = pSolverSettings.RestrictionAttributeNames;
			restrictions.RemoveAll();
			if(isOneWay==true)
				restrictions.Add("oneway");
			pSolverSettings.RestrictionAttributeNames=restrictions;

			/*
			 *  'Restrict UTurns
			 * */
			pSolverSettings.RestrictUTurns =esriNetworkForwardStarBacktrack.esriNFSBNoBacktrack;

			//IgnoreInvalidLocations allows the network analyst solvers to ignore locations that have not snapped to a network edge
			pSolverSettings.IgnoreInvalidLocations=true;

			// Set the Hierachy attribute

			if(isHierarchy==true)
			{
				
				pSolverSettings.UseHierarchy=true;
				pSolverSettings.HierarchyAttributeName = "hierarchy";
				pSolverSettings.HierarchyLevelCount = 3;
                
				pSolverSettings.set_MaxValueForHierarchy(1,1);
				pSolverSettings.set_NumTransitionToHierarchy(1,9);

				pSolverSettings.set_MaxValueForHierarchy(2,2);
				pSolverSettings.set_NumTransitionToHierarchy(2,9);


			
			} 
			else
				pSolverSettings.UseHierarchy=false;


			// Do not forget to update the context after you set your impedance
			pSolver.UpdateContext(_m_pNAContext, GetDENetworkDataset(_m_pNAContext.NetworkDataset),new GPMessagesClass());

		
		
		}
示例#41
0
        //加载参与分析的点要素
        public static void LoadNANetworkLocations(string strNAClassName, IFeatureClass inputFC, INAContext m_NAContext, double snapTolerance)
        {
            ITable    b1 = inputFC as ITable;
            int       i1 = b1.RowCount(null);
            INAClass  naClass;
            INamedSet classes;

            classes = m_NAContext.NAClasses;
            naClass = classes.get_ItemByName(strNAClassName) as INAClass;
            ITable b2 = naClass as ITable;
            int    i2 = b2.RowCount(null);

            naClass.DeleteAllRows();
            ITable         b3          = naClass as ITable;
            int            i3          = b2.RowCount(null);
            INAClassLoader classLoader = new NAClassLoader();

            classLoader.Locator = m_NAContext.Locator;
            if (snapTolerance > 0)
            {
                classLoader.Locator.SnapTolerance = snapTolerance;                   //设置容差
            }
            classLoader.NAClass = naClass;
            //设置字段映射
            INAClassFieldMap fieldMap = null;

            fieldMap = new NAClassFieldMap();
            fieldMap.set_MappedField("FID", "FID");
            classLoader.FieldMap = fieldMap;
            int            rowsIn        = 0;
            int            rowLocated    = 0;
            IFeatureCursor featureCursor = inputFC.Search(null, true);

            classLoader.Load((ICursor)featureCursor, null, ref rowsIn, ref rowLocated);
            INAClass na = classLoader.NAClass;
            ITable   b5 = na as ITable;
            int      i5 = b2.RowCount(null);
            ITable   b4 = inputFC as ITable;
            int      i4 = b1.RowCount(null);

            ((INAContextEdit)m_NAContext).ContextChanged();
        }
示例#42
0
		/// <summary>
		/// 将网络数据添加到地图中
		/// </summary>
		/// <param name="dataPath">网络数据路径</param>
		/// <param name="_mapControl">地图控件</param>
		/// <param name="_pNAContext">INAContext</param>
		/// <param name="cmbCost">获取网络数据集里面的代价字段</param>
		/// <param name="isRoute">是否使用route</param>
		public void loadNetworkData(string dataPath,AxMapControl _mapControl,ref INAContext _pNAContext,ComboBox cmbCost,bool isRoute)
		{

				     
			IFeatureWorkspace pFWorkspace;
            
			INetworkDataset pNetworkDataset;
			
			INetworkAttribute pNetworkAttribute;

			int i;

			IFeatureClass pInputFClass;
			
			//打开workspace
			pFWorkspace=OpenWorkspace(dataPath) as IFeatureWorkspace;

			//打开network Dataset

			pNetworkDataset=OpenNetworkDataset(pFWorkspace as IWorkspace,"Streets_nd");

			if(isRoute==false)
			_pNAContext=CreateSolverContext(pNetworkDataset);
			else
				_pNAContext=CreateRouteSolverContext(pNetworkDataset);

			// Get Cost Attributes
			for(i=0;i<pNetworkDataset.AttributeCount;i++)
			{

				//get the attribute of the network dataset
                			    
				pNetworkAttribute=pNetworkDataset.get_Attribute(i);
				//if it is a cost attribute,add it to combo box

				if(pNetworkAttribute.UsageType==esriNetworkAttributeUsageType.esriNAUTCost)
				{
					cmbCost.Items.Add(pNetworkAttribute.Name);

				
				}

			


			}
			cmbCost.SelectedIndex=0;

			

			if(isRoute==false)
			{
				pInputFClass = pFWorkspace.OpenFeatureClass("BayAreaIncident");
				LoadNANetworkLocations("Incidents",pInputFClass, 100,ref _pNAContext);
			}
			else
			{
			
			}


			
			pInputFClass = pFWorkspace.OpenFeatureClass("BayAreaLocations");
			if(isRoute==false)
			{
				LoadNANetworkLocations("Facilities", pInputFClass, 100,ref _pNAContext);
			}
			else
			{
				LoadNANetworkLocations("Stops", pInputFClass, 100,ref _pNAContext);
			
			}
			

			
			//'Create Layer for Network Dataset and add to ArcMap
			
			ILayer pLayer;
			INetworkLayer pNetworkLayer=new NetworkLayerClass();

			pNetworkLayer.NetworkDataset = pNetworkDataset;

			pLayer = pNetworkLayer as ILayer;

			pLayer.Name = "Network Dataset";

			_mapControl.AddLayer(pLayer,0);

			//Create a Network Analysis Layer and add to ArcMap

			
			INALayer pNALayer=_pNAContext.Solver.CreateLayer(_pNAContext);
			pLayer = pNALayer as ILayer;
			pLayer.Name = _pNAContext.Solver.DisplayName;
			_mapControl.AddLayer(pLayer,0);
			

		}
示例#43
0
        //�������
        //�����µ���ȡ�����ʩ������
        private void menuItem24_Click(object sender, EventArgs e)
        {
            treeViewListItem.Nodes.Clear();
            comboBoxNetList.Items.Clear();
            m_NAContext = Utility.CreateSolverContext(m_pNetDataset, "��ʩ");
            m_sNAName = "��ʩ";
            TreeNode node1;
            node1 = treeViewListItem.Nodes.Add("��ʩ");
            node1 = treeViewListItem.Nodes.Add("�¹�");
            node1 = treeViewListItem.Nodes.Add("·��");
            node1 = treeViewListItem.Nodes.Add("�ϰ�");
            string strClosetF = "���ٽ�������ʩ" + iClosetFCount.ToString();
            comboBoxNetList.Items.Add(strClosetF);
            comboBoxNetList.Text = strClosetF;
            iClosetFCount += 1;
            strNetAnalystContext = "�ٽ���ʩ";

            AxMapControl axMap = getMapControl();
            //axMap.AddLayer(layer, 0);

            //Create a Network Analysis Layer and add to ArcMap
            INALayer naLayer = m_NAContext.Solver.CreateLayer(m_NAContext);
            ILayer layer = naLayer as ILayer;
            layer.Name = m_NAContext.Solver.DisplayName;
            axMap.AddLayer(layer, 0);
        }
示例#44
0
        /// <summary>
        /// ������������ӵ���ͼ��
        /// </summary>
        /// <param name="dataPath">��������·��</param>
        /// <param name="_mapControl">��ͼ�ؼ�</param>
        /// <param name="_pNAContext">INAContext</param>
        /// <param name="cmbCost">��ȡ�������ݼ�����Ĵ����ֶ�</param>
        /// <param name="isRoute">�Ƿ�ʹ��route</param>
        public void loadNetworkData(string dataPath,AxMapControl _mapControl,ref INAContext _pNAContext,ComboBox cmbCost,bool isRoute)
        {
            IFeatureWorkspace pFWorkspace;

            INetworkDataset pNetworkDataset;

            INetworkAttribute pNetworkAttribute;

            int i;

            IFeatureClass pInputFClass;

            //��workspace
            pFWorkspace=OpenWorkspace(dataPath) as IFeatureWorkspace;

            //��network Dataset

            pNetworkDataset=OpenNetworkDataset(pFWorkspace as IWorkspace,"Streets_nd");

            if(isRoute==false)
            _pNAContext=CreateSolverContext(pNetworkDataset);
            else
                _pNAContext=CreateRouteSolverContext(pNetworkDataset);

            // Get Cost Attributes
            for(i=0;i<pNetworkDataset.AttributeCount;i++)
            {

                //get the attribute of the network dataset

                pNetworkAttribute=pNetworkDataset.get_Attribute(i);
                //if it is a cost attribute,add it to combo box

                if(pNetworkAttribute.UsageType==esriNetworkAttributeUsageType.esriNAUTCost)
                {
                    cmbCost.Items.Add(pNetworkAttribute.Name);

                }

            }
            cmbCost.SelectedIndex=0;

            if(isRoute==false)
            {
                pInputFClass = pFWorkspace.OpenFeatureClass("BayAreaIncident");
                LoadNANetworkLocations("Incidents",pInputFClass, 100,ref _pNAContext);
            }
            else
            {

            }

            pInputFClass = pFWorkspace.OpenFeatureClass("BayAreaLocations");
            if(isRoute==false)
            {
                LoadNANetworkLocations("Facilities", pInputFClass, 100,ref _pNAContext);
            }
            else
            {
                LoadNANetworkLocations("Stops", pInputFClass, 100,ref _pNAContext);

            }

            //'Create Layer for Network Dataset and add to ArcMap

            ILayer pLayer;
            INetworkLayer pNetworkLayer=new NetworkLayerClass();

            pNetworkLayer.NetworkDataset = pNetworkDataset;

            pLayer = pNetworkLayer as ILayer;

            pLayer.Name = "Network Dataset";

            _mapControl.AddLayer(pLayer,0);

            //Create a Network Analysis Layer and add to ArcMap

            INALayer pNALayer=_pNAContext.Solver.CreateLayer(_pNAContext);
            pLayer = pNALayer as ILayer;
            pLayer.Name = _pNAContext.Solver.DisplayName;
            _mapControl.AddLayer(pLayer,0);
        }
		//*********************************************************************************
		// Initialize the form, create a NA context, load some locations and draw the map
		//*********************************************************************************
		private void Initialize()
		{
			// Open Geodatabase and network dataset
			IFeatureWorkspace featureWorkspace = OpenWorkspace(Application.StartupPath + @"\..\..\..\..\..\Data\SanFrancisco\SanFrancisco.gdb") as IFeatureWorkspace;
			INetworkDataset networkDataset = OpenNetworkDataset(featureWorkspace as IWorkspace, "Transportation", "Streets_ND");

			// Create NAContext and NASolver
			m_NAContext = CreateSolverContext(networkDataset);

			// Get Cost Attributes and populate the combo drop down box
			INetworkAttribute networkAttribute;
			for (int i = 0; i < networkDataset.AttributeCount - 1; i++)
			{
				networkAttribute = networkDataset.get_Attribute(i);
				if (networkAttribute.UsageType == esriNetworkAttributeUsageType.esriNAUTCost)
				{
					cboCostAttribute.Items.Add(networkAttribute.Name);
					cboCostAttribute.SelectedIndex = 0;
				}
			}

			// Set the default number of facilities to solve for
			txtFacilitiesToLocate.Text = "1";

			// Set up the no cutoff for the Minimize Impedance case.
			// See the cboProblemType_SelectedIndexChanged routine for how this is managed for other problem types
			txtCutOff.Text = "<None>";

			// Populate combo box with Location-Allocation problem types
			cboProblemType.Items.Add("Minimize Impedance");
			cboProblemType.Items.Add("Maximize Coverage");
            cboProblemType.Items.Add("Maximize Capacitated Coverage");
            cboProblemType.Items.Add("Minimize Facilities");
			cboProblemType.Items.Add("Maximize Attendance");
			cboProblemType.Items.Add("Maximize Market Share");
			cboProblemType.Items.Add("Target Market Share");
			cboProblemType.Text = "Minimize Impedance";
			m_ProblemType = "Minimize Impedance";

			// Populate combo box with Impedance Transformation choices
			cboImpTransformation.Items.Add("Linear");
			cboImpTransformation.Items.Add("Power");
			cboImpTransformation.Items.Add("Exponential");
			cboImpTransformation.Text = "Linear";

			// Set the default impedance transformation parameter
			txtImpParameter.Text = "1.0";

			// Set up the default percentage for the Target Market Share problem type
			txtTargetMarketShare.Text = "10.0";

            // Set up the default capacity
            txtDefaultCapacity.Text = "1.0";

			// Load facility locations from feature class
			IFeatureClass inputFClass = featureWorkspace.OpenFeatureClass("CandidateStores");
			LoadNANetworkLocations("Facilities", inputFClass, 500);

			// Load demand point locations from feature class
			inputFClass = featureWorkspace.OpenFeatureClass("TractCentroids");
			LoadNANetworkLocations("DemandPoints", inputFClass, 500);

			// Create Layer for Network Dataset and add to Ax Map Control
			ILayer layer;
			INetworkLayer networkLayer;
			networkLayer = new NetworkLayerClass();
			networkLayer.NetworkDataset = networkDataset;
			layer = networkLayer as ILayer;
			layer.Name = "Network Dataset";
			axMapControl.AddLayer(layer, 0);

			// Create a Network Analysis Layer and add to Ax Map Control
			INALayer naLayer = m_NAContext.Solver.CreateLayer(m_NAContext);
			layer = naLayer as ILayer;
			layer.Name = m_NAContext.Solver.DisplayName;
			axMapControl.AddLayer(layer, 0);
		}
 /// <summary>
 /// 获取NALayer
 /// </summary>
 /// <param name="_pNaSover"></param>
 /// <param name="_pNaContext"></param>
 /// <returns></returns>
 INALayer GetNaLayer(INASolver _pNaSover,INAContext _pNaContext)
 {
     return _pNaSover.CreateLayer(_pNaContext);
 }