Wednesday, June 29, 2011

Silverlight Charting

Here is a great resource for developing Silverlight charts using the Silverlight Toolkit: http://cesso.org/Samples/ChartBuilder/

Thursday, June 23, 2011

Creating a PDF Document

One of the most interesting features with the mapping module in python is the ability to create a PDF document.  This feature can be used as the starting point of developing tools that can create map books.

The PDFDocument allows manipulation of PDF documents, including facilities for merging pages, setting document open behavior, adding file attachments, and creating or changing document security settings.  PDFDocumentOpen and PDFDocumentCreate are two functions that provide a reference to a PDFDocument object.

Example: Creating a Blank PDF Document

pdfPath = r"c:\temp\my.pdf"
pdfDoc = arcpy.mapping.PDFDocumentCreate(pdfPath)

#Commit changes and delete variable reference
pdfDoc.saveAndClose()
del pdfDoc

*Always call saveAndClose(), or the pdf will not appear on the file system.

Example: Opening a PDF Document and update properties

import arcpy
pdfDoc = arcpy.mapping.PDFDocumentOpen(r"C:\Project\ParcelAtlasMapBook.pdf")
pdfDoc.updateDocProperties(pdf_title="Atlas Map",
                           pdf_author="ESRI",
                           pdf_subject="Map Book",
                           pdf_keywords="Atlas; Map Books",
                           pdf_open_view="USE_THUMBS",
                           pdf_layout="SINGLE_PAGE")
pdfDoc.saveAndClose()
del pdfDoc


The mapping module in ArcPay allows for a host of properties to be updated as in the example above.

More examples and a full explanation of the object can be found here.

Wednesday, June 22, 2011

ArcPy's PictureElement Object

The PictureElement object provides access to properties that enable its reposition on the page layout as well as changing the images source.  Like previous posts, to get a reference to the PictureElement using the ListLayoutElements() which produces a list of page layout element objects.


Example: Changing the Datasource of a Picture Element

import arcpy
mxd = arcpy.mapping.MapDocument(r"C:\temp\Project.mxd")
for elm in arcpy.mapping.ListLayoutElements(mxd, "PICTURE_ELEMENT"):
   if elm.name == "Logo":
      elm.sourceImage = r"C:\temp\NewLogo.bmp"
mxd.save()
del mxd

Friday, June 17, 2011

AddIn Extension - Update Document Properties

A way to keep track of who accesses map documents is to create an extension that logs who last used the map document.  To do this, you need to wire events to the OpenDocument event.


        private void WireDocumentEvents()
        {
            // Named event handler
            ArcMap.Events.OpenDocument += new IDocumentEvents_OpenDocumentEventHandler(Events_OpenDocument);
         
        }

Call this event OnStartup(), so override it in the extension:

        protected override void OnStartup()
        {
            // Wire the events
             WireDocumentEvents();
        }

Next stub out the Events_OpenDocument()


        void Events_OpenDocument()
        {
            IMxDocument mxDoc = ArcMap.Document as IMxDocument;
            IDocumentInfo2 docInfo = mxDoc as IDocumentInfo2;
            docInfo.Comments += Environment.NewLine + "Opened On: " + DateTime.Now.ToString() + " by " + Environment.UserName;
            if (docInfo.RelativePaths == false)
            {
                docInfo.RelativePaths = true;
            }
        }

Now if you look at the Map Documents properties in ArcMap you'll see something like:
"Opened On: 06/17/2011 3:02 AM by Bob1234"

An additional option would be to tack in a Save() to save the document right away so the information doesn't get lost if the user exits ArcMap.


        private void Save()
        {
            ArcMap.Application.SaveDocument();
        }

Thursday, June 16, 2011

Using the TextElement Object

The TextElement Object provide access to properties that allows developers move and alter the text within a map document.  It changes text within a page layout and can be used on inserted text, call outs, rectangle text, titles, etc...  It is even dynamic enough to access grouped text elements. 

