Example #1
0
        //根据层名,得到层的索引
        public System.Int32 GetIndexNumberFromLayerName(ESRI.ArcGIS.Carto.IActiveView activeView, System.String layerName)
        {
            if (activeView == null || layerName == null)
            {
                return(-1);
            }
            ESRI.ArcGIS.Carto.IMap map = activeView.FocusMap;

            // Get the number of layers
            int numberOfLayers = map.LayerCount;

            // Loop through the layers and get the correct layer index
            for (System.Int32 i = 0; i < numberOfLayers; i++)
            {
                if (layerName == map.get_Layer(i).Name)
                {
                    // Layer was found
                    return(i);
                }
                //map.get_Layer(i).Visible = false;
            }

            // No layer was found
            return(-1);
        }
Example #2
0
        //======================================================================================================

        #region 判断要素是否在同一图层以及图层的编辑状态
        //===================================================================================================
        //陈胜鹏  2009-08-19 添加
        /// <summary>
        /// 从图面上获取选中要素所在数据集的工作空间,判断是否开启编辑
        /// </summary>
        /// <param name="pMap">当前加载了数据的地图对象</param>
        /// <returns></returns>
        private bool GetDatasetEditState(ESRI.ArcGIS.Carto.IMap pMap)
        {
            int    pSameLyr = 0; //记录要素是否为同层
            ILayer pLayer   = null;

            //判断选择的要素是否处于同一个图层
            for (int i = 0; i < pMap.LayerCount; i++)
            {
                IFeatureLayer     pFeatLyr = null;
                IFeatureSelection pFeatSel = null;
                pLayer = pMap.get_Layer(i);
                if (pLayer is IGroupLayer)
                {
                    if (pLayer.Name == "示意图")
                    {
                        continue;
                    }
                    ICompositeLayer pComLayer = pLayer as ICompositeLayer;
                    for (int j = 0; j < pComLayer.Count; j++)
                    {
                        ILayer mLayer = pComLayer.get_Layer(j);
                        pFeatLyr = mLayer as IFeatureLayer;
                        if (pFeatLyr != null)
                        {
                            pFeatSel = pFeatLyr as IFeatureSelection;
                            if (pFeatSel.SelectionSet.Count > 0)
                            {
                                pSameLyr     = pSameLyr + 1;
                                m_MergeLayer = pFeatLyr;//当只有一个图层被选中时,pFeatLyr就是要进行融合的目标图层
                            }
                        }
                    }
                }

                pFeatLyr = pLayer as IFeatureLayer;
                if (pFeatLyr != null)
                {
                    pFeatSel = pFeatLyr as IFeatureSelection;
                    if (pFeatSel.SelectionSet.Count > 0)
                    {
                        pSameLyr     = pSameLyr + 1;
                        m_MergeLayer = pFeatLyr;//当只有一个图层被选中时,pFeatLyr就是要进行融合的目标图层
                    }
                }
            }
            //如果选择的要素所在的层数不是1,即要素不在同一个层
            if (pSameLyr != 1)
            {
                return(false);
            }

            //一系列的QI后获得IWorkspaceEdit接口对象pWSE
            IFeatureClass  pFeatCls = m_MergeLayer.FeatureClass as IFeatureClass;
            IDataset       pDS      = pFeatCls as IDataset;
            IWorkspace     pWs      = pDS.Workspace as IWorkspace;
            IWorkspaceEdit pWSE     = pWs as IWorkspaceEdit;

            return(pWSE.IsBeingEdited());  //返回编辑状态
        }
        public bool ConvertLayerToKML(IFeatureClass fc, string kmzOutputPath, string tmpShapefilePath, ESRI.ArcGIS.Carto.IMap map)
        {
            try
            {
                string kmzName    = System.IO.Path.GetFileName(kmzOutputPath);
                string folderName = System.IO.Path.GetDirectoryName(kmzOutputPath);
                var    fcName     = System.IO.Path.GetFileNameWithoutExtension(kmzName);

                IFeatureLayer fLayer = new FeatureLayer();
                fLayer.FeatureClass = fc;
                var geoLayer = (fLayer as IGeoFeatureLayer);
                if (geoLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPoint)
                {
                    ISimpleMarkerSymbol pSimpleMarkerSymbol = new SimpleMarkerSymbolClass();
                    pSimpleMarkerSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle;
                    pSimpleMarkerSymbol.Size  = CoordinateConversionLibrary.Constants.SymbolSize;
                    pSimpleMarkerSymbol.Color = new RgbColorClass()
                    {
                        Red = 255
                    };
                    ISimpleRenderer pSimpleRenderer;
                    pSimpleRenderer        = new SimpleRenderer();
                    pSimpleRenderer.Symbol = (ISymbol)pSimpleMarkerSymbol;
                    geoLayer.Name          = fcName;
                    geoLayer.Renderer      = (IFeatureRenderer)pSimpleRenderer;
                }
                var featureLayer = geoLayer as FeatureLayer;

                map.AddLayer(geoLayer);

                // Initialize the geoprocessor.
                IGeoProcessor2 gp         = new GeoProcessorClass();
                IVariantArray  parameters = new VarArrayClass();
                parameters.Add(featureLayer.Name);
                parameters.Add(folderName + "\\" + kmzName);
                var result = gp.Execute(CoordinateConversionLibrary.Constants.LayerToKMLGPTool, parameters, null);

                // Remove the temporary layer from the TOC
                for (int i = 0; i < map.LayerCount; i++)
                {
                    ILayer layer = map.get_Layer(i);
                    if (layer.Name == fcName)
                    {
                        map.DeleteLayer(layer);
                        break;
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }

            return(false);
        }
Example #4
0
        public bool ConvertLayerToKML(string kmzOutputPath, string tmpShapefilePath,
                                      ESRI.ArcGIS.Carto.IMap map, GraphicTypes graphicType)
        {
            try
            {
                string kmzName = System.IO.Path.GetFileName(kmzOutputPath);

                IGeoProcessor2 gp = new GeoProcessorClass();
                gp.OverwriteOutput = true;
                IGeoFeatureLayer geoLayer = null;

                IVariantArray parameters = new VarArrayClass();
                parameters.Add(tmpShapefilePath);
                parameters.Add(kmzName);
                gp.Execute("MakeFeatureLayer_management", parameters, null);

                string layerFileName = getLayerFileFromGraphicType(graphicType);
                if (!string.IsNullOrEmpty(layerFileName))
                {
                    IVariantArray parametersASM = new VarArrayClass();
                    parametersASM.Add(kmzName);
                    parametersASM.Add(layerFileName);
                    gp.Execute("ApplySymbologyFromLayer_management", parametersASM, null);
                }

                IVariantArray parameters1 = new VarArrayClass();
                // assign  parameters
                parameters1.Add(kmzName);
                parameters1.Add(kmzOutputPath);

                gp.Execute("LayerToKML_conversion", parameters1, null);

                // Remove the temporary layer from the TOC
                for (int i = 0; i < map.LayerCount; i++)
                {
                    ILayer layer = map.get_Layer(i);
                    if ((layer.Name == "featureLayer") || (layer.Name == kmzName))
                    {
                        map.DeleteLayer(layer);
                        break;
                    }
                }
                if (geoLayer != null)
                {
                    map.DeleteLayer(geoLayer);
                }

                return(true);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                return(false);
            }
        }
Example #5
0
 /// <summary>
 /// 根据图层索引获得图层
 /// </summary>
 /// <param name="activeView">当前视图窗口对象</param>
 /// <param name="layerIndex">图层序号</param>
 /// <returns></returns>
 public ESRI.ArcGIS.Carto.IFeatureLayer GetFeatureLayerFromLayerIndexNumber(ESRI.ArcGIS.Carto.IActiveView activeView, System.Int32 layerIndex)
 {
     if (activeView == null || layerIndex < 0)
     {
         return(null);
     }
     ESRI.ArcGIS.Carto.IMap map = activeView.FocusMap;
     if (layerIndex < map.LayerCount && map.get_Layer(layerIndex) is ESRI.ArcGIS.Carto.IFeatureLayer)
     {
         return((ESRI.ArcGIS.Carto.IFeatureLayer)activeView.FocusMap.get_Layer(layerIndex)); // Explicit Cast
     }
     else
     {
         return(null);
     }
 }
Example #6
0
        /// <summary>
        /// 根据图层索引获得图层
        /// </summary>
        /// <param name="activeView">当前视图窗口对象</param>
        /// <param name="layerIndex">图层序号</param>
        /// <returns></returns>
        public ESRI.ArcGIS.Carto.IFeatureLayer GetFeatureLayerFromLayerName(ESRI.ArcGIS.Carto.IActiveView activeView, System.String name)
        {
            if (activeView == null || name == "")
            {
                return(null);
            }
            IFeatureLayer fealyr = null;

            ESRI.ArcGIS.Carto.IMap map = activeView.FocusMap;
            for (int i = 0; i < map.LayerCount; i++)
            {
                ICompositeLayer lyrs = map.get_Layer(i) as ICompositeLayer;
                if (lyrs == null)
                {
                    continue;
                }
                for (int j = 0; j < lyrs.Count; j++)
                {
                    ILayer          lyr          = lyrs.get_Layer(j);
                    ICompositeLayer compositrlyr = lyr as ICompositeLayer;
                    if (compositrlyr != null)
                    {
                        for (int k = 0; k < compositrlyr.Count; k++)
                        {
                            ILayer lyr1 = compositrlyr.get_Layer(k);
                            if (lyr1.Name == name)
                            {
                                fealyr = lyr1 as IFeatureLayer;
                                break;
                            }
                        }
                    }
                    else
                    {
                        if (lyr.Name == name)
                        {
                            fealyr = lyr as IFeatureLayer;
                            break;
                        }
                    }
                }
            }
            return(fealyr);
        }
        public bool ConvertLayerToKML(string kmzOutputPath, string tmpShapefilePath, ESRI.ArcGIS.Carto.IMap map)
        {
            try
            {
                string kmzName    = System.IO.Path.GetFileName(kmzOutputPath);
                string folderName = System.IO.Path.GetDirectoryName(kmzOutputPath);

                IGeoProcessor2 gp         = new GeoProcessorClass();
                IVariantArray  parameters = new VarArrayClass();
                parameters.Add(tmpShapefilePath);
                parameters.Add(kmzName);
                gp.Execute("MakeFeatureLayer_management", parameters, null);

                IVariantArray parameters1 = new VarArrayClass();
                // assign  parameters
                parameters1.Add(kmzName);
                parameters1.Add(kmzOutputPath);

                gp.Execute("LayerToKML_conversion", parameters1, null);

                // Remove the temporary layer from the TOC
                for (int i = 0; i < map.LayerCount; i++)
                {
                    ILayer layer = map.get_Layer(i);
                    if (layer.Name == "featureLayer")
                    {
                        map.DeleteLayer(layer);
                        break;
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Example #8
0
        //创建饼状专题图
        public static void CreatePieTheme(System.Web.UI.Page page, int nLayerID, string[] fields)
        {
            if (page == null)
            {
                return;
            }
            // 得到地图服务下的ArcObjects map对象
            ESRI.ArcGIS.Server.IServerContext pServerContext = GetServerContext(page);

            ESRI.ArcGIS.Carto.IMapServer         mapServer        = (ESRI.ArcGIS.Carto.IMapServer)pServerContext.ServerObject;
            ESRI.ArcGIS.Carto.IMapServerObjects2 mapServerObjects = (ESRI.ArcGIS.Carto.IMapServerObjects2)mapServer;
            string mapName = mapServer.DefaultMapName;

            ESRI.ArcGIS.Carto.IMap aoMap = mapServerObjects.get_Map(mapName);

            ESRI.ArcGIS.Carto.ILayer           pLayer    = aoMap.get_Layer(nLayerID);//得到图层
            ESRI.ArcGIS.Carto.IGeoFeatureLayer pGeoLayer = pLayer as IGeoFeatureLayer;

            //设置专题图的属性列表
            ESRI.ArcGIS.Carto.IChartRenderer  pCharRenderer = pServerContext.CreateObject("esriCarto.ChartRenderer") as IChartRenderer;
            ESRI.ArcGIS.Carto.IRendererFields pRenderFields = pCharRenderer as IRendererFields;
            foreach (string var in fields)
            {
                pRenderFields.AddField(var, var);
            }

            //实例化图表对象并取得元素指定属性的最大值
            ESRI.ArcGIS.Display.IPieChartSymbol pPieSym  = pServerContext.CreateObject("esriDisplay.PieChartSymbol") as ESRI.ArcGIS.Display.IPieChartSymbol;
            ESRI.ArcGIS.Display.IChartSymbol    pCharSym = pPieSym as ESRI.ArcGIS.Display.IChartSymbol;
            pPieSym.Clockwise  = true;
            pPieSym.UseOutline = true;

            pCharSym.MaxValue = GetStaMaxMin(fields, pGeoLayer)[0];

            //设置饼图外围线
            ISimpleLineSymbol pOutLine = pServerContext.CreateObject("esriDisplay.SimpleLineSymbol") as ISimpleLineSymbol;

            pOutLine.Color = GetRGB(255, 0, 128, pServerContext);
            pOutLine.Style = ESRI.ArcGIS.Display.esriSimpleLineStyle.esriSLSSolid;
            pOutLine.Width = 1;

            pPieSym.Outline = pOutLine;
            IMarkerSymbol pMarkSym = pPieSym as IMarkerSymbol;

            pMarkSym.Size = 5;


            //设置饼状图填充效果
            ESRI.ArcGIS.Display.ISymbolArray pSymArr = pPieSym as ISymbolArray;
            ISimpleFillSymbol pSimFillSym            = pServerContext.CreateObject("esriDisplay.SimpleFillSymbol") as ESRI.ArcGIS.Display.SimpleFillSymbol;

            pSimFillSym.Color   = GetRGB(128, 128, 128, pServerContext);
            pSimFillSym.Outline = pOutLine;

            Random randColor = new Random();

            for (int i = 0; i < fields.Length; i++)
            {
                IFillSymbol pFillSym = pServerContext.CreateObject("esriDisplay.SimpleFillSymbol") as IFillSymbol;
                pFillSym.Color = GetRGB(randColor.Next(255), randColor.Next(255), randColor.Next(255), pServerContext);
                pSymArr.AddSymbol((ISymbol)pFillSym);
            }

            //设置地图图层背景
            pSimFillSym              = pServerContext.CreateObject("esriDisplay.SimpleFillSymbol") as ESRI.ArcGIS.Display.SimpleFillSymbol;
            pSimFillSym.Color        = GetRGB(255, 128, 255, pServerContext);
            pCharRenderer.BaseSymbol = pSimFillSym as ISymbol;


            //设置饼状图表属性
            IPieChartRenderer pPieChartRenderer = pCharRenderer as IPieChartRenderer;

            pPieChartRenderer.MinValue             = 0.1;
            pPieChartRenderer.MinSize              = 1;
            pPieChartRenderer.FlanneryCompensation = false;
            pPieChartRenderer.ProportionalBySum    = true;
            pPieChartRenderer.ProportionalField    = fields[0];
            pCharRenderer.ChartSymbol              = pPieSym as IChartSymbol;
            pCharRenderer.Label = "面积";

            //应用饼状专题到指定图层
            pCharRenderer.UseOverposter = false;
            pCharRenderer.CreateLegend();
            pGeoLayer.Renderer = pCharRenderer as IFeatureRenderer;

            //刷新地图显示图表及图例
            mapServerObjects.RefreshServerObjects();
            // Map1.RefreshResource("MapResourceItem0");
            pServerContext.ReleaseContext();
        }
Example #9
0
        public void execute()
        {
            // check if the status is ready (all the attributes have been set and parent is known
            // execute and return the features and set them to _features
            // compare the features with what is expected in parent.  If it matches, transfer the values to the parent and set the paramNode to be complete.
            ESRI.ArcGIS.Carto.IMap         map     = null;
            ESRI.ArcGIS.Carto.IMapDocument tempDoc = new ESRI.ArcGIS.Carto.MapDocument();
            string filePath = this.sourceName;

            ESRI.ArcGIS.Carto.IMapDocument mapDoc = new ESRI.ArcGIS.Carto.MapDocument();
            if (mapDoc.get_IsPresent(filePath) && !mapDoc.get_IsPasswordProtected(filePath))
            {
                mapDoc.Open(filePath, string.Empty);
                // set the first map as the active view
                map = mapDoc.get_Map(0);
                for (int i = 0; i < map.LayerCount; i++)
                {
                    IFeatureLayer layer = map.get_Layer(i) as IFeatureLayer;
                    Console.WriteLine("layer=====" + layer.Name);
                    if (layer.Name == this.sourceLayer)
                    {
                        layer.Selectable = true;
                        IQueryFilter queryFilter = new QueryFilterClass();

                        // queryFilter.WhereClause = this.query;
                        queryFilter.WhereClause = "ZONE_ = 'A'";

                        IFeatureSelection pFeatureSelection = layer as IFeatureSelection;
                        pFeatureSelection.SelectFeatures(queryFilter, esriSelectionResultEnum.esriSelectionResultNew, false);

                        //pFeatureSelection.SelectionSet.
                        if (pFeatureSelection.SelectionSet.Count == 0)
                        {
                            Console.WriteLine("No features found for" + this.query);
                        }
                        else
                        {
                            //for (int j = 0; j < pFeatureSelection.SelectionSet.Count; j++)
                            //{
                            //    IFeature f = (pFeatureSelection as IFeatureLayer).FeatureClass.GetFeature(j);
                            //    this.parent.Values.Add(f);
                            //}

                            IFeatureClass featureClass = layer.FeatureClass;
                            //use an IEnumIDs to read the SelectionSet IDs
                            IEnumIDs enumIDs     = pFeatureSelection.SelectionSet.IDs;
                            int      fieldIndex1 = featureClass.FindField("SHAPE_Length");
                            int      fieldIndex2 = featureClass.FindField("SHAPE_Area");
                            string   s           = "{0}ID \t\tSHAPE_Length \t\tSHAPE_Area";
                            IFeature feature;
                            IDataset dataset = (IDataset)featureClass;

                            int iD = enumIDs.Next();
                            while (iD != -1) //-1 is reutned after the last valid ID has been reached
                            {
                                feature = featureClass.GetFeature(iD);
                                s      += "{0}" + iD + ":\t\t" + feature.get_Value(fieldIndex1) + "\t\t" + feature.get_Value(fieldIndex2);
                                iD      = enumIDs.Next();
                            }

                            //report some information about the selection
                            // we need to store this result back to the VALUES of the Parent's node, which is a ParamNode.
                            Console.WriteLine("A SelectionSet containing: {1} Rows {0}has been created using the query: {2} {0}this selection set was created on the feature class: {3}{0}" + s + "{0}",
                                              Environment.NewLine, pFeatureSelection.SelectionSet.Count, queryFilter.WhereClause, dataset.Name);
                        }
                    }
                }
            }
        }
Example #10
0
        //创建柱状专题图
        public void CreateBarRenderer(int layerID, string[] fields)
        {
            // 得到地图服务下的ArcObjects map对象
            ESRI.ArcGIS.Server.IServerContext pServerContext = GetServerContext();

            ESRI.ArcGIS.Carto.IMapServer         mapServer        = (ESRI.ArcGIS.Carto.IMapServer)pServerContext.ServerObject;
            ESRI.ArcGIS.Carto.IMapServerObjects2 mapServerObjects = (ESRI.ArcGIS.Carto.IMapServerObjects2)mapServer;
            string mapName = mapServer.DefaultMapName;

            ESRI.ArcGIS.Carto.IMap aoMap = mapServerObjects.get_Map(mapName);

            ESRI.ArcGIS.Carto.ILayer           pLayer    = aoMap.get_Layer(layerID);//得到图层
            ESRI.ArcGIS.Carto.IGeoFeatureLayer pGeoLayer = pLayer as IGeoFeatureLayer;
            //设置专题图元素的属性名称列表
            IChartRenderer  pChartRender  = pServerContext.CreateObject("esriCarto.ChartRenderer") as IChartRenderer;
            IRendererFields pRenderFields = pChartRender as IRendererFields;

            foreach (string var in fields)
            {
                pRenderFields.AddField(var, var);
            }

            //实例化图表对象并取得元素指定属性的最大值
            IBarChartSymbol pBarChartSymbol = pServerContext.CreateObject("esriDisplay.BarChartSymbol") as IBarChartSymbol;
            IChartSymbol    pChartSymbol    = pBarChartSymbol as IChartSymbol;

            pChartSymbol.MaxValue = GetStaMaxMin(fields, pGeoLayer)[0];
            pBarChartSymbol.Width = 8;
            IMarkerSymbol pMarkerSymbol = pBarChartSymbol as IMarkerSymbol;

            pMarkerSymbol.Size = 50;

            //设置柱状图每列填充效果
            ISymbolArray pSymbolArray = pBarChartSymbol as ISymbolArray;
            Random       ranColor     = new Random();

            for (int i = 0; i < fields.Length; i++)
            {
                IFillSymbol pFillSymbol = pServerContext.CreateObject("esriDisplay.SimpleFillSymbol") as IFillSymbol;
                pFillSymbol.Color = GetRGB(ranColor.Next(255), ranColor.Next(255), ranColor.Next(255), pServerContext);
                pSymbolArray.AddSymbol((ISymbol)pFillSymbol);
            }

            //设置地图图层背景
            ESRI.ArcGIS.Display.ISimpleFillSymbol pFSymbol = pServerContext.CreateObject("esriDisplay.SimpleFillSymbol") as ESRI.ArcGIS.Display.SimpleFillSymbol;
            pFSymbol.Color          = GetRGB(239, 228, 249, pServerContext);
            pChartRender.BaseSymbol = pFSymbol as ISymbol;

            //应用柱状专题到指定图层
            pChartRender.ChartSymbol   = pBarChartSymbol as IChartSymbol;
            pChartRender.Label         = "Test";
            pChartRender.UseOverposter = false;
            pChartRender.CreateLegend();
            pGeoLayer.Renderer = pChartRender as IFeatureRenderer;

            //刷新地图显示图表及图例
            mapServerObjects.RefreshServerObjects();
            Map1.RefreshResource("MapResourceItem0");
            Toc1.BuddyControl = "Map1";
            //Toc1.Refresh();
            Map1.Refresh();
            pServerContext.ReleaseContext();
        }
Example #11
0
        protected override void OnClick()
        {
            // Get the min/max zoom from user input
            int minzoom = 0;
            int maxzoom = 6;

            Ecotrust.Form1 form1 = new Ecotrust.Form1();
            if (form1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                minzoom = (int)form1.numericUpDown1.Value;
                maxzoom = (int)form1.numericUpDown2.Value;
            }
            else
            {
                return; //TODO
            }

            // Use the FolderBrowserDialog Class to choose export folder
            System.Windows.Forms.FolderBrowserDialog folderDialog = new System.Windows.Forms.FolderBrowserDialog();
            folderDialog.Description = "Select output folder for map tiles...";
            string exportDir = "";

            if (folderDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                // The returned string will be the full path, filename and file-extension for the chosen shapefile. Example: "C:\test\cities.shp"
                exportDir = folderDialog.SelectedPath;
                if (exportDir == "")
                {
                    return;  // TODO raise error
                }
            }
            else
            {
                return; //TODO
            }

            ESRI.ArcGIS.ArcMapUI.IMxDocument mxDocument = ArcMap.Application.Document as ESRI.ArcGIS.ArcMapUI.IMxDocument; // Dynamic Cast
            ESRI.ArcGIS.Carto.IActiveView    activeView = mxDocument.ActiveView;
            ESRI.ArcGIS.Carto.IMap           map        = activeView.FocusMap;

            ESRI.ArcGIS.Geometry.IEnvelope mapaoi = activeView.Extent;

            // Set up export object and tile pixel coordinates
            int tileSizeX = 256;
            int tileSizeY = 256;

            // set up exporter with transparent background
            ESRI.ArcGIS.Output.IExportPNG pngexport = new ESRI.ArcGIS.Output.ExportPNGClass();
            ESRI.ArcGIS.Display.IColor    tcolor    = new ESRI.ArcGIS.Display.RgbColorClass();
            // Warning: 254,254,254 will be set to transparent; don't use in any of map styling
            ((IRgbColor)tcolor).Red   = 254;
            ((IRgbColor)tcolor).Green = 254;
            ((IRgbColor)tcolor).Blue  = 254;
            ((ExportPNG)pngexport).BackgroundColor = tcolor;
            pngexport.TransparentColor             = tcolor;
            ESRI.ArcGIS.Output.IExport export = (ESRI.ArcGIS.Output.IExport)pngexport;

            ESRI.ArcGIS.esriSystem.tagRECT exportRECT;
            exportRECT.left   = 0;
            exportRECT.top    = 0;
            exportRECT.right  = tileSizeX;
            exportRECT.bottom = tileSizeY;
            ESRI.ArcGIS.Geometry.IEnvelope envelope = new ESRI.ArcGIS.Geometry.EnvelopeClass();
            envelope.PutCoords(exportRECT.left, exportRECT.top, exportRECT.right, exportRECT.bottom);
            export.PixelBounds = envelope;

            map.DelayDrawing(true);

            // Turn off all layers
            for (int i = 0; i < map.LayerCount; i++)
            {
                map.get_Layer(i).Visible = false;
            }

            // Calculate total number of tiles needed
            GlobalMercator mercator = new GlobalMercator();

            GlobalMercator.Coords tempmins;
            GlobalMercator.Coords tempmaxs;
            Double numTiles = 0;

            for (int tz = minzoom; tz <= maxzoom; tz++)
            {
                tempmins  = mercator.MetersToTile(mapaoi.XMin, mapaoi.YMin, tz);
                tempmaxs  = mercator.MetersToTile(mapaoi.XMax, mapaoi.YMax, tz);
                numTiles += ((tempmaxs.y - tempmins.y) + 1) * ((tempmaxs.x - tempmins.x) + 1);
            }
            numTiles *= map.LayerCount;

            ESRI.ArcGIS.esriSystem.IStatusBar statusBar = ArcMap.Application.StatusBar;
            statusBar.set_Message(0, "Rendering " + numTiles.ToString() + " tiles");

            // Create a CancelTracker
            ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass();

            ESRI.ArcGIS.Framework.IProgressDialogFactory progressDialogFactory = new ESRI.ArcGIS.Framework.ProgressDialogFactoryClass();

            // Set the properties of the Step Progressor
            System.Int32 int32_hWnd = ArcMap.Application.hWnd;
            ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd);
            stepProgressor.MinRange  = 0;
            stepProgressor.MaxRange  = (int)numTiles;
            stepProgressor.StepValue = 1;
            stepProgressor.Message   = "Calculating " + numTiles.ToString() + " tiles";

            // Create the ProgressDialog. This automatically displays the dialog
            ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog2 = (ESRI.ArcGIS.Framework.IProgressDialog2)stepProgressor; // Explict Cast

            // Set the properties of the ProgressDialog
            progressDialog2.CancelEnabled = true;
            progressDialog2.Description   = "Rendering " + numTiles.ToString() + " map tiles";
            progressDialog2.Title         = "Creating map tiles...";
            progressDialog2.Animation     = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriDownloadFile;
            System.Boolean boolean_Continue = true;

            int tileCount = 0;

            for (int lyrnum = 0; lyrnum < map.LayerCount; lyrnum++)
            {
                // Turn on the layer of interest
                ESRI.ArcGIS.Carto.ILayer layer = map.get_Layer(lyrnum);
                layer.Visible = true;

                // Set extents
                //ESRI.ArcGIS.Geometry.IEnvelope layeraoi = layer.AreaOfInterest;
                ESRI.ArcGIS.Geometry.IEnvelope aoi = new ESRI.ArcGIS.Geometry.EnvelopeClass();

                // Create layer directory if it doesn't exist
                DirectoryInfo dir = new DirectoryInfo(exportDir + "\\" + layer.Name);
                if (!dir.Exists)
                {
                    dir.Create();
                }

                DateTime startTime = DateTime.Now;

                // Loop through zoom levels, rows, cols
                for (int tz = minzoom; tz <= maxzoom; tz++)
                {
                    GlobalMercator.Coords mins = mercator.MetersToTile(mapaoi.XMin, mapaoi.YMin, tz);
                    GlobalMercator.Coords maxs = mercator.MetersToTile(mapaoi.XMax, mapaoi.YMax, tz);

                    // Create zoom directory if it doesn't exist
                    DirectoryInfo dir2 = new DirectoryInfo(dir.FullName + "\\" + tz);
                    if (!dir2.Exists)
                    {
                        dir2.Create();
                    }

                    for (int tx = (int)mins.x; tx <= (int)maxs.x; tx++)
                    {
                        // Create X directory if it doesn't exist
                        DirectoryInfo dir3 = new DirectoryInfo(dir2.FullName + "\\" + tx);
                        if (!dir3.Exists)
                        {
                            dir3.Create();
                        }

                        for (int ty = (int)mins.y; ty <= (int)maxs.y; ty++)
                        {
                            // Flip y-axis for output tile name
                            int invertTy = (int)((Math.Pow(2, tz) - 1) - ty);

                            tileCount += 1;

                            // TODO Calculate time and set new message
                            // TimeSpan timeElapsed = TimeSpan.FromTicks(DateTime.Now.Subtract(startTime).Ticks); // * ((double)tileCount - (numTiles + 1)) / (numTiles + 1));
                            // double timeRemaining = (timeElapsed.TotalSeconds / (tileCount / numTiles)) - timeElapsed.TotalSeconds;
                            //(" + ((int)timeRemaining).ToString() +" remaining)";

                            stepProgressor.Message = layer.Name + "\\" + tz + "\\" + tx + "\\" + invertTy +
                                                     ".png (" + tileCount + " of " + numTiles + ")";


                            export.ExportFileName = dir3.FullName + "\\" + invertTy + ".png";

                            GlobalMercator.Bounds bnd = mercator.TileBounds(tx, ty, tz);
                            aoi.PutCoords(bnd.minx, bnd.miny, bnd.maxx, bnd.maxy);
                            aoi.SpatialReference = map.SpatialReference; // TODO aoi spatial reference == mercator?
                            // Use FullExtent instead of Extent to make the extent independent of the activeView ratio
                            activeView.FullExtent = aoi;

                            // Export
                            System.Int32 hDC = export.StartExporting();
                            activeView.Output(hDC, (System.Int16)export.Resolution, ref exportRECT, null, null); // Explicit Cast and 'ref' keyword needed
                            export.FinishExporting();
                            export.Cleanup();

                            stepProgressor.Position = tileCount;

                            //Check if the cancel button was pressed. If so, break out of row
                            boolean_Continue = trackCancel.Continue();
                            if (!boolean_Continue)
                            {
                                break;
                            }
                        }
                        //Check if the cancel button was pressed. If so, break out of col
                        boolean_Continue = trackCancel.Continue();
                        if (!boolean_Continue)
                        {
                            break;
                        }
                    }
                    //Check if the cancel button was pressed. If so, break out of layers
                    boolean_Continue = trackCancel.Continue();
                    if (!boolean_Continue)
                    {
                        break;
                    }

                    // Write log
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(exportDir + "\\log.txt", true))
                    {
                        file.WriteLine(layer.Name + ", zoom " + tz + ", numtiles " + tileCount + ":" +
                                       mins.x + " " + mins.y + " " + maxs.x + " " + maxs.y);
                    }
                }
                // Turn it off
                layer.Visible = false;
            }

            map.DelayDrawing(false);

            // Turn ON all layers
            for (int i = 0; i < map.LayerCount; i++)
            {
                map.get_Layer(i).Visible = true;
            }

            // restore extent
            activeView.FullExtent = mapaoi;
            activeView.Refresh();

            // Done
            trackCancel    = null;
            stepProgressor = null;
            progressDialog2.HideDialog();
            progressDialog2 = null;
        }