private static void MapUsingSimpleMarkerRenderer() { string layerName = CboLayers.GetSelectedLayer(); ILayer layer = GetLayerByName(layerName); string colorName = CboColors.GetSelectedColor(); ICmykColor markerColor = ColorbrewerExtension.GetSingleCMYKColor(); ISimpleMarkerSymbol marker = new SimpleMarkerSymbol(); marker.Style = esriSimpleMarkerStyle.esriSMSCircle; marker.Color = markerColor; marker.Size = 5; ISimpleRenderer renderer = new SimpleRenderer(); renderer.Symbol = marker as ISymbol; renderer.Label = layer.Name; IGeoFeatureLayer gFLayer = layer as IGeoFeatureLayer; gFLayer.Renderer = renderer as IFeatureRenderer; IMxDocument mxDoc = ArcMap.Application.Document as IMxDocument; IMap map = mxDoc.FocusMap; mxDoc.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, gFLayer, mxDoc.ActiveView.Extent); mxDoc.UpdateContents(); }
protected override void OnClick() { functionModel funcMd = new functionModel(); IMxDocument mxDoc = ArcMap.Document; IMap map = mxDoc.FocusMap; funcMd.addFunctionRasterToMap(map); mxDoc.UpdateContents(); }
private void cmdHide_Click(object sender, EventArgs e) { ILayer pSelectedLayer = getLayerByName(cmbLayers.SelectedItem.ToString()); pSelectedLayer.Visible = false; IDocument document = _application.Document; IMxDocument pMxDoc = (IMxDocument)document; pMxDoc.UpdateContents(); pMxDoc.ActiveView.Refresh(); }
private void button2_Click(object sender, EventArgs e) { IGxDialog gxd = new GxDialog(); gxd.AllowMultiSelect = false; gxd.ButtonCaption = "Add"; gxd.Title = "Add a shapefile"; gxd.RememberLocation = true; IGxObjectFilter filter1 = new GxFilterFileGeodatabases(); IGxObjectFilter filter2 = new GxFilterShapefiles(); IGxObjectFilterCollection filters = gxd as IGxObjectFilterCollection; filters.AddFilter(filter1, true); filters.AddFilter(filter2, false); IEnumGxObject enumObj; if (gxd.DoModalOpen(ArcMap.Application.hWnd, out enumObj) == false) // show dialog { return; // return if clicking on cancel } IGxObject gxObj = enumObj.Next(); int len1 = gxObj.FullName.Length; int len2 = gxObj.Name.Length; string shpPath = gxObj.FullName.Substring(0, len1 - len2); string shpPath2 = gxObj.FullName.Substring(0); IMxDocument mxdoc = ArcMap.Application.Document as IMxDocument; IWorkspaceFactory wsf = new ShapefileWorkspaceFactory(); IWorkspace ws = wsf.OpenFromFile(shpPath, 0); IFeatureWorkspace fws = ws as IFeatureWorkspace; IFeatureClass featureClass = fws.OpenFeatureClass(gxObj.BaseName); IFeatureLayer featureLayer = new FeatureLayer(); featureLayer.FeatureClass = featureClass; ILayer layer = (ILayer)featureLayer; layer.Name = gxObj.BaseName; mxdoc.AddLayer(layer); mxdoc.ActiveView.Refresh(); mxdoc.UpdateContents(); textBox2.Text = shpPath2; tracts = shpPath2; }
private static void MapUsingProportionalSymbolRenderer() { ISimpleMarkerSymbol marker = new SimpleMarkerSymbol(); marker.Style = esriSimpleMarkerStyle.esriSMSCircle; ICmykColor markerColor = ColorbrewerExtension.GetSingleCMYKColor(); marker.Size = 10; marker.Color = markerColor; IMxDocument mxDoc = ArcMap.Application.Document as IMxDocument; IMap map = mxDoc.FocusMap; string layerName = CboLayers.GetSelectedLayer(); ILayer layer = GetLayerByName(layerName); IFeatureLayer fLayer = layer as IFeatureLayer; IFeatureClass fClass = fLayer.FeatureClass as IFeatureClass; IFeatureCursor cursor = fClass.Search(null, true); IDataStatistics dataStats = new DataStatisticsClass(); dataStats.Cursor = cursor as ICursor; string fieldName = CboFields.GetSelectedField(); dataStats.Field = fieldName; IStatisticsResults statResult = dataStats.Statistics; IProportionalSymbolRenderer propSymRenderer = new ProportionalSymbolRendererClass(); propSymRenderer.Field = fieldName; propSymRenderer.MinDataValue = statResult.Minimum == 0.0 ? 1 : statResult.Minimum; propSymRenderer.MaxDataValue = statResult.Maximum; propSymRenderer.FlanneryCompensation = true; propSymRenderer.ValueUnit = esriUnits.esriUnknownUnits; propSymRenderer.MinSymbol = marker as ISymbol; propSymRenderer.LegendSymbolCount = 3; propSymRenderer.CreateLegendSymbols(); IGeoFeatureLayer gFLayer = layer as IGeoFeatureLayer; gFLayer.Renderer = propSymRenderer as IFeatureRenderer; mxDoc.ActiveView.Refresh(); mxDoc.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, gFLayer , mxDoc.ActiveView.Extent); mxDoc.UpdateContents(); }
private void cmdShow_Click(object sender, EventArgs e) { //we need to know which layer we should show //how do we know which layer? the layer has a selecteditem (which is a string = the layer name) // we do not now have ILayer as an object > we have a string //how can we get the layer from the string?? >> we write a function! ILayer pSelectedLayer = getLayerByName(cmbLayers.SelectedItem.ToString()); pSelectedLayer.Visible = true; IDocument document = _application.Document; IMxDocument pMxDoc = (IMxDocument)document; pMxDoc.UpdateContents(); //FocusMap and ActiveView are the same //refreshes symbology and map pMxDoc.ActiveView.Refresh(); }
private void btnOK_Click(object sender, EventArgs e) { this.Cursor = Cursors.WaitCursor; IMxDocument pMxDoc = (IMxDocument)ArcMap.Document; IMaps pMaps = (IMaps)pMxDoc.Maps; try { if (this.chkEconomDev.Checked == true) { loadEconomDevLayers(); } if (this.chkFire.Checked == true) { loadFireLayers(); } if (this.chkPlan.Checked == true) { loadPlanningLayers(); } if (this.chkPolice.Checked == true) { loadPoliceLayers(); } if (this.chkPubWorks.Checked == true) { loadPubWorksLayers(); } pMxDoc.UpdateContents(); } catch (Exception ex) { MessageBox.Show("An error occurred while loading the data frame you selected.\r\n\r\n" + ex.Message, "Error occurred", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { this.Cursor = Cursors.Default; this.Dispose(); } }
internal static void addNewShapefile(IApplication m_application, string shpFileName) { IMxDocument pDoc = m_application.Document as IMxDocument; IMap pMap = pDoc.FocusMap; IWorkspaceFactory pFactory = new ShapefileWorkspaceFactory(); // Based on the .NET Application Setting WorldShapefilePath, get the path, make a layer, and add to TOC IFeatureWorkspace pFeatWorkspace = pFactory.OpenFromFile(System.IO.Path.GetDirectoryName(ArcTimData.StaticClass.infoTable.Rows[0]["ShapefilePath"].ToString() + "\\" + shpFileName), 0) as IFeatureWorkspace; IFeatureClass pFeatClass = pFeatWorkspace.OpenFeatureClass(System.IO.Path.GetFileNameWithoutExtension(ArcTimData.StaticClass.infoTable.Rows[0]["ShapefilePath"].ToString() + "\\" + shpFileName)); IFeatureLayer pfeatureLayer = new FeatureLayerClass(); pfeatureLayer.Name = System.IO.Path.GetFileNameWithoutExtension(shpFileName); pfeatureLayer.FeatureClass = pFeatClass; pMap.AddLayer((ILayer)pfeatureLayer); IActiveView iav = pDoc.ActiveView; iav.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null); iav.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null); pDoc.UpdateContents(); }
private void btnExp2Map_Click(object sender, EventArgs e) { string sTipo = ""; string sRuta = ""; if (radioBtnProbabilidad.Checked) { sTipo = "Probabilidad"; sRuta = _sigpi.Parametros.RutaSIGPI + _sigpi.Parametros.Resultado; } else if (radioBtnModelo.Checked) { sTipo = "Modelo"; sRuta = _sigpi.Parametros.RutaSIGPI + _sigpi.Parametros.Raster; } if (lvwModelos.SelectedIndices.Count > 0) { string sModelo = lvwModelos.SelectedItems[0].Text; IMxDocument pMxDoc = m_pApp.Document as IMxDocument; IMap pMap = pMxDoc.FocusMap; IRasterLayer pRLayer = new RasterLayerClass(); pRLayer.CreateFromFilePath(sRuta + "\\" + sModelo); AsignarSimbologiaProbabilidad(pRLayer); pMap.AddLayer(pRLayer); if (pMap.LayerCount > 0) { pMap.MoveLayer(pRLayer, pMap.LayerCount - 1); } pMxDoc.UpdateContents(); pMxDoc.ActiveView.Refresh(); } //FrmExportMap frmExportMap = new FrmExportMap(_sigpi, lvwModelos.SelectedItems[0].Text, sTipo); //frmExportMap.ShowDialog(); }
private void AddTable(string strPath, string strFileName) { try { IWorkspaceFactory pFact = new ShapefileWorkspaceFactory(); IWorkspace pWorkspace = pFact.OpenFromFile(strPath, 0); IFeatureWorkspace pFeatws = pWorkspace as IFeatureWorkspace; ITable ptable = pFeatws.OpenTable(strFileName); IMxDocument pmxdoc = ArcMap.Document as IMxDocument; IMap pmap = pmxdoc.FocusMap; IStandaloneTable pStTab = new StandaloneTableClass(); pStTab.Table = ptable; IStandaloneTableCollection pStTabColl = pmap as IStandaloneTableCollection; pStTabColl.AddStandaloneTable(pStTab); pmxdoc.UpdateContents(); ITableWindow2 ptableWindow = new TableWindowClass(); ptableWindow.Application = ArcMap.Application; ptableWindow.StandaloneTable = pStTab; ptableWindow.Show(true); System.Runtime.InteropServices.Marshal.ReleaseComObject(pFact); System.Runtime.InteropServices.Marshal.ReleaseComObject(pWorkspace); System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatws); System.Runtime.InteropServices.Marshal.ReleaseComObject(ptable); System.Runtime.InteropServices.Marshal.ReleaseComObject(pStTab); System.Runtime.InteropServices.Marshal.ReleaseComObject(pStTabColl); System.Runtime.InteropServices.Marshal.ReleaseComObject(ptableWindow); GC.Collect(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
protected override void OnMouseUp(MouseEventArgs arg) { try { IPoint pPoint; //Point object for clicked location pPoint = m_pMxDoc.CurrentLocation; //Create string variable to hold the field name in the ortho index string orthoField = "ORTHOID"; //Call method to get value of clicked index string strFieldValue; strFieldValue = getFeatureVal.featureUtility(pPoint, m_pOrthoIndexLayer, orthoField); //Create a Raster Layer object IRasterLayer pRLayer; pRLayer = new RasterLayer(); //Set the path to the selected image pRLayer.CreateFromFilePath("C:/Users/micha/Documents/GEOG 489/Lesson_3/Data/orthos/" + strFieldValue + ".tif"); pRLayer.Name = "Tile " + strFieldValue; //Update layer name //Add the ortho image to the map m_pMap.AddLayer(pRLayer); //Move the image to the bottom in the TOC m_pMap.MoveLayer(pRLayer, m_pMap.LayerCount - 1); //Update the map contents m_pMxDoc.UpdateContents(); } catch (System.Exception ex) { MessageBox.Show("Error: This index does not have an orthophoto"); } }
/// <summary> /// Sets layer visibility in current map document /// </summary> /// <param name="ipMxDoc"></param> private void SetLayerVisibility(IMxDocument ipMxDoc) { IMap ipMap = ipMxDoc.FocusMap; //get all the layers from the map IEnumLayer ipEnumLayer; ILayer ipLayer; ipEnumLayer = ipMap.get_Layers(null, true); // 'is there anything visible??? if (colVisibleLayers.Count == 0) { return; } string strServer = ""; string strLayerName = ""; string strSecretName = ""; // 'is it in visible layer list? foreach (string layer in colVisibleLayers) { string[] s = DecodeServiceList(layer); if (s.Length == 3) { strServer = s[0]; strLayerName = s[1]; strSecretName = s[2]; } else if (s.Length == 2) { strServer = s[0]; strLayerName = s[1]; strSecretName = ""; } else if (s.Length == 1) { strServer = ""; strLayerName = s[0]; strSecretName = ""; } ipEnumLayer.Reset(); ipLayer = ipEnumLayer.Next(); do { if (ipLayer.Name == strLayerName) { SetLayerVisible(ipLayer, strLayerName, strSecretName); break; } ipLayer = ipEnumLayer.Next(); } while (ipLayer != null); } //'update toc ipMxDoc.UpdateContents(); // 'and update the view ipMxDoc.ActiveView.Refresh(); }
private static void MapUsingClassbreaksRenderer() { string layerName = CboLayers.GetSelectedLayer(); ILayer layer = GetLayerByName(layerName); IFeatureLayer2 fLayer = layer as IFeatureLayer2; string fieldName = CboFields.GetSelectedField(); // Get the number of classes string selectedClass = CboClasses.GetSelectedClass(); int numberOfClasses = Convert.ToInt32(selectedClass); ITableHistogram tableHistogram = new TableHistogramClass(); tableHistogram.Table = fLayer.FeatureClass as ITable; tableHistogram.Field = fieldName; IHistogram histo = tableHistogram as IHistogram; object datavalues, datafrequencies; histo.GetHistogram(out datavalues, out datafrequencies); IClassify classify = new QuantileClass(); classify.SetHistogramData(datavalues, datafrequencies); classify.Classify(ref numberOfClasses); if (numberOfClasses <= 1) { return; } double[] classBreaks = (double[])classify.ClassBreaks; IClassBreaksRenderer render = new ClassBreaksRenderer(); render.Field = fieldName; render.BreakCount = numberOfClasses; render.MinimumBreak = classBreaks[0]; // Get the colors ICmykColor[] colors = ColorbrewerExtension.GetCmykColors(); IFillSymbol fill = null; // Iterate through the colors for (int i = 0; i < numberOfClasses; i++) { fill = new SimpleFillSymbol(); fill.Color = colors[i]; fill.Outline.Width = 0.5; render.Symbol[i] = fill as ISymbol; render.Break[i] = classBreaks[i + 1]; render.Label[i] = string.Format("{0} to {1}", classBreaks[i] , classBreaks[i + 1]); } IGeoFeatureLayer gFLayer = layer as IGeoFeatureLayer; gFLayer.Renderer = render as IFeatureRenderer; IMxDocument mxDoc = ArcMap.Application.Document as IMxDocument; mxDoc.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, gFLayer , mxDoc.ActiveView.Extent); mxDoc.UpdateContents(); }
/// <summary> /// Sets layer visibility in current map document /// </summary> /// <param name="ipMxDoc"></param> private void SetLayerVisibility(IMxDocument ipMxDoc) { IMap ipMap = ipMxDoc.FocusMap; //get all the layers from the map IEnumLayer ipEnumLayer; ILayer ipLayer; ipEnumLayer = ipMap.get_Layers(null, true); // 'is there anything visible??? if (colVisibleLayers.Count == 0) return; string strServer = ""; string strLayerName = ""; string strSecretName = ""; // 'is it in visible layer list? foreach (string layer in colVisibleLayers) { string[] s = DecodeServiceList(layer); if (s.Length == 3) { strServer = s[0]; strLayerName = s[1]; strSecretName = s[2]; } else if (s.Length == 2) { strServer = s[0]; strLayerName = s[1]; strSecretName = ""; } else if (s.Length == 1) { strServer = ""; strLayerName = s[0]; strSecretName = ""; } ipEnumLayer.Reset(); ipLayer = ipEnumLayer.Next(); do { if (ipLayer.Name == strLayerName) { SetLayerVisible(ipLayer, strLayerName, strSecretName); break; } ipLayer = ipEnumLayer.Next(); } while (ipLayer != null); } //'update toc ipMxDoc.UpdateContents(); // 'and update the view ipMxDoc.ActiveView.Refresh(); }
public void CopyAnnotationFeatures() { try { IMxDocument pMxDoc = (IMxDocument)ArcMap.Application.Document; IMap pMap = pMxDoc.FocusMap; ILayer SourceLayer = pMap.Layer[0]; ILayer TargetLayer = pMap.Layer[1]; IFeatureLayer SourceFLayer = (IFeatureLayer)SourceLayer; IFeatureLayer TargetFLayer = (IFeatureLayer)TargetLayer; IFeatureClass SourceFeatureClass = SourceFLayer.FeatureClass; IFeatureClass TargetFeatureClass = TargetFLayer.FeatureClass; IFields TargetFields = TargetFeatureClass.Fields; IFields SourceFields = SourceFeatureClass.Fields; IDictionary <int, int> symbSourceTargIdXref = new Dictionary <int, int>(); symbSourceTargIdXref.Add(4, 17); symbSourceTargIdXref.Add(5, 22); symbSourceTargIdXref.Add(43, 45); symbSourceTargIdXref.Add(45, 45); ISymbolCollection targetSymbolsColl = (TargetFeatureClass.Extension as IAnnoClass).SymbolCollection; IField pFld; int[] lSrcFlds; int[] lTarFlds; int lFld, lExFld, i; lExFld = 0; for (lFld = 0; lFld <= (SourceFields.FieldCount - 1); lFld++) { pFld = SourceFields.Field[lFld]; if (pFld.Type != esriFieldType.esriFieldTypeOID && pFld.Type != esriFieldType.esriFieldTypeGeometry && pFld.Name.ToUpper() != "ELEMENT" && pFld.Name.ToUpper() != "ZORDER" && pFld.Editable == true) { lExFld = lExFld + 1; } } lSrcFlds = new int[lExFld]; lTarFlds = new int[lExFld]; i = 0; for (lFld = 0; lFld <= (SourceFields.FieldCount - 1); lFld++) { pFld = SourceFields.Field[lFld]; if (pFld.Type != esriFieldType.esriFieldTypeOID && pFld.Type != esriFieldType.esriFieldTypeGeometry && pFld.Name.ToUpper() != "ELEMENT" && pFld.Name.ToUpper() != "ZORDER" && pFld.Editable == true) { lSrcFlds[i] = lFld; lTarFlds[i] = TargetFields.FindField(pFld.Name); i = i + 1; } } IFeatureCursor pICursor; pICursor = SourceFeatureClass.Search(null, true); IFeature pIFeat; pIFeat = pICursor.NextFeature(); IFDOGraphicsLayerFactory pGLF; pGLF = new FDOGraphicsLayerFactory(); IDataset pDataset; pDataset = (IDataset)TargetFeatureClass; IAnnotationFeature pAnnoFeature; IClone pAClone; IElement pElement; IAnnoClass pTargetAnnoClass = (IAnnoClass)TargetFeatureClass.Extension; while (pIFeat != null) { pAnnoFeature = (IAnnotationFeature)pIFeat; if (pAnnoFeature.Annotation != null) { ITextElement sourceTextElement = pAnnoFeature.Annotation as ITextElement; pAClone = (IClone)sourceTextElement; pElement = (IElement)pAClone.Clone(); ITextElement ptempTxt = (ITextElement)pAClone.Clone(); //set id IFeature pTempFeat = TargetFeatureClass.CreateFeature(); ISymbolCollectionElement TargetSymbCollElem = (ISymbolCollectionElement)ptempTxt; ISymbolCollectionElement sourceSymbCollElem = sourceTextElement as ISymbolCollectionElement; int sourceSymbID = sourceSymbCollElem.SymbolID; int symbolID = symbSourceTargIdXref[sourceSymbID]; ISymbolIdentifier2 pSymbI; ISymbolCollection2 pSymbolColl2 = ( ISymbolCollection2 )pTargetAnnoClass.SymbolCollection; pSymbolColl2.GetSymbolIdentifier(symbolID, out pSymbI); //reset the desired symbol id TargetSymbCollElem.set_SharedSymbol(pSymbI.ID, pSymbI.Symbol); //save the annotation feature IAnnotationFeature pAnnoFeat = (IAnnotationFeature)pTempFeat; pAnnoFeat.Annotation = ptempTxt as IElement; pTempFeat.Store(); //reset the over rided property by analysing the override code if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideXOffset) <= sourceSymbCollElem.OverriddenProperties) { TargetSymbCollElem.XOffset = sourceSymbCollElem.XOffset; } if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideYOffset) <= sourceSymbCollElem.OverriddenProperties) { TargetSymbCollElem.YOffset = sourceSymbCollElem.YOffset; } if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideHorzAlignment) <= sourceSymbCollElem.OverriddenProperties) { TargetSymbCollElem.HorizontalAlignment = sourceSymbCollElem.HorizontalAlignment; } if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideVertAlignment) <= sourceSymbCollElem.OverriddenProperties) { TargetSymbCollElem.VerticalAlignment = sourceSymbCollElem.VerticalAlignment; } if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideFlipAngle) <= sourceSymbCollElem.OverriddenProperties) { TargetSymbCollElem.FlipAngle = TargetSymbCollElem.FlipAngle; } if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideSize) <= sourceSymbCollElem.OverriddenProperties) { TargetSymbCollElem.Size = sourceSymbCollElem.Size; } if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideColor) <= sourceSymbCollElem.OverriddenProperties) { TargetSymbCollElem.Color = sourceSymbCollElem.Color; } if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideCharSpacing) <= sourceSymbCollElem.OverriddenProperties) { TargetSymbCollElem.CharacterSpacing = sourceSymbCollElem.CharacterSpacing; } if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideCharWidth) <= sourceSymbCollElem.OverriddenProperties) { TargetSymbCollElem.CharacterWidth = sourceSymbCollElem.CharacterWidth; } if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideWordSpacing) <= sourceSymbCollElem.OverriddenProperties) { TargetSymbCollElem.WordSpacing = sourceSymbCollElem.WordSpacing; } if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideLeading) <= sourceSymbCollElem.OverriddenProperties) { TargetSymbCollElem.Leading = sourceSymbCollElem.Leading; } if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideBold) <= sourceSymbCollElem.OverriddenProperties) { TargetSymbCollElem.Bold = sourceSymbCollElem.Bold; } if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideItalic) <= sourceSymbCollElem.OverriddenProperties) { TargetSymbCollElem.Italic = sourceSymbCollElem.Italic; } if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideUnderline) <= sourceSymbCollElem.OverriddenProperties) { TargetSymbCollElem.Underline = sourceSymbCollElem.Underline; } if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideBackground) <= sourceSymbCollElem.OverriddenProperties) { TargetSymbCollElem.Background = sourceSymbCollElem.Background; } if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideFontName) <= sourceSymbCollElem.OverriddenProperties) { TargetSymbCollElem.FontName = sourceSymbCollElem.FontName; } //save the feature again pAnnoFeat.Annotation = ptempTxt as IElement; pTempFeat.Store(); } pIFeat = pICursor.NextFeature(); } pMxDoc.UpdateContents(); pMxDoc.ActiveView.Refresh(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
// Function with arguments that have been passed from each sensor. public void bandCombination(GUI_AddRaster theGUI, int int_RedBandIndex, int int_GreenBandIndex, int int_BlueBandIndex) { try { // Folder path only. string rasterFolderPath = System.IO.Path.GetDirectoryName(theGUI.textBox_PathURL.Text); // Image file name only. string rasterFileName = System.IO.Path.GetFileName(theGUI.textBox_PathURL.Text); // Map document. IMxDocument mxDoc = ArcMap.Application.Document as IMxDocument; // Needed for working with rasters. IWorkspaceFactory wSF = new RasterWorkspaceFactoryClass(); // Set the raster image workspace. IWorkspace wS = wSF.OpenFromFile(rasterFolderPath, ArcMap.Application.hWnd); // Prepare the raster workspace. IRasterWorkspace rasterWS = wS as IRasterWorkspace; // Open the raster image. IRasterDataset rasterDataset = rasterWS.OpenRasterDataset(rasterFileName); // Prepare raster image as raster layer. IRasterLayer rasterLayer = new RasterLayerClass(); // Create the raster layer from raster image. rasterLayer.CreateFromDataset(rasterDataset); // Add raster layer to map. mxDoc.AddLayer(rasterLayer); // Required for displaying raster layer with specific band combinations (the renderer). IRasterRGBRenderer2 rgbRen = new RasterRGBRendererClass(); IRasterRenderer rasRen = rgbRen as IRasterRenderer; // Assign band combination based on parameters that were fed into the function. rgbRen.RedBandIndex = int_RedBandIndex; rgbRen.GreenBandIndex = int_GreenBandIndex; rgbRen.BlueBandIndex = int_BlueBandIndex; // Rename the raster layer to sensor type + study type + image name, with spaces and file extension removed. rasterLayer.Name = theGUI.combo_SensorType.SelectedItem.ToString().Replace(" ", string.Empty) + "_" + theGUI.combo_StudyType.SelectedItem.ToString().Replace(" ", string.Empty) + "__" + System.IO.Path.GetFileNameWithoutExtension(rasterFileName).Replace(" ", string.Empty); // Update the renderer with band combinations. rasterLayer.Renderer = rasRen; rasRen.Update(); if (theGUI.checkBox_RasterExtent.Checked) { // Zoom to raster image extent if the checkbox is checked. mxDoc.ActiveView.Extent = rasterLayer.AreaOfInterest; } // Refresh the map and update the table of contents. mxDoc.ActiveView.Refresh(); mxDoc.UpdateContents(); } catch (Exception exc) { // Catch any exception found and display a message box. MessageBox.Show("Exception caught: " + nL + exc.Message + nL + exc.StackTrace); return; } }
//this method is executed when the user wants to zoom to the user-defined object id in textbox 1 private void btnZoomOID1_Click(object sender, EventArgs e) { try { IFeatureLayer pFeatureLayer = null; //clear the selected features - in case other layers are selected pMap.ClearSelection(); //get access to the layer associated with the objectid the user wants to zoom to for (int i = 0; i < pMap.LayerCount; i++) { //check to see if the layer is an event layer (ex: VoterXY) if (pMap.get_Layer(i) is FeatureLayer) { pFeatureLayer = pMap.get_Layer(i) as IFeatureLayer; if (!(pFeatureLayer is IEventSource)) { if (pFeatureLayer.Name == cboLayer1.Text) { pFeatureLayer.Visible = true; break; } } } } IFeatureSelection pFeatureSelection = pFeatureLayer as IFeatureSelection; //QI pFeatureSelection.Clear(); //set up query filter IQueryFilter pQueryFilter = new QueryFilter(); pQueryFilter.WhereClause = "OBJECTID = " + txtOID1.Text; pActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, null); pFeatureSelection.SelectFeatures(pQueryFilter, esriSelectionResultEnum.esriSelectionResultNew, false); pActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, null); pFeatureSelection.SelectionChanged(); //refresh the maps - allow the selection anchor to display ISelectionEvents pSelectionEvents = pMap as ISelectionEvents; pSelectionEvents.SelectionChanged(); //zoom to selected features UID pUID = new UID(); pUID.Value = "{AB073B49-DE5E-11D1-AA80-00C04FA37860}"; clsAgrcArcMapExtension.m_application.Document.CommandBars.Find(pUID).Execute(); //refresh map pActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null); pActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null); pMxDocument.UpdateContents(); } catch (Exception ex) { MessageBox.Show("Error Message: " + Environment.NewLine + ex.Message + Environment.NewLine + Environment.NewLine + "Error Source: " + Environment.NewLine + ex.Source + Environment.NewLine + Environment.NewLine + "Error Location:" + Environment.NewLine + ex.StackTrace, "AGRC Custom Tools ArcMap Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
private void createDataFrame(string sMapName) { try { IMxDocument pMxDoc = (IMxDocument)ArcMap.Document; IMap pMap = new MapClass(); pMap.Name = sMapName; //Dictionary<string, string> dctMapLayers = Dictionary <string, string> dctMapLayers = new Dictionary <string, string>(); switch (sMapName.ToUpper()) { case "ECONOMIC DEVELOPMENT": dctMapLayers = SConst.EconDevLayers; this.loadLayers(ref pMap, dctMapLayers, this.m_EconOnLayers); break; case "FIRE": dctMapLayers = SConst.FireLayers; this.loadLayers(ref pMap, dctMapLayers, this.m_FireOnLayers); break; case "PLANNING": dctMapLayers = SConst.PlanningLayers; this.loadLayers(ref pMap, dctMapLayers, this.m_PlanOnLayers); break; case "POLICE": dctMapLayers = SConst.PoliceLayers; this.loadLayers(ref pMap, dctMapLayers, this.m_PoliceOnLayers); break; case "PUBLIC WORKS": dctMapLayers = SConst.PublicWorksLayers; this.loadLayers(ref pMap, dctMapLayers, this.m_PWOnLayers); break; default: return; } //addMapLayers(ref pMap, sMapName); IEnvelope pEnv = new EnvelopeClass(); pEnv.PutCoords(1, 1, 5, 4); // page units pMxDoc.Maps.Add(pMap); IMapFrame pMapFrame = this.MakeMapFrame(pEnv, pMap); pMapFrame.Map.MapUnits = esriUnits.esriFeet; IGraphicsContainer pGC = (IGraphicsContainer)pMxDoc.PageLayout; pGC.AddElement((IElement)pMapFrame, 0); pMxDoc.CurrentContentsView.Refresh(null); pMxDoc.UpdateContents(); Application.DoEvents(); // activate the frame and zoom to the extent of the UGB for (int i = 0; i < pMxDoc.Maps.Count; i++) { IMap map = pMxDoc.Maps.get_Item(i); if (map.Name == sMapName) { pMxDoc.ActiveView = (IActiveView)map; //Set the query filter. use the arguements passed into the function ESRI.ArcGIS.Geodatabase.IQueryFilter pQueryFilter = new ESRI.ArcGIS.Geodatabase.QueryFilterClass(); pQueryFilter.WhereClause = "CITY = 'Medford'"; using (CSpatialSubs oSpatialSubs = new CSpatialSubs()) { oSpatialSubs.selectFeatures(pQueryFilter, this.App, (IFeatureLayer)oSpatialSubs.returnFeatureLayer(pMap, "MEDSDE.DBO.Urban_Growth_Boundary"), true); } pMxDoc.FocusMap.ClearSelection(); } } pMxDoc.UpdateContents(); Application.DoEvents(); } catch (Exception ex) { string s = ex.Message; s += ex.InnerException.Message; s += " "; } }
protected override void OnMouseUp(MouseEventArgs arg) { try { IPoint pPoint; //Point object for clicked location pPoint = m_pMxDoc.CurrentLocation; //Create string variable to hold the field name in the ortho index string streetField = "NEWID"; //Call method to get value of clicked index string strFieldStreet; strFieldStreet = getFeatureVal.featureUtility(pPoint, m_pStreetIndexLayer, streetField); //Create a Raster Layer object IFeatureLayer pFLayer; pFLayer = new FeatureLayer(); //Create workspace object to hold the file location IWorkspaceFactory pWSFactory; pWSFactory = new ShapefileWorkspaceFactory(); //Set filepath to workspace IWorkspace pWorkspace; pWorkspace = pWSFactory.OpenFromFile("C:/Users/micha/Documents/GEOG 489/Lesson_3/Data/roads/", ArcMap.Application.hWnd); //Create feature object IFeatureWorkspace pFWorkspace; pFWorkspace = (IFeatureWorkspace)pWorkspace; //Set name of feature to the selected roads name IFeatureClass pFClass; pFClass = pFWorkspace.OpenFeatureClass("roads_" + strFieldStreet + ".shp"); pFLayer.FeatureClass = pFClass; //Change name of layer to "Roads - selected field" pFLayer.Name = "Roads - " + strFieldStreet; //*********Symbology for roads************** //Create RGB object IRgbColor pRGBColor; pRGBColor = new RgbColor(); //Set RGB values to the new object pRGBColor.Red = 0; pRGBColor.Green = 255; pRGBColor.Blue = 255; //Create simple line object for road cl ISimpleLineSymbol pSimpleLine; pSimpleLine = new SimpleLineSymbol(); //Set the width, style and color of the streets pSimpleLine.Width = 0.5; pSimpleLine.Style = ESRI.ArcGIS.Display.esriSimpleLineStyle.esriSLSDot; pSimpleLine.Color = pRGBColor; //Create the renderer ISimpleRenderer pSimpleRenderer; pSimpleRenderer = new SimpleRenderer(); pSimpleRenderer.Symbol = (ISymbol)pSimpleLine; //Create geo feature to apply renderer IGeoFeatureLayer pGeoFLayer; pGeoFLayer = (IGeoFeatureLayer)pFLayer; pGeoFLayer.Renderer = (IFeatureRenderer)pSimpleRenderer; //Add layer to map m_pMap.AddLayer(pFLayer); //Update the map contents m_pMxDoc.UpdateContents(); } catch (System.Exception ex) { MessageBox.Show("Error: This index does not have any streets"); } }
private void btnExp2Map_Click_1(object sender, EventArgs e) { if (m_pApp != null) { IRasterLayer pRLayer = new RasterLayerClass(); try { this.Cursor = Cursors.WaitCursor; DateTime fechaExportacion = monthCalendar1.SelectionStart; int iMonth = fechaExportacion.Month; string sMonth = (iMonth.ToString().Length == 1 ? "0" + iMonth.ToString() : iMonth.ToString()); int iYear = fechaExportacion.Year; string sNombreFileGDB = iYear.ToString() + "-" + sMonth + "-Modelos.gdb"; IWorkspaceFactory pWF = new FileGDBWorkspaceFactoryClass(); string sRutaFileGDB = Sigpi.Parametros.RutaSIGPI + "\\" + Sigpi.Parametros.Resultado + "\\" + sNombreFileGDB; IRasterWorkspaceEx pRWorkspace = (IRasterWorkspaceEx)pWF.OpenFromFile(sRutaFileGDB, 0); string sNombreCapa = "Amenaza_" + fechaExportacion.ToString("yyyy_MM_dd"); IRasterDataset pRDataset = pRWorkspace.OpenRasterDataset(sNombreCapa); pRLayer.CreateFromDataset(pRDataset); pRLayer.Name = sNombreCapa; IMxDocument pMxDoc = m_pApp.Document as IMxDocument; IMap pMap = pMxDoc.FocusMap; AsignarSimbologiaProbabilidad(pRLayer); IEnumLayer pEnumLayer = pMap.Layers; ILayer pLayer = pEnumLayer.Next(); Boolean bLayerInMap = false; while (pLayer != null) { if (pLayer.Name.Contains("Amenaza_")) { pLayer.Visible = false; } if (pLayer.Name.Equals(sNombreCapa)) { bLayerInMap = true; pLayer.Visible = true; } pLayer = pEnumLayer.Next(); } System.Windows.Forms.Application.DoEvents(); if (!bLayerInMap) { pMap.AddLayer(pRLayer); if (pMap.LayerCount > 0) { pMap.MoveLayer(pRLayer, pMap.LayerCount - 1); } } if (!(pMxDoc.ActiveView is IPageLayout)) { pMxDoc.ActiveView = (IActiveView)pMxDoc.PageLayout; } IPageLayout pageLayout = pMxDoc.PageLayout; IGraphicsContainer pGraphicsContainer = (IGraphicsContainer)pageLayout; pGraphicsContainer.Reset(); IElement pElement; pElement = pGraphicsContainer.Next(); while (pElement != null) { if (pElement is ITextElement) { ITextElement pTxtElement = (ITextElement)pElement; IElementProperties3 pElemProperties = (IElementProperties3)pTxtElement; if (pElemProperties.Name.Equals("lblProbabilidad")) { pTxtElement.Text = "PROBABILIDAD PARA EL " + fechaExportacion.ToLongDateString(); } if (pElemProperties.Name.Equals("lblFechaGeneracion")) { pTxtElement.Text = "Fecha Generación: " + DateTime.Now.ToLongTimeString(); } } pElement = pGraphicsContainer.Next(); } pMxDoc.UpdateContents(); pMxDoc.ActiveView.Refresh(); String fileName = Sigpi.Parametros.RutaSIGPI + "\\" + "JPG" + "\\" + sNombreCapa + "_Incendios_INTERNET_.jpg"; CreateJPEGFromActiveView(pMxDoc.ActiveView, fileName); fileName = Sigpi.Parametros.RutaSIGPI + "\\" + "JPG" + "\\" + sNombreCapa + "_Incendios.jpg"; CreateJPEGHiResolutionFromActiveView(pMxDoc.ActiveView, fileName); MessageBox.Show("Se ha generado el mapa de amenazas en formato JPG"); // opens the folder in explorer Process.Start(Sigpi.Parametros.RutaSIGPI + "\\" + "JPG"); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error cargando Capa!!!"); } } this.Cursor = Cursors.Default; //string sTipo = ""; //string sRuta = ""; //if (radioBtnProbabilidad.Checked) //{ // sTipo = "Probabilidad"; // sRuta = _sigpi.Parametros.RutaSIGPI + _sigpi.Parametros.Resultado; //} //else if (radioBtnModelo.Checked) //{ // sTipo = "Modelo"; // sRuta = _sigpi.Parametros.RutaSIGPI + _sigpi.Parametros.Raster; //} //if (lvwModelos.SelectedIndices.Count > 0) //{ // string sModelo = lvwModelos.SelectedItems[0].Text; // IMxDocument pMxDoc = m_pApp.Document as IMxDocument; // IMap pMap = pMxDoc.FocusMap; // IRasterLayer pRLayer = new RasterLayerClass(); // pRLayer.CreateFromFilePath(sRuta + "\\" + sModelo); // AsignarSimbologiaProbabilidad(pRLayer); // pMap.AddLayer(pRLayer); // if (pMap.LayerCount > 0) // { // pMap.MoveLayer(pRLayer, pMap.LayerCount - 1); // } // pMxDoc.UpdateContents(); // pMxDoc.ActiveView.Refresh(); //} //FrmExportMap frmExportMap = new FrmExportMap(_sigpi, lvwModelos.SelectedItems[0].Text, sTipo); //frmExportMap.ShowDialog(); }
protected override void OnClick() { // Create two points. IPoint fromPoint = new Point(); fromPoint.PutCoords(1300757, 554219); IPoint toPoint = new Point(); toPoint.PutCoords(1300759, 554217); // Note: Spatial Reference = NAD_1983_StatePlane_Washington_North_FIPS_4601_Feet // ****** No Need to go through IPointCollection **** //// Add the points to a point collection //object missing = Type.Missing; //IPointCollection pointCollection = new Multipoint(); //pointCollection.AddPoint(fromPoint, ref missing, ref missing); //pointCollection.AddPoint(toPoint, ref missing, ref missing); // ****** No Need to go through IPointCollection **** // Get a reference to a feature class from ArcMap IMap map = ArcMap.Document.ActiveView as IMap; ILayer layer = map.get_Layer(0); IFeatureLayer featureLayer = layer as FeatureLayer; IFeatureClass featureClass = featureLayer.FeatureClass; IFeature feature = featureClass.CreateFeature(); IPolyline polyline = new PolylineClass(); polyline.FromPoint = fromPoint; polyline.ToPoint = toPoint; //IPolyline polyline = pointCollection as IPolyline; // This leads to a null polyline feature.Shape = polyline as IGeometry; feature.Store(); // ---- Symbolize the polyline with the ArrorMarker at both ends of the line ----------- // See: http://resources.arcgis.com/en/help/arcobjects-net/conceptualhelp/index.html#//0001000008w8000000 ICartographicLineSymbol ipArrowLineSymbol = new CartographicLineSymbol(); // the line color will be red IRgbColor ipRgbRedColor = new RgbColorClass(); ipRgbRedColor.Red = 192; // the arrow will be black IRgbColor ipRgbBlackColor = new RgbColorClass(); ipRgbBlackColor.RGB = 0; // set up the arrow that will be displayed along the line IArrowMarkerSymbol ipArrowMarker = new ArrowMarkerSymbolClass(); ipArrowMarker.Style = esriArrowMarkerStyle.esriAMSPlain; ipArrowMarker.Length = 18; ipArrowMarker.Width = 12; ipArrowMarker.Color = ipRgbBlackColor; // set up the line itself ipArrowLineSymbol.Width = 4; ipArrowLineSymbol.Color = ipRgbRedColor; // decorate the line with the arrow symbol ISimpleLineDecorationElement ipSimpleLineDecorationElement = new SimpleLineDecorationElementClass(); ipSimpleLineDecorationElement.Rotate = true; ipSimpleLineDecorationElement.PositionAsRatio = true; ipSimpleLineDecorationElement.MarkerSymbol = ipArrowMarker; ipSimpleLineDecorationElement.AddPosition(0.0); ipSimpleLineDecorationElement.AddPosition(1.0); ipSimpleLineDecorationElement.FlipFirst = true; ILineDecoration ipLineDecoration = new LineDecorationClass(); ipLineDecoration.AddElement(ipSimpleLineDecorationElement); ((ILineProperties)ipArrowLineSymbol).LineDecoration = ipLineDecoration; // Create renderer and apply it to the layer ISimpleRenderer simpleRenderer = new SimpleRendererClass(); simpleRenderer.Symbol = ipArrowLineSymbol as ISymbol; IGeoFeatureLayer geoFeatureLayer = featureLayer as IGeoFeatureLayer; geoFeatureLayer.Renderer = simpleRenderer as IFeatureRenderer; IMxDocument mxDocument = ArcMap.Application.Document as IMxDocument; mxDocument.ActiveView.Refresh(); mxDocument.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, geoFeatureLayer, mxDocument.ActiveView.Extent); mxDocument.UpdateContents(); // ---- Symbolize the polyline with the ArrorMarker at both ends of the line ----------- ArcMap.Application.CurrentTool = null; }
/// <summary> /// Ejecuta el modelo de amenazas de incendios /// </summary> /// <param name="sTablaPrecipPromedio">Tabla Precipitacion Promedio</param> /// <param name="sConsultaTablaPrecipPromedio">SQL para la table precipitacion promedio</param> /// <param name="sPrefijo">Prefijo para los nombres de las capas</param> /// <param name="sTablaTempPromedio">Nombre de la tabla temporal de promedios</param> /// <param name="sConsultaTablaTempPromedio">SQL para la tabla temporal de promedios</param> /// <param name="bUsarSatelite">Indica si se han de utilizar las imagenes de satelita</param> /// <param name="bMostrarIntermedios">Indica si se mostraran los resultados intermedios en el mapa activo</param> private void GenerarModelo(string sTablaPrecipPromedio, string sConsultaTablaPrecipPromedio, string sPrefijo, string sTablaTempPromedio, string sConsultaTablaTempPromedio, bool bUsarSatelite, bool bMostrarIntermedios, String[] sRastersPrecipitacion) { String sPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase); String tempDir = ""; sPath = sPath.Replace("file:\\", ""); SIGPIParametros parametros = new SIGPIParametros(); try { XmlSerializer serializer = new XmlSerializer(typeof(SIGPIParametros)); System.IO.StreamReader r = new System.IO.StreamReader(sPath + "\\parameters\\parametros.xml"); parametros = (SIGPIParametros)serializer.Deserialize(r); r.Close(); serializer = null; r = null; } catch (Exception ex) { MessageBox.Show(ex.Message, "SIGPI 2013"); return; } SIGPIProcesamiento procesamiento = new SIGPIProcesamiento(parametros); SIGPICls sigpi = new SIGPICls(); SIGPIDao sigpiDao = new SIGPIDao(); sigpiDao.ConnectLocalDB(parametros.RutaBD); sigpiDao.UltimaFechaIncorporacion(sigpi); sigpi.Parametros = parametros; OleDbCommand command = sigpiDao.LocalDBConnection.CreateCommand(); OleDbParameter param = command.CreateParameter(); OleDbParameter param1 = command.CreateParameter(); param.ParameterName = "fecProce"; param.Value = sigpi.FechaProcesamiento; command.CommandText = "UPDATE FECHAS_PROCESO SET FEC_PROCE = @fecProce"; command.Parameters.Add(param); string sSQL = ""; // "UPDATE FECHAS_PROCESO SET FEC_PROCE = #" + sigpi.FechaProcesamiento.ToString("MM/dd/yyyy") + "#"; try { sigpiDao.EjecutarSentenciaSinQuery(command); } catch (Exception ex) { MessageBox.Show("No se pudo actualizar la fecha de incorporacion.\n" + ex.Message); } IProgressDialogFactory pProDiaFac = new ProgressDialogFactoryClass(); IStepProgressor pStepPro = pProDiaFac.Create(null, 0); pStepPro.MinRange = 1; pStepPro.MaxRange = 5; pStepPro.StepValue = 1; IProgressDialog2 pProDia = (IProgressDialog2)pStepPro; pProDia.Animation = esriProgressAnimationTypes.esriProgressGlobe; pProDia.Title = "Generar Modelo Amenazas"; pProDia.ShowDialog(); pStepPro.Step(); pStepPro.Message = "Generando Grids Meteorologicos..."; IFeatureClass pFeatureClass; IWorkspaceFactory pShpWorkspaceFactory = new ShapefileWorkspaceFactoryClass(); IWorkspaceFactory pFileGDBWorkspaceFactory = new FileGDBWorkspaceFactoryClass(); string sFormatTmp = "gdb_" + sigpi.FechaProcesamiento.ToString("yyyyMMdd") + "_" + DateTime.Now.ToString("HHmmss"); tempDir = sigpi.Parametros.TempDir; if (tempDir == null || tempDir.Trim().Equals("")) { tempDir = System.IO.Path.GetTempPath(); } string sRutaFileGDB = System.IO.Path.GetTempPath() + sFormatTmp + ".gdb"; if (System.IO.Directory.Exists(sRutaFileGDB)) { try { System.IO.Directory.Delete(sRutaFileGDB); } catch (Exception ex) { MessageBox.Show("No se pudo borrar la File Geodatabase Temporal: " + sRutaFileGDB + " Intente Borrarla Manualmente. " + ex.Message); return; } } Geoprocessor gp = new Geoprocessor(); IWorkspaceName pWSName; string sCapaResultado = "Amenaza_" + sigpi.FechaProcesamiento.ToString("yyyy_MM_dd"); string sRutaGdbResultados = parametros.RutaSIGPI + parametros.Resultado + "\\" + sigpi.FechaProcesamiento.Year.ToString() + "-" + sigpi.FechaProcesamiento.ToString("MM") + "-Modelos.gdb"; if (System.IO.Directory.Exists(sRutaGdbResultados)) { GPUtilitiesClass gpUtilClass = new GPUtilitiesClass(); try { Delete del = new Delete(); del.in_data = sRutaGdbResultados + "\\" + sCapaResultado; gp.Execute(del, null); } catch (Exception) { } } else { try { pWSName = pFileGDBWorkspaceFactory.Create(parametros.RutaSIGPI + parametros.Resultado + "\\", sigpi.FechaProcesamiento.Year.ToString() + "-" + sigpi.FechaProcesamiento.ToString("MM") + "-Modelos.gdb", null, 0); } catch (Exception ex) { MessageBox.Show("No se pudo crear la Geodatabase de resultados: \n" + sRutaGdbResultados); pStepPro.Hide(); } } pWSName = pFileGDBWorkspaceFactory.Create(System.IO.Path.GetTempPath(), sFormatTmp, null, 0); ESRI.ArcGIS.esriSystem.IName name = (ESRI.ArcGIS.esriSystem.IName)pWSName; IFeatureWorkspace pWorkspaceTemp; try { pWorkspaceTemp = (IFeatureWorkspace)name.Open(); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } IWorkspaceFactory pWF = new AccessWorkspaceFactoryClass(); IFeatureWorkspace pWSMask = (IFeatureWorkspace)pWF.OpenFromFile(parametros.RutaGBD, 0); IGeoDataset pFCMask = (IGeoDataset)pWSMask.OpenFeatureClass(parametros.Mascara); ISpatialReference pSpaRef = pFCMask.SpatialReference; IEnvelope pEnv = pFCMask.Extent; string sNombreTabla = "TMPPR_"; DateTime fechaProcesamiento = sigpi.FechaProcesamiento; fechaProcesamiento = fechaProcesamiento.Date; for (int i = 0; i < 10; i++) { try { sigpiDao.EjecutarSentenciaSinQuery("DROP TABLE " + sNombreTabla + i.ToString()); } catch (Exception ex) { System.Console.WriteLine(ex.Message); } // "IIf([LECTUS_PRECI]![LECTURA]<=2,5,IIf([LECTUS_PRECI]![LECTURA]<=8 And [LECTUS_PRECI]![LECTURA]>2,4,IIf([LECTUS_PRECI]![LECTURA]<=14 And [LECTUS_PRECI]![LECTURA]>8,3,IIf([LECTUS_PRECI]![LECTURA]<=24 And [LECTUS_PRECI]![LECTURA]>14,2,IIf([LECTUS_PRECI]![LECTURA]>24,1,0))))) AS LECTURAS " + //sSQL = "SELECT CODIGO, FECHA, X, Y, LECTURA AS RASTERVALU " + // "INTO " + sNombreTabla + i.ToString() + " " + // "FROM LECTUS_PRECI " + // "WHERE (((FECHA)=#" + sigpi.FechaProcesamiento.AddDays(-i).ToString("MM/dd/yyyy") + "#))"; command = sigpiDao.LocalDBConnection.CreateCommand(); command.CommandText = "SELECT CODIGO, FECHA, X, Y, LECTURA AS RASTERVALU " + "INTO " + sNombreTabla + i.ToString() + " " + "FROM LECTUS_PRECI " + "WHERE (((FECHA) >=@fecha) and ((FECHA) <@fecha1))"; param = command.CreateParameter(); param.ParameterName = "fecha"; param.Value = sigpi.FechaProcesamiento.AddDays(-i); command.Parameters.Add(param); param1 = command.CreateParameter(); param1.ParameterName = "fecha1"; param1.Value = sigpi.FechaProcesamiento.AddDays(-i + 1); command.Parameters.Add(param1); try { sigpiDao.EjecutarSentenciaSinQuery(command); } catch (Exception ex) { MessageBox.Show("Error generando las tablas temporales de precipitaciones. Descripcion: \n" + ex.Message); //pProDia.HideDialog(); return; } } try { sigpiDao.EjecutarSentenciaSinQuery("DROP TABLE TEMPERATURA_PROMEDIO"); } catch (Exception ex) { } //"IIf(Avg(LECTUS_TEMPE.LECTURA)<=6,1,IIf(Avg(LECTUS_TEMPE.LECTURA) <=12 And Avg(LECTUS_TEMPE.LECTURA)>6,2," + //"IIf(Avg(LECTUS_TEMPE.LECTURA)<=18 And Avg(LECTUS_TEMPE.LECTURA)>12,3,IIf(Avg(LECTUS_TEMPE.LECTURA)<=24 And " + //"Avg(LECTUS_TEMPE.LECTURA)>12,4,IIf(Avg(LECTUS_TEMPE.LECTURA)>24,5,0))))) AS LECTURAS, " + //sSQL = "SELECT CODIGO, Max(LECTUS_TEMPE.FECHA) AS FECHA, 10 AS Num_Dias, X, Y, AVG(LECTURA) AS RASTERVALU " + // "INTO TEMPERATURA_PROMEDIO " + // "FROM LECTUS_TEMPE " + // "WHERE (((FECHA)>=#" + sigpi.FechaProcesamiento.AddDays(-10).ToString("MM/dd/yyyy") + "# " + // "And (FECHA)<=#" + sigpi.FechaProcesamiento.ToString("MM/dd/yyyy") + "#)) " + // "GROUP BY CODIGO, X, Y"; command = sigpiDao.LocalDBConnection.CreateCommand(); command.CommandText = "SELECT CODIGO, Max(LECTUS_TEMPE.FECHA) AS FECHA, 10 AS Num_Dias, X, Y, AVG(LECTURA) AS RASTERVALU " + "INTO TEMPERATURA_PROMEDIO " + "FROM LECTUS_TEMPE " + "WHERE (((FECHA)>= @fecha1 " + "And (FECHA)<= @fecha)) " + "GROUP BY CODIGO, X, Y"; param = command.CreateParameter(); param.ParameterName = "fecha"; param.Value = sigpi.FechaProcesamiento; param1 = command.CreateParameter(); param1.ParameterName = "fecha1"; param1.Value = sigpi.FechaProcesamiento.AddDays(-10); command.Parameters.Add(param1); command.Parameters.Add(param); try { sigpiDao.EjecutarSentenciaSinQuery(command); } catch (Exception ex) { MessageBox.Show("Error Generando Tabla: TEMPERATURA_PROMEDIO " + ex.Message); pProDia.HideDialog(); return; } string sExpression = ""; string sOutGrid; double dPeso = 0; string sAmenazaXPrecipitacion = sRutaFileGDB + "\\amenaza_x_precipitacion"; string sTablaTemperaturaPromedio = "TEMPERATURA_PROMEDIO"; string sFCTempPromedio = "TEMP_PROMEDIO"; string sPrefijoIDW = "idw"; string sAmenazaXTemperatura = sRutaFileGDB + "\\" + "amenaza_x_temperatura"; string sAmenazasParciales = parametros.RutaGBD + "\\" + "amenazas_parciales_2"; string sAmenazaBruta = sRutaFileGDB + "\\amenaza_incendio_bruta"; string sAmenazaFinal = sRutaFileGDB + "\\amenaza_incendio_final"; string sTablaReclassIncendios = parametros.TablaReclasificacionIncendios; //"tbl_reclass_amenaza_incendios"; string sTablaReclassTemp = parametros.TablaReclasificacionTemperatura; //"tbl_reclass_temperatura"; string sTablaReclassPrecip = parametros.TablaReclasificacionPrecipitacion; //"tbl_reclass_precipitacion"; string sAmenazaXTemperaturaCombinada = sRutaFileGDB + "\\" + "amenaza_x_temperatura_combinada"; string sEstVirtualesPrecipitacion = sRutaFileGDB + "\\" + "estaciones_virtuales_precipitacion"; string sAmenazaXPrecipitacionCombinada = sRutaFileGDB + "\\" + "amenaza_x_precipitacion_combinada"; string sAmenazaFinalBrutaNVI = sRutaFileGDB + "\\" + "amenaza_incend_raw_nvi"; string sNVITempReclass = sRutaFileGDB + "\\" + "nvi_reclass_temp"; string sFromField = "FROM_"; string sToField = "TO_"; string sOutField = "OUT"; string sNoData = "NODATA"; string sFieldLecturas = "RASTERVALU"; //LECTURAS"; string sTipoEstadistico = parametros.TipoEstadistico; //"MAXIMUM"; string sAmenazaXPrecipReclass = sAmenazaXPrecipitacion + "_reclass"; string sAmenazaXTempReclass = sAmenazaXTemperatura + "_reclass"; string nvi = parametros.RutaSIGPI + "NVI" + "\\" + "tmpMosaic.500m_16_days_NDVI_GEO.tif"; double dPesoPrecipitacion = parametros.PesoPrecipitacion; //0.29; double dPesoTemperatura = parametros.PesoTemperatura; //0.24; double dPesoAmenazasParciales = parametros.PesoAmenazasParciales; //0.47; IDataset pDS; IDatasetName pDSName; IDatasetName pDSName2 = new FeatureClassNameClass(); IExportOperation pExportOp = new ExportOperationClass(); string sEstacionesVirtuales = sRutaFileGDB + "\\" + "EstacionesVirtuales.shp"; ExtractValuesToPoints extractValPoint = new ExtractValuesToPoints(); extractValPoint.in_point_features = sEstacionesVirtuales; extractValPoint.interpolate_values = "NONE"; extractValPoint.add_attributes = "VALUE_ONLY"; //'0.037037037; // 1" = 1/3600 double dCellSize = parametros.TamanoCelda / (3600 * 30); double[] iPesos = parametros.Pesos; //{ 30, 20, 10, 9, 8, 7, 6, 5, 4, 3 }; double iTotalPesos = 0; //102; foreach (double dP in iPesos) { iTotalPesos += dP; } gp.AddOutputsToMap = bMostrarIntermedios; gp.SetEnvironmentValue("Mask", parametros.RutaGBD + "\\" + parametros.Mascara); gp.SetEnvironmentValue("Extent", pEnv.XMin.ToString() + " " + pEnv.YMin.ToString() + " " + pEnv.XMax.ToString() + " " + pEnv.YMax.ToString()); ESRI.ArcGIS.SpatialAnalystTools.Idw idw = new Idw(); idw.z_field = sFieldLecturas; idw.cell_size = dCellSize; for (int i = 0; i < 10; i++) { pFeatureClass = procesamiento.FCPrecipitacion(sNombreTabla + i.ToString(), pSpaRef); pDS = (IDataset)pFeatureClass; pDSName = (IDatasetName)pDS.FullName; pDSName2.Name = sNombreTabla + i.ToString(); pDSName2.WorkspaceName = pWSName; try { pExportOp.ExportFeatureClass(pDSName, null, null, null, (IFeatureClassName)pDSName2, 0); } catch (Exception ex) { MessageBox.Show(ex.Message); pProDia.HideDialog(); return; } if (bUsarSatelite) { //Geoprocessor gp1 = new Geoprocessor(); //extractValPoint.in_raster = sRastersPrecipitacion[i]; // txtRutaPrecipitacion.Text; //extractValPoint.out_point_features = sEstVirtualesPrecipitacion + i.ToString(); //try //{ // gp1.Execute(extractValPoint, null); //} //catch (Exception ex) //{ // MessageBox.Show(ex.Message); //} //Merge merge = new Merge(); //string sInputMerge = sRutaFileGDB + "\\" + sNombreTabla + i.ToString() + ";" + sEstVirtualesPrecipitacion + i.ToString(); //merge.inputs = sInputMerge; ////"[" + sRutaFileGDB + "\\" + sNombreTabla + i.ToString() + ";" + sEstVirtualesPrecipitacion + i.ToString() + "]" ; //merge.output = sRutaFileGDB + "\\" + "est_precip_temporal" + i.ToString(); //try //{ // gp.Execute(merge, null); //} //catch (Exception ex) //{ // MessageBox.Show(ex.Message); //} //idw.in_point_features = sRutaFileGDB + "\\" + "est_precip_temporal" + i.ToString(); idw.in_point_features = sRutaFileGDB + "\\" + sNombreTabla + i.ToString(); } else { idw.in_point_features = sRutaFileGDB + "\\" + sNombreTabla + i.ToString(); } sOutGrid = sRutaFileGDB + "\\" + sPrefijoIDW + "_" + sNombreTabla + i.ToString(); idw.out_raster = sOutGrid; try { gp.Execute(idw, null); } catch (Exception ex) { MessageBox.Show(ex.Message); } dPeso = iPesos[i] / iTotalPesos; sExpression += "( Raster(r'" + sOutGrid + "') * " + dPeso.ToString().Replace(",", ".") + ")"; if (i < 9) { sExpression += " + "; } } pStepPro.Step(); ////for (int i = 0; i < 10; i++) ////{ //// //pStepPro.Message = "Generando Modelo Precipitacion: " + i.ToString(); //// sOutGrid = sRutaFileGDB + "\\" + sPrefijoIDW + "_" + sNombreTabla + i.ToString(); //// idw.in_point_features = sRutaFileGDB + "\\" + sNombreTabla + i.ToString(); //// idw.out_raster = sOutGrid; //// gp.Execute(idw, null); //// dPeso = iPesos[i] / iTotalPesos; //// sExpression += "(" + sOutGrid + " * " + dPeso.ToString() + ")"; //// if (i < 9) //// sExpression += " + "; ////} //gp.AddMessage("Expresion: " + sExpression); //SingleOutputMapAlgebra mapAlgebra = new SingleOutputMapAlgebra(); ESRI.ArcGIS.SpatialAnalystTools.RasterCalculator mapAlgebra = new RasterCalculator(); //mapAlgebra.expression_string = sExpression; // mapAlgebra.out_raster = sAmenazaXPrecipitacion; mapAlgebra.expression = sExpression; mapAlgebra.output_raster = sAmenazaXPrecipitacion; pStepPro.Message = "Generando Amenaza Precipitacion..."; try { gp.Execute(mapAlgebra, null); } catch (Exception ex) { MessageBox.Show("Error Generando Amenaza x Precipitacion. " + ex.Message); pProDia.HideDialog(); return; } //if (bUsarSatelite) // Para la combinacion de la precipitacion x estaciones y satelite //{ // //CellStatistics cellStatisticsP = new CellStatistics(); // //cellStatisticsP.in_rasters_or_constants = sAmenazaXPrecipitacion + ";" + txtRutaPrecipitacion.Text; // //cellStatisticsP.out_raster = sAmenazaXPrecipitacionCombinada; // //cellStatisticsP.statistics_type = sTipoEstadistico; // try // { // gp.Execute(extractValPoint, null); // //sAmenazaXPrecipitacion = sAmenazaXPrecipitacionCombinada; // } // catch (Exception ex) // { // MessageBox.Show("Error generando estaciones virtuales con precipitacion." + ex.Message); // return; // } // Merge merge = new Merge(); // merge.inputs = //} DateTime date = sigpi.FechaProcesamiento; string sMonth = date.ToString("MM"); pStepPro.Step(); pStepPro.Message = "Generando Amenaza x Temperatura"; pFeatureClass = procesamiento.FCPrecipitacion(sTablaTemperaturaPromedio, pSpaRef); pDS = (IDataset)pFeatureClass; pDSName = (IDatasetName)pDS.FullName; pDSName2.Name = sFCTempPromedio; pDSName2.WorkspaceName = pWSName; try { pExportOp.ExportFeatureClass(pDSName, null, null, null, (IFeatureClassName)pDSName2, 0); } catch (Exception ex) { throw new Exception(ex.Message); } idw.in_point_features = sRutaFileGDB + "\\" + sFCTempPromedio; idw.out_raster = sAmenazaXTemperatura; try { gp.Execute(idw, null); } catch (Exception ex) { Console.WriteLine(ex.Message); } //if (bUsarSatelite) //{ // Geoprocessor gp1 = new Geoprocessor(); // Con pContmp = new Con(); // pContmp.in_conditional_raster = txtRutaTemperatura.Text; // pContmp.in_true_raster_or_constant = txtRutaTemperatura.Text; // pContmp.in_false_raster_or_constant = -99; // string sRasterTTemp = sAmenazaXTemperaturaCombinada + "_ajs"; // pContmp.out_raster = sRasterTTemp; // pContmp.where_clause = "VALUE < 55"; // try // { // gp1.Execute(pContmp, null); // } // catch (Exception) // { // sRasterTTemp = txtRutaTemperatura.Text; ; // } // gp1 = null; // CellStatistics cellStatistics = new CellStatistics(); // cellStatistics.in_rasters_or_constants = sAmenazaXTemperatura + ";" + sRasterTTemp; // cellStatistics.out_raster = sAmenazaXTemperaturaCombinada; // cellStatistics.statistics_type = sTipoEstadistico; // try // { // gp.Execute(cellStatistics, null); // sAmenazaXTemperatura = sAmenazaXTemperaturaCombinada; // } // catch (Exception) // { // } //} ReclassByTable rbt = new ReclassByTable(); rbt.in_raster = sAmenazaXPrecipitacion; rbt.in_remap_table = sTablaReclassPrecip; // parametros.RutaGBD + "\\" + sTablaReclassPrecip; rbt.from_value_field = sFromField; rbt.to_value_field = sToField; rbt.output_value_field = sOutField; rbt.missing_values = sNoData; rbt.out_raster = sAmenazaXPrecipReclass; //pStepPro.Message = "Generando Amenaza X Precipitacion Reclasificada"; try { gp.Execute(rbt, null); } catch (Exception ex) { MessageBox.Show(ex.Message); pProDia.HideDialog(); return; } rbt.in_raster = sAmenazaXTemperatura; rbt.in_remap_table = sTablaReclassTemp; // parametros.RutaGBD + "\\" + sTablaReclassTemp; rbt.out_raster = sAmenazaXTempReclass; //pStepPro.Message = "Generando Amenaza X Temperatura Reclasificada"; try { gp.Execute(rbt, null); } catch (Exception ex) { MessageBox.Show(ex.Message); pProDia.HideDialog(); return; } sExpression = "( Raster(r'" + sAmenazaXPrecipReclass + "') * " + dPesoPrecipitacion.ToString().Replace(",", ".") + ") + " + "( Raster(r'" + sAmenazaXTempReclass + "') * " + dPesoTemperatura.ToString().Replace(",", ".") + ") + " + "( Raster(r'" + sAmenazasParciales + "') * " + dPesoAmenazasParciales.ToString().Replace(",", ".") + ")"; //mapAlgebra.expression_string = sExpression; //mapAlgebra.out_raster = sAmenazaBruta; sExpression = sExpression.Replace("\\\\", "/").Replace("\\", "/"); mapAlgebra.expression = sExpression; mapAlgebra.output_raster = sAmenazaBruta; pStepPro.Message = "Generando Amenaza Final Bruta"; try { gp.Execute(mapAlgebra, null); } catch (Exception ex) { MessageBox.Show(ex.Message); } //if (txtRutaNVI.Text.Trim() != "") //{ Geoprocessor gp2 = new Geoprocessor(); mapAlgebra = new RasterCalculator(); sExpression = "Con (Raster(r'" + nvi + "') < 0.75, Raster(r'" + sAmenazaBruta + "'), Raster(r'" + sAmenazaBruta + "') -1)"; sExpression = sExpression.Replace("\\\\", "/").Replace("\\", "/"); mapAlgebra.expression = sExpression; mapAlgebra.output_raster = sAmenazaFinalBrutaNVI; try { gp2.Execute(mapAlgebra, null); } catch (Exception ex) { MessageBox.Show(ex.Message); } //} rbt.in_raster = sAmenazaFinalBrutaNVI; // sAmenazaBruta; rbt.in_remap_table = sTablaReclassIncendios; // parametros.RutaGBD + "\\" + sTablaReclassIncendios; rbt.from_value_field = sFromField; rbt.to_value_field = sToField; rbt.output_value_field = sOutField; rbt.missing_values = sNoData; rbt.out_raster = sAmenazaFinal; pStepPro.Message = "Generando Amenaza Final Reclasificada"; gp.AddOutputsToMap = true; try { gp.Execute(rbt, null); } catch (Exception ex) { MessageBox.Show(ex.Message); } Copy copy = new Copy(); copy.in_data = sAmenazaFinal; copy.out_data = sRutaGdbResultados + "\\" + sCapaResultado; try { gp.Execute(copy, null); } catch (Exception ex) { MessageBox.Show("Error Copiando el resultado. \n " + ex.Message); } MessageBox.Show("Algoritmo completo ejecutado: " + sRutaGdbResultados + "\\" + sCapaResultado); if (m_pApp != null) { IRasterLayer pRLayer = new RasterLayerClass(); try { IWorkspaceFactory pWF2 = new FileGDBWorkspaceFactoryClass(); IRasterWorkspaceEx pRW = (IRasterWorkspaceEx)pWF2.OpenFromFile(sRutaGdbResultados, 0); IRasterDataset pRDataset = pRW.OpenRasterDataset(sCapaResultado); pRLayer.CreateFromDataset(pRDataset); pRLayer.Name = sCapaResultado; IMxDocument pMxDoc = m_pApp.Document as IMxDocument; IMap pMap = pMxDoc.FocusMap; AsignarSimbologiaProbabilidad(pRLayer); pMap.AddLayer(pRLayer); if (pMap.LayerCount > 0) { pMap.MoveLayer(pRLayer, pMap.LayerCount - 1); } pMxDoc.UpdateContents(); pMxDoc.ActiveView.Refresh(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error cargando Capa!!!"); } } pProDia.HideDialog(); }