To find the TextElement on the page layout use the ListLayoutElement() with a filter of TEXT_ELEMENT for the type to return. 


import arcpy
from arcpy import mapping
mxd = mapping.MapDocument("CURRENT")
textElem = mapping.ListLayoutElements(mxd, "TEXT_ELEMENT")


Now a list of all TextElements are returned. The next step is to find the text element you want to change. Each TextElement has a property called 'name' and when you perform your cartographic duties, I strongly suggest you set this. It makes it easy to update the elements.


import arcpy
from arcpy import mapping
mxd = mapping.MapDocument("CURRENT")
textElem = mapping.ListLayoutElements(mxd, "TEXT_ELEMENT")
for elem in textElem:
   if elem.name == "txtTitle":
      elem.text = "Mr. Toads Wild Ride"
   elif elem.name == "txtCurrentDate":
      # make an element have dynamic text of current date
      elem.text = """<dyn format="short" type="date">"""

mxd.save()
del mxd


Now you might be thinking dynamic text, what the heck is that!?!? well it's exactly what it means, it's dynamic, it changes, and it's awesome. You can check out more here.

Wednesday, June 15, 2011

Advanced - Extending Search Cursor Object

The 'with' statement is used to wrap the execution of a block with functionality provided by a separate guard object.  The expression is evaluated once, and should yield a context guard, which is used to control execution of the suite. The guard can provide execution-specific data, which is assigned to the target (or target list). 

As a developer, think of a 'with' statement as a try/finally pattern

def opening(filename):
   f = open(filename)
   try:
      yield f
   finally:
      f.close()

This can now be viewed as:

with f = opening(filename):
   #...read data from f...

This makes writing code easier to understand, and you don't have to always remember to delete the object reference using the del().

How does this apply to the Cursor object? Well natively, the Cursor object does not support 'with' statement use. To extend the Cursor, more specifically SearchCursor, first create a class:

class custom_cursor(object):
   """
      Extension class of cursor to enable use of
      with statement
   """
   def __init__(self, cursor):
      self.cursor = cursor
   def __enter__(self):
      return self.cursor
   def __exit__(self, type, value, traceback):
      del self.cursor

Now you have an object called custom_cursor that has the minimum required class properties of __enter__() and __exit__(). Notice that __exit__() performs that annoying del() to remove the schema locks on our data.

How do you use this? It's not hard at all.  In this example, the function searchCursor() takes a feature class or table and a where clause (expression) and returns the results as an array of Row objects. 

def searchCursor(fc,expression=""):
   """
       Returns a collections of rows as an array of Row Objects
      :param fc: Feature Class or Table
      :param expression: Where Clause Statement (Optional)
      :rtype Rows: Array of Rows
  
   """
   rows = []
   with custom_cursor(arcpy.SearchCursor(fc,expression)) as cur:
      for row in cur:
         rows.append(row)
   return rows


The del() is taken care of automatically, and when the process is completed the __exit__() is called launching the del().

I got this idea from Sean Gillies Blog

Tuesday, June 14, 2011

The Legend Element

Continuing with the mapping module objects, leads me to start talking about cartography automation.  The LegendElement object allows developers to access properties that enables the altering of the legend on the page layout.  The LegendElement object has an association with a single data frame. 

Example: Add Layer to Legend

import arcpy
mxd = arcpy.mapping.MapDocument(r"C:\temp\BestMapEver.mxd")
df = arcpy.mapping.ListDataFrames(mxd)[0]
addLayer = r"c:\temp\World.lyr"
# Get the First Legend Object
#
legend = arcpy.mapping.ListLayoutElements(mxd, "LEGEND_ELEMENT", "Legend")[0]
legend.autoAdd = True
arcpy.mapping.AddLayer(df,addLayer,"BOTTOM")
mxd.save() # Now the map has the new layer which makes the map even better
del mxd


It's not too hard to do simple changing to map documents. All you need is a nice template to work off of, and you can alter the text, position and size of most map elements.