A python primer for arcgis pdf

 

    A Python Primer for the GIS Professional. • What is a script? Why automate a task ? • What is Python? What can Python do? Why use it? • What is ArcPy?. University of Pennsylvania. • ESRI Conference Workshop: Python. Essentials in ArcGIS-I. • LinuxWorld Tutorial: Introduction to. Python by Guido van. Python Scripting for ArcGIS. Nathan Jennings is experienced in GIS, Remote Sensing, GPS, GIS for web, geospatial technology, consulting, and business systems integration. This book is a poor, poor choice for anyone wanting to learn Python scripting in an ArcGIS environment, or any.

    Author:JOELLE CRACOLICI
    Language:English, Spanish, Japanese
    Country:China
    Genre:Health & Fitness
    Pages:716
    Published (Last):10.11.2015
    ISBN:431-2-52403-857-5
    Distribution:Free* [*Registration Required]
    Uploaded by: LASHELL

    47127 downloads 113722 Views 17.83MB PDF Size Report


    A Python Primer For Arcgis Pdf

    Examples, Python and ArcGIS, Python versions. • Fundamentals of geoprocessing in ArcGIS. • Python language fundamentals. – Where to run Python code. Demonstrate how to build a Python script that uses ArcMap tools Manual process (e.g. following documentation/tutorial). • Difficult to share. Using ArcGIS and Python. Nick Santos, Josh Viers, and Anna Fryjoff-Hung. Feb University Extension. Contact: [email protected]

    This YouTube series was super helpful for me, personally. The videos are short, and I just watched them all in one evening on 2x speed to get a flavor of how ArcPy works didn't bother with doing any exercises, just watched the videos. It is a decent to good intro and was certainly helpful for me, but definitely lacks depth and advanced topics. From my own experience, you cannot strictly learn the arcpy site package without eventually bringing in larger concepts from the Python programming language. In fact, I first tried to take the approach you are eluding to, where I began using the arcpy site package to automate processes in ArcGIS. However, I quickly found myself paging through Python documentation looking for better approaches to, for example, manipulate paths such as with os. In sum I would recommend the following steps to learn Python fundamentals complimented by the arcpy site package: First: use an IDE such as PythonWin or PyScripter to do all of your scripting! It takes too many people too long to realize that they can implement and debug scripts outside of the ArcGIS python window. Perform even the most simple tasks using Python. For example, define a workspace and create a geodatabase programmatically. Don't start out creating complicated scripts. It's okay to do all of your scripting using arcpy initially--just keep in mind there are better, more efficient methods for many tasks. Always look for a better alternative with pure Python, if necessary. Find programmatic solutions to inquiries on this site.

    This is not possible within the scripting environment, and therefore, The MapDocument object is usually one of the first object references created in a a saveAs method is not provided. The MapDocument class map automation script because it is a required parameter for many of has save and saveACopy methods for managing modifications to a map the arcpy. It is through the MapDocument object that you document.

    The executed line of code. To refresh the map document to reflect the changes, use object also contains methods for managing map document thumbnails and either the RefreshActiveView or RefreshTOC functions.

    These functions will methods for saving map documents that are found within the ArcMap File menu. The There are two different ways that a MapDocument object can be created using refresh functions are only needed if you want to see the application updated. The first, and most recommended, method is to Arcpy. This updated results without using these functions. Referencing a specific map document on disk provides more control in because the user and password information is not saved within the layer file or terms of how the script will execute because a given script may not work on all map document.

    Map documents that contain these layers will prompt the user to map documents. This technique only works from within an ArcMap during execution, but that means that the layers will be treated as though they application because the MapDocument object references the map document that have broken data sources. In other words, secured layers will not be rendered in is currently loaded into the ArcMap application. If it is necessary for these layers to render appropriately, then there when quickly testing and learning the scripting capabilities and command syntax are a couple of options.

    First, save the user name and password information with within the Python window. You may start off learning the syntax in the Python the layers. Second, the CreateArcSDEConnectionFile geoprocessing function window, then start pasting those lines of code into a more permanent script saved allows you to create a connection that persists in memory. If this command is used to disk. Currently, there is from a custom menu or the Catalog window.

    For this same The variable that references the MapDocument object will place a lock on the map reason, if a script tool has a validation script that includes a reference to CURRENT, document file. It is good practice to remove the Map Document object reference an error may occur if you try to edit the validation script from ArcCatalog.

    There are disabled. Background processing runs all scripts as though they were being run as two methods on the MapDocument object that help with this. There is a all of a layer's or table's workspace path. For more dateExported Returns a Python datetime object that reports the date the DateTime detailed discussion, parameter information, scenarios, and code samples, please last time the map document was exported.

    This value is only Read Only current if the map document was saved after the map was refer to the Updating and fixing data sources with arcpy. The activeDataFrameproperty will return the Read and Write Read Only appropriate data frame even if the map document is in page layout view. The Read and Write property works with a string that represents the active data pageSize Provides the ability to get the layout's page size.

    If activeView is a map document's page width and height. Read and Write deleteThumbnail tags String This performs the same operation as clicking the Delete Thumbnail button on Provides the ability to either get or set the map document's tag information.

    Separate tags with a single comma ,. If an empty string is passed, then all workspace paths will be replaced with deleteThumbnail Deletes a map document's. If it is not valid, the workspace will not be image replaced. In this case, if a match does not document. The default value is True save Saves a map document. If it Type is not valid, the workspace will not be replaced. In you want to find.

    If an empty string is passed, then all this case, if a match does not exist, then the data sources would workspace paths will be replaced with be broken. If an empty string is passed, multiple samples, please refer to the Updating and Fixing Data Sources with workspaces can be redirected into one workspace.

    The default value will use the current version. This sample will update the first data frame's name and document. The output map documents will be saved in data view mode so when refresh the table of contents so the change can be see in the application. Paste each map document is opened, the corresponding data frame will be active data the following code into the Python window within a new ArcMap document.

    The script also sets the title property of each output map document. ListDataFrames mxd [0]. Python strings cannot end with a backslash, arcpy. RefreshTOC even when the string is preceded by an r. You must use a double backslash. This del mxd becomes important when appending dynamic file names to a folder path. You must press the Enter key to execute these lines.

    MapDocument example 3 MapDocument example 4 The following is another simple script that demonstrates the use of The following script will allow secured layers to render correctly by creating an the CURRENT keyword within the Python window. Each layer name will be printed SDE connection in memory before opening a map document that requires to the Python window. Loops are also possible, provided that you maintain the password information.

    This script simply defines the connection information and correct indentation. Similar to the example above, paste the code below into the exports the map document to a PDF file. It is good practice to delete this reference Python window. When pasted into the interactive window it will appear as follows. Again, press the os. Summary Read and Write Provides access to properties that enables its repositioning on the page layout as parentDataFrameName A string that represents the name of the DataFrame for the String well as identifying its parent data frame.

    Read Only Discussion A MapsurroundElement object is a page element that has an association with a type String Returns the element type for any given page layout data frame.

    For example, there is a one-to-one relationship between a north arrow element. Read Only and a data frame. A Code Sample wildcard can also be used to further refine the search based on the element name.

    MapsurroundElement example It is recommended that each page layout element be given a unique name so that The following script will find the mapsurround element named ScaleBar and it can be easily isolated using arcpy scripting.

    X and Y element positions are change it's position. ListDataFrames mxd, scaleBar. Read and Write elementWidth Double The width of the element in page units. PDFDocument arcpy. Allows manipulation of PDF documents, including facilities for merging pages, For more discussion on how to create map books, see the Building Map Books deleting pages, setting document open behavior, adding file attachments, and with ArcGIS help topic. If a PDFDocument object is passed, the method will fail.

    It is also required that PDF import arcpy, os security be the same for all documents that are being appended, inserted, or attached. It may take a long time to process dozens of pages. If only a Create the file and append pages relative few have been modified, it is faster to delete only those pages, then insert the newly updated pages using the insertPages method. However, no PDF file will be created until subsequent steps are performed to insert or append pages and save the PDF file. A common scenario for using this function is the creation of a PDF map book.

    For example, if the document that is being appended to does an existing PDF document. If a Parameter Explanation Type script exits before saveAndClose is executed, changes will not be saved. Ranges can also be applied for example, "1, 3, ". Data Parameter Explanation It is important to keep track of the pages that are being deleted, because each Type time pages are deleted, the internal PDF page numbers are automatically adjusted.

    If page 1 and page 2 are deleted, page 3 becomes page 1. You need to consider this if you are using deletePages and then immediately The default value is None using appendPages or insertPages. A string that includes the location and name of the input PDF document to be inserted. The default value is None encryption String import arcpy, os A string that defines the encryption technique used on the PDF.

    The permissions argument can accept a pdfDoc. The pdfDoc. The master password is required to make this change to a will open. Note how we insert the new page 3 before the current page 3 which was really page 4 before the original page PDFDocument example 3 3 was removed. The same applies to the range of pages 5—7. The following script will set the user password to esri, encrypt the PDF import arcpy using RC4 compression, and require a password when the document is opened.

    Discussion elementHeight Double The height of the element in page units. The units assigned or The PictureElement object represents a raster or image that has been inserted reported are in page units. Read and Write into the page layout. The ListLayoutElements function returns a Python list of page layout element objects. It is necessary to then iterate through each item in the list elementPositionX Double The x location of the data frame element's anchor position.

    Lesson 1: Introduction to GIS modeling and Python

    The or specify an index number to reference a specific page element object. To return units assigned or reported are in page units. A wild card can also be used to further refine the elementPositionY Double search based on the element name. The y location of the data frame element's anchor position. It is recommended that each page layout element be given a unique name so that Read and Write it can be easily isolated in Python. X,Y element positions are based on the element's anchor position, which is set using the Size and Position tab on elementWidth Double The width of the element in page units.

    The units assigned or the Elements Properties dialog box in ArcMap. Read and Write The PictureElement object has a sourceImage property that allows you to read or modify the picture source location. If you plan on replacing a picture with name String The name of the element.

    When a picture is replaced using the sourceImage property and has a different aspect ratio, it will be fit to the area sourceImage String A text string that represents the path to the image data source. Replaced pictures will never be Read and Write larger than the original authored size. You will also want to set the anchor position so that all new pictures are fit relative to that location. If you don't want pictures to type String Returns the element type for any given page layout element.

    There is a different location. The pictures are named Photo1. The first value in The RasterClassifiedSymbology class provides access to different the classBreakValues list is the minimum value; all other values are the class properties that allow you to change the appearance of a layer's raster classified break values as they appear in the ArcMap use interface.

    For this reason, symbology. Discussion Setting one parameter will often modify other parameters automatically. For The RasterClassifiedSymbology class provides access to a limited number example, if you set numClasses, normalization, or of properties and methods that allow you to automate layer symbology in a map the valueField parameters, the classBreakValues, classBreakLabels, document.

    Basic operations, such as changing the andclassBreakDescriptions properties will automatically be adjusted based number of classes, modifying class break values and labels, or changing the field on the current classification method.

    For this reason, the order in which properties that the symbology is based on, are some of the properties that can be modified. For access to the complete set of layer symbology properties and settings, for example, changing individual symbols for individual classes, it is necessary to The reclassify method updates a layer's symbology properties based on the author these changes in the ArcMap user interface and then save those changes underlying source data.

    It is useful when a layer's symbology is updated using to a layer file.

    These custom settings can then be applied to existing layers using the UpdateLayer function with symbology stored in another layer or layer file the UpdateLayer function. For example, let's say you want to update the color properties of the symbology of a layer in a map document with the symbology stored in a layer file.

    A layer can use any number of symbologies but not all of them can be modified. However, the layer in the map document and the layer file have different data Not all layers will use the RasterClassifiedSymbology class, so it is sources. The minimum and maximum values and class breaks in the layer file may important to first test if the layer is using this symbology class before attempting to be different than the layer in the map document.

    Updating the symbology of the make changes to its properties. The symbologyType property on the Layer class layer in the map document with the symbology stored in the layer file may produce was designed for this purpose. First test if the symbologyType for the layer is unintended results for example, the class break values will match the layer file's raster classified if lyr.

    In other words, source data. You can only change the properties for a specific symbology class on If you are making these symbology modifications via the Python Window and you a layer. The only way to change the symbology type is by publishing the desired are referencing a map document using CURRENT, you may not immediately see result to a layer file and using the UpdateLayer function.

    The classification method cannot be changed. In cases where you want to use different classification methods, you would need to preauthor layer files and use those to update a layer, then modify the properties that can be changed.

    This value cannot be set if the classification method is manual; Data therefore, numClasses should not be called after Property Explanation Type the classBreakValues property because it will automatically set the classification method to manual. Changing this value will automatically adjust other symbology classBreakDescriptions A sorted list of strings that represent the descriptions for each List properties based on the new information.

    These values are only accessible in the valueField String A string that represents a valid dataset field name used for the ArcMap user interface by right-clicking a symbol displayed layer's classification symbology.

    Changing this value will within the Symbologytab in the Layer Properties dialog box Read and Write automatically adjust other symbology properties based on the and selecting Edit Description.

    The number of descriptions in new information. This is because the classBreakValues list also includes a minimum value which you don't see in the user interface. These values are Method Overview affected by changes to nearly all other class properties, so it is Method Explanation best practice to set these values last. The number of labels in the sorted list Resets the layer's symbology to the layer's data source information and statistics.

    Read and Write must always be one less than the number of classBreakValues. This is because the classBreakValues list also includes a minimum value Methods which you don't see in the user interface.

    These values are affected by changes to nearly all other class properties, so it is reclassify best practice to set these values last. When underlying source data. It is useful when a layer's symbology is updated using Read and Write settingclassBreakValues, it will automatically set the UpdateLayer function with symbology stored in another layer or layer file the numClasses property and will also set the classification.

    This method will automatically update the symbology properties based on method to manual as well as update other properties such as classBreakLabels. Unlike the ArcMap user interface, the layer's actual data source information and statistics and not the information you have the ability to set a minimum value. The first value in that is persisted in a layer file.

    The method needs to be used cautiously because it the sorted list represents the minimum value, and the has the potential to overwrite other symbology properties. It will not ns lists. Changing this value will automatically adjust other affectnumClasses or normalization. The reclassify method has no affect symbology properties based on the new information. For example 1; 3; Read and Write ; and 8. The values are removed from the classification, and therefore, will not be displayed.

    The following script modifies the symbology for a layer in the current map It first updates the layer's symbology using a layer file on disk with document. It first verifies that the layer has raster classified symbology. Finally, it the UpdateLayer function. The layer file contains a custom color ramp that is modifies a number of the properties on theRasterClassifiedSymbology class applied to the layer.

    Next, it verifies that the layer has raster classified symbology. The script then calls the reclassify method. This method will update the Since this sample uses the CURRENT keyword to access the map document, it symbology properties based on the layer's actual data source information and must be executed from within ArcMap.

    This is because the MapDocument object statistics and not the information that is persisted in a layer file. Finally, the result references the map document that is currently loaded into the ArcMap application. For more information regarding accessing map documents, see import arcpy the MapDocument class help topic. ListLayers mxd, "lakene. ListDataFrames mxd, "Lakes" [0] arcpy.

    RefreshActiveView arcpy. A layer is added to the first data frame in the map Provides access to StyleItem class properties. The symbols you choose to display features, elements, or graphics in your map are stored in style files. You use the Style Manager dialog box to create, view, and modify styles and their contents. ListDataFrames mxd [0] folder name. In the user interface, when you add a new layer to the table to contents, and that feature is automatically added to the legend, a default style is applied.

    This can be accomplished using the del mxd following workflow.

    Read Only itemCategory A string that represents the category of the item the way it appears in String the Style Manager dialog box window. Categories are used to group Read Only symbols within a style. Identifying Read Only thestyleFolderName allows you to determine the type of the style object you have referenced. TableView arcpy. Returns the name of the table's dataset the way it appears in the workspace, not in the table of contents.

    Discussion Read Only The TableView object is essential for managing stand-alone tables that reside dataSource Returns table's data source path. It includes String within a map document. It provides access to basic table properties such the workspacePath and the datasetName combined.

    The TableView constructor function allows you to reference a table outside of a Read and Write map document within a workspace. This provides the ability to add an external table into a map document using the AddTableView function.

    This function is name String Provides the ability to set or get the name of a table the way it would similar to MakeTableView, but the difference is that the result from appear in the ArcMap table of contents. Spaces can be included.

    MakeTableView can't be added permanently into a map document. It is isBroken Returns True if a table's data source is broken. Boolean necessary to then iterate through each item in the list or specify an index number to reference a specific TableView object. Tables can be searched within an Read Only entire map document or within a specific data frame.

    Wildcards can also be used to limit the search. A definition query will not work for all workspaces. For more information on updating Method Explanation workspaces and data sources in a map document or layer file, please refer to the Updating and Fixing Data Sources with arcpy.

    In this case, if a match does not exist, then the table's data source would be broken. The default value is True For more detailed discussion, parameter information, scenarios, and code samples, please refer to the Updating and Fixing Data Sources help topic. Code Sample TableView example 2 TableView example 1 The following script will reference a table in a file geodatabase and then add that The following script will find a table called Customers in a data frame table into the referenced map document.

    ListTableViews mxd, "", df: TableView r"C: AddTableView df, accidentsTable mxd. Double repositioning on the page layout as well as modifying the text string and font size. This elementHeight Double The height of the element in page units. The units assigned or includes items such as inserted text, callouts, rectangle text, titles, and so on. It reported are in page units. Read and Write also includes text strings that have been grouped into a group element. It does not include text strings that are part of a legend or inserted table.

    It is necessary to then iterate through each item in the list or specify an Read and Write index number to reference a specific page element object.

    A wildcard can also be used to further refine the units assigned or reported are in page units. Read and Write search based on the element name. Existing text elements can be cloned and deleted. This capability was initially elementWidth Double added to support the creation of dynamic graphic tables. To accomplish this, a The width of the element in page units.

    If column field names have different text property settings than the cell values, then at least two text elements need to be authored. As the information is fontSize Double The element font size in page units. When cloning an element it is very useful to provide a suffix value so that cloned elements can be easily name String identified while using the ListLayoutElements function with a wildcard and the The name of the element.

    The returned list of elements can be further modified or Read and Write deleted using the delete method.

    Arcgis Books

    The TextElement is also unique from most other page elements in that it has type String Returns the element type for any given page layout element. It is with this property that strings can be read and modified.

    X and Y element positions are based on the element's anchor position, which is set via theSize and Position tab on the element's properties dialog box in ArcMap. The String new element will get the same element name as the parent text element plus the suffix value plus a numeric sequencer. Grouped text elements can't be cloned. All grouped elements are graphic element types. First check to see if a graphic element is grouped by using the isGroup property on the GraphicElement object.

    Cloned elements, when created, can be given a custom suffix so they can be easy to find when using the wildcard parameter on the ListLayoutElements function. TextElement example 2 TextElement example 3 The following script will update a static 9. It string to now incorporate the new version 10 dynamic text strings. Current time is essentially sets the initial font size to points and reduces the font size until the appended as a new line below the current date.

    The text string is set using a text string fits the desired width. The text string is set up as dynamic text that couple of different Python techniques.

    All produce the same result. This script will only run properly if you set the title property of the map document.

    Use triple quotes and put the line break within the string. RefreshActiveView del mxd mxd. The UniqueValuesSymbology class provides access to different properties that allow you to change the appearance of a layer's unique value symbology.

    Properties Data Property Explanation Discussion Type The UniqueValuesSymbology class provides access to a limited number of properties and methods that allow you to automate layer symbology in a map classDescriptions A list of strings or numbers that represent the descriptions for List each unique value that can optionally appear in a map document's document.

    Basic operations such as modifying class Read and Write legend. These values are only accessible in the ArcMap user values and labels, or changing the field that the symbology is based on are some interface by right-clicking a symbol displayed within of the properties that can be modified.

    For access to the complete set of layer the Symbology tab in the Layer Properties dialog box and symbology properties and settings, for example, changing individual symbols for selecting Edit Description.

    The classDescriptions list needs to have the same number of elements and arranged in the individual classes, it is necessary to author these changes in the ArcMap user same order as the classValues property. These custom settings can classLabels A list of strings or numbers that represent the labels for each List then be applied to existing layers using the UpdateLayer function.

    The classDescriptions list needs to Not all layers will use the UniqueValuesSymbology class, so it is important to have the same number of elements and built in the same order as the classValues property. If this property is not set, its values first test if the layer is using this symbology class before attempting to make will be the same as classValues. The symbologyType property on the Layer class was classValues A list of strings or numbers that represent the class breaks.

    List designed for this purpose. First test if the symbololgyType for the layer is Changing this property will automatically adjust other unique unique values if lyr. It is good practice to always set this value before create a variable reference to the UniqueValuesSymbology class for that layer settingclassDescriptions and classLabels. The symbologyType on the Layer object is a read-only property. In other words, Read and Write you can't change a unique values symbology to a graduated colors or graduated symbols symbology.

    You can only change the properties for a specific symbology valueField String A string that represents a valid dataset field name used for the class on a layer. The only way to change the symbology type is by publishing the Read and Write layer's unique value symbology.

    Changing this value will desired result to a layer file and using the UpdateLayer function. The valueField is used to change the field the unique values are based on. After setting the new field it makes sense to immediately call the addAllValues method so that an updated list of classes is automatically Method Overview generated.

    Similar to the user interface, calling addAllValues will automatically Method Explanation sort the classes in accending order. If you want to change the order, then use the classValues and classLabels properties. The addAllValues method is also useful for situations where data is addAllValues Adds all unique values to the symbology. Layers symbolized using unique values in a map document don't dynamically update when data is changed.

    TheaddAllValues method provides a mechanism to automate this process. Methods UniqueValuesSymbology example 2 addAllValues The following script will update a layer's unique value symbology class list based The addAllValues method updates a layer's symbology so that all values are on the results of an attribute query.

    This method is useful when unique values are added to a layer after the symbology has been authored in ArcMap. Calling the addAllValues method will insert those new values into the list of import arcpy existing values.

    ListLayers mxd, "Population" [0] Code Sample arcpy. Next, the addAllValues is used to update the class list. MapDocument "current" if lyr. ListLayers mxd, "Population" [0] lyr. RefreshTOC arcpy. This Layer Discussion reference can point to a layer file on disk or a layer within a map AddLayer is an easy way to add a layer or group layer into a map document.

    It document. The layer that is added must reference an already existing layer keep in mind that a layer can be a group layer as well. The source can either come from a layer file on disk, from within the same map document and data frame, the same map document but different data frame, or even from a completely separate map document. The way a layer appears in the table of contents TOC after it is added depends on the source layer and how it appears.

    For example, some layers are completely collapsed and do not display their symbol s in the TOC. This setting is built into the layer. If a layer is collasped, saved to a layer file, and then added to a map document, the layer will be collasped in the new map document when added via AddLayer.

    Code Sample AddLayer example 2: AddLayer example 1: ListDataFrames mxd2, "Layers" [0] mxd. It can add a layer with auto-arrange logic that places the new layer in a layer will be added. It must be a group layer. This reference can point to a layer file on disk or a layer based on layer weight rules and geometry type. The other placement layer in a map document. AddLayerToGroup does not allow you to add layers to group layers within a layer file.

    Layer files should be managed and authored using ArcMap. The source can either come from a layer file on disk, from within the same map document and data frame, the same map document but different data frame, or even from a completely separate map Code Sample document. AddLayerToGroup example: The way a layer appears in the table of contents TOC after it is added depends The following script will add a new layer from a layer.

    For example, some layers are completely it at the bottom of a group layer called Scale Data in a data frame collapsed and do not display their symbol s in the TOC. This setting is built into called County Maps. If a layer is collasped, saved to a layer file, and then added to a map document, the layer will be collasped in the new map document when added import arcpy via AddLayerToGroup.

    Discussion AddTableView provides a way to add a table into a map document. A reference import arcpy to a TableView object must exist first. DataFrame arcpy. TableView del mxd This reference can point to a table within an existing map document or it can reference a table in a workspace via the TableView function. AnalyzeForMSD arcpy. Starting at ArcGIS Please use the AnalyzeForSD function instead. Analyzes map documents.

    See the following help topics for more information: What to expect when migrating to ArcGIS Consider using the AnalyzeForSD function instead.

    For more information, see Top the overview of the Publishing toolset. Syntax Discussion AnalyzeForSD sddraft An important task that you can perform is analyzing your Service Definition Draft file to identify errors and other potential issues that you may need to address Data Parameter Explanation before you can create a Service Definition file.

    This function returns a Python dictionary containing errors, warnings and messages. Analysis for a map Service Definition Draft file is based on many factors including the data used by the map; map, layer, and symbol properties; set service properties such as chosen capabilities and associated properties the service will support; and the server type hosting the service. You will see three types of messages in the Python dictionary: Errors for a map Service Definition Draft file typically refer to your map's use of map layer types or display options that are not supported for map services.

    All errors must be repaired before you can create a Service Definition file. Warnings and other messages identify issues that may affect drawing performance and appearance.

    Warnings alert you to issues in which drawing performance or drawing appearance may be affected, but these issues do not preclude you from converting the Service Definition Draft file to a Service Definition file. Staging compiles all the necessary information needed to successfully publish the GIS resource. If you have chosen to copy data to the server, the data will be added when the Service Definition Draft is staged. AnalyzeForSD r"C: AnalyzeForSD sddraft print " applies to: Execute StageService arcpy.

    Automating the publishing of map services can be if the sddraft analysis contained errors, display them accomplished by using a combination of arcpy. The workflow begins with a map document that you want to publish.

    First, use the arcpy. Next, you should analyze the service definition draft for issues that could prevent you from publishing successfully by using the AnalyzeForSD function. After analyzing the service definition draft and addressing serious issues, it is time to stage the service definition. Staging takes the service definition draft and consolidates all the information needed to publish the service into a complete service definition.

    ConvertToMSD arcpy. MapDocument with Service Definition Draft. If more DataFrame Discussion than one data frame exists, it is important to specify which data frame will be the active data frame for the Starting at ArcGIS The default value is the active data with Service Definition Draft. See frame. This option takes the longest to render.

    Each individual font has parameters created within it by the font author that defines which sizes the font should draw with antialiasing. Top Summary Note: The map document can be further modified before finally being printed The PrintingTools service can be used in a web application to generate a high- or exported.

    For more information regarding the Discussion PrintingTools service, see the following: The ConvertWebMapToMapDocument function will convert a web map that you Printing in web applications intend to print or export to a map document. Once the document is converted, the Once you have a Python script that prepares the map for printing, you can full state of the web map exists in the map document.

    The map document can encapsulate it in a geoprocessing script tool. You can then publish the script tool then be further modified before finally being printed or exported to a common as an ArcGIS Server geoprocessing service.

    Some example workflows that can be met using For more information on geoprocessing services, see the following: What is a geoprocessing service? This is commonly desired when a vector output is wanted instead of service layers. One way to accomplish swapping service layers for vector data would be to stage template map documents that contain vector equivalents of all the possible service layers. After executing the ConvertWebMapToMapDocument function, loop through all the layers in the output map document, removing all layers except the vector layers that correspond to the service layers in the web map.

    This workflow would be used when swapping your own services with the corresponding vector data that you already have. For example, the ExportToPDF function has parameters for controlling raster and vector compression, defining colorspace, embedding fonts, and so on. When using ConvertWebMapToMapDocument in a geoprocessing service in the be required for your script to run successfully. A sample string is below: The extension of the file depends on "url": The following strings are accepted: The ability "version": However, before the script can be published and used in the web APIs, it has to be run locally.

    Any valid web map JSON string can be used when running the script locally. However, the line breaks must be uses ConvertWebMapToMapDocument in a geoprocessing service, you need to removed for the string to be valid input. For more information on registering data, see the following: When authoring template map documents in the registered folder, it is best ,"xmax": That way, ArcGIS for Server will be able to find the data in the registered folder relative to the location of the map documents.

    See Referencing data in the map for more information. For example, the script doesn't look for web map layers by name. If the Caution: Therefore, it is good practice to ensure the script If you choose to not use registered folders, template map documents and data works locally before publishing by testing with a valid web map JSON string or will be packaged and copied to the server.

    During packaging, data may be moved using a debug map document that contains all the elements that would be in the and re-sourced with relative paths to a folder structure web map JSON. For this reason, usage of registered folders is recommended.

    In addition to creating your own template map documents, you can also use the Tip: For example, if the JSON has stored in an in-memory workspace. For more information, see the layoutOptions section use the Consolidate Map or Package Map geoprocessing tools to make a copy of in ExportWebMap specification.

    See code example 2 below. If the web map does not contain notes overlays, you can use the saveACopy method from the MapDocument class to make a permanent copy of the output map document. See the removeItem method on the LegendElement class to remove legend items. This below demonstrates this workflow. See the updateItem method on parameter is required if the services in the web map the LegendElement class and the ListStyleItems method to update legend items.

    JSON require a user name and password to view. Keys accepted in the dictionary are as follows: Be sure to read the following tutorials. Basic web map printing and exporting using arcpy. Advanced web map printing and exporting using arcpy. For use connection where graphic features should be written. For use from the web map JSON need to be preserved when performing a data view export. In most cases, this parameter is not required, as a temporary in-memory workspace will be Caution: This parameter allows you to save graphic features to persistent storage, ConvertWebMapToMapDocument will create temporary map documents which is essential if you plan to use the map document.

    On Windows Vista and 7, this is located for operations that require saving or loading from disk at C: It is the user's for example, packaging or consolidating. The path responsibility to manage the map documents in this folder.

    To delete these temporary must end with a. GetParameterAsText 1 pdfDoc. After executing arcpy. Input Layout template if not lyr. GetParameterAsText 2 and not lyr. After executing if not vlyr. The data view of the output map document is then exported to PNG using the DPI, output height, and Get a list of all vector layers that don't have a corresponding output width values returned from the ConvertWebMapToMapDocument function, service layer as specified in the web app.

    Input web map json if not lyr. GetParameterAsText 0 and not lyr. ListDataFrames mxd, 'Webmap' [0] Export the web map Get a list of all service layer names in the map arcpy. DPI if slyr. The page range is then exported to a multipage PDF document.

    If String Related functions: By default, they are staged in a folder on your Syntax local machine. String connection file. The output file extension must end with.

    Servers node in the Catalog window. This step takes the Service Definition file, copies it onto the server, Summary extracts required information, and publishes the GIS resource. For more information, see the overview of the Publishing toolset.

    Converts Map Document. Once the. The output created from properties for services that have caching enabled. A Service Server Cache Scales tool can be used to add new scales or delete existing scales Definition Draft is the combination of a Map Document, information about the from a cache. Modify SDDraft example 7 demonstrates this.

    The tiling scheme can server, and a set of service properties. However, due to the complexity published to, the type of service being published, metadata for the service Item of the tiling scheme XML structure, it is recommended to use the Caching toolset info , and data references whether or not data is being copied to the server.

    Also included are any additional capabilities of the service, such as Desktop main menu. For more chosen capability. This method initially uses a set of default service properties. Moreover, ArcGIS, see the following topics: A draft service alone cannot be actions you do with your server. For example, stop and start services, edit used to publish a service. Similar to the AnalyzeForSD function, CreateMapSDDraft also returns a Python properties of services, such as the maximum number of instances, grant and revoke user permissions on services, and so on.

    For more information about the types You can also create Service Definition Draft files for geoprocessing, image, and of errors, warnings and information messages, and how to access them, geocoding services. See the following related functions: A server connection can be provided later when the Service Definition Draft is published using the Upload Service Definition tool.

    Spatial Data Server services Parameter Explanation Data Type always use registered data and will therefore never copy data to the server. A string that represents a folder name to which you want The name can only contain alphanumeric characters and to publish the service definition. If the folder does not underscores. No spaces or special characters are allowed. The default folder is the The name cannot be more than characters in length.

    If A string that represents the Item Description Summary. Use this parameter to override the user interface parameter entirely. Use this parameter to override the user interface tags, or to provide tags if they do not exist. If Returns a Python Dictionary of information messages, warnings, and errors. Automating the publishing of map services can if the sddraft analysis contained errors, display them be accomplished by using a combination of arcpy.

    Note that the Item Description, Summary, and Tags for the input map document are overwritten using the summary and tags parameters. Next, you CreateMapSDDraft example 2 should analyze the service definition draft for issues that could prevent you from The following sample script creates a Service Definition Draft.

    After analyzing the service definition draft and addressing a Map Document. It then prints the Python Dictionary of errors, warnings, serious issues, it is time to stage the service definition. The definition draft and consolidates all the information needed to publish the service analysis information contained in the Python dictionary helps to identify potential into a complete service definition. Use the Stage Service geoprocessing tool to performance bottlenecks and map errors that you may need to address before you stage the service definition.

    Finally, use the Upload Service can create a Service Definition. This script also demonstrates how to Definition geoprocessing tool to upload the service definition to the server and create a Service Definition Draft without specifying the server connection publish the map service.

    MapDocument 'C: The modified Service Definition Draft. Finally, the new. AnalyzeForSD outXml for key in 'messages', 'warnings', 'errors': We have to drill down to the The following sample script creates a Service Definition Draft. Title property by modifying the. The modified. Reference map document for CreateSDDraft function. Read the sddraft xml. Find all elements named TypeName. It then disables KmlServer capabilities by modifying the.

    The Analyze the new sddraft for errors. Create service and sddraft variables for CreateSDDraft function. This is where the server object extension SOE names are defined.

    Get the TypeName we want to disable. Disabled SOE. AnalyzeForSD outXml import arcpy import xml. It then turn on caching in the configuration properties enables caching on the service by modifying the. Next, the new. Use the Stage Service geoprocessing tool to stage the for propSet in propSets: Once the for keyValue in keyValues: Scales geoprocessing tool which updates the scale levels in an existing cached if keyValue.

    Free GIS Programming Tutorials: Learn How to Code - GIS Geography

    Use this tool to add new scales or delete existing scales turn on caching from a cache. MapDocument os. MapServer' print " applies to: StageService and UploadServiceDefinition aborted. For example, an organization may want to push Update,Delete,Uploads,Editing capabilities. The first two code updates to keep synchronized with the daily changes made by itsArcGIS for pieces handle overwriting an existing service.

    The last three pieces Desktop users. This sample script will demonstrate how to: You can customize the capabilities by removing items. Note you cannot disable Query from a Feature Service. Update the variables with your path to the MXD file.

    The script will create if tagType. You can modify this value to a path on your if typeName. If the sddraft analysis contained errors, display them and quit. Stage the service arcpy. In this case, the feature service will be shared to everyone on ArcGIS.

    Please consult the ArcGIS documentation for the usage of the 'password': For example, the inclusion of the port number, , may not be required. Check your web adaptor configuration to if you need a token, execute this line: This is the name people will see and use to identify the service. The name can only contain alphanumeric characters and underscores. The name cannot be more than characters in length. For example, in the user interface, it is Summary not possible to process only the selected set of records and only those in the Exports a formatted, tabular report using data from layers or stand-alone tables in visible extent.

    The same rule applies to the ExportReport function; only one a map document along with the report template information that is provided in a parameter can be set at a time. If more than one of these parameters is set, they report layout file. An The ExportReport function provides a mechanism to automate the generation example is provided below. A report layout file authored in ArcMap is a pages. This can be a continuous group of pages or even a discontinuous template that stores information about the content and placement of the items in a set of pages 3,7.

    In these cases, when you generate a report and report. The source data can also have associated joins and what you've entered Page 3, Page 7. This was designed for scenarios where related table information that is used within the report.

    If the scenario requires that the output page numbers be continuous, for example Page 1, Page 2 , then you must set The ExportReport function has a dependency on the ArcMap installation. This means that ExportReport will need installed. ExportReport will not run using stand-alone installations of ArcGIS to be executed once for each page.

    The source data must exist in a map document. A report layout file can be used with file. If fields are dropped from the field map dictionary, those names. If the data is similar but the data source field names are different, then fields will be dropped from the report. It is possible to use arcpy. Pictures in a report have a property called Source Image.

    It may be does not have access to this value but if the source image value is pointing to a necessary to author a collection of specific templates for generating and exporting path on disk, arcpy. In a Data The reporting tools in the ArcMap user interface have a button called Dataset Driven Pages example, you could change the picture based on the current extent, options.

    This allows the author to choose only one of four ways in which records for example, with arcpy. An example is will be processed: Object ry which rows will be exported to the output report. This value will overwrite any layout file. The specified file extension controls the output format.

    This value will override When anextent object is passed into this parameter, the the Dataset Optionsvalue stored in the report layout file rows will be based on those features that intersect the extent.

    If the data source. Code Sample ExportReport example 2 ExportReport example 1 The following script extends the example above to demonstrate how to combine a The following script will export a report to a PDF file using the layer's selected spatial selection and an attribute selection to generate the desired report. This is the way to go for developing your own web mapping applications.

    Starting with the basics, HTML is the markup language that gives structure to web pages like headings, tables and lists. While CSS stylizes webpages with layouts, it also provides color, fonts and size.

    Your biggest hurdle is JavaScript. If you really want to make your webpage dynamic, then take a look at JavaScript. Because JavaScript is run in a browser, it manipulates the behavior of your web-based content. In addition, the Dojo toolkit provides language utilities and UI components. Again, the assumption is starting at zero.

    Put your knowledge to action with a project of your own. For example, create your own personal web map project by starting simple. Rich web maps often use open-source JavaScript libraries like Leaflet. JavaScript libraries are code someone else has written to make life easier for the rest of us. This is the same how Python modules are distributed. For example, JQuery, three. When you use Leaflet, you can build your own web map from this JavaScript library.

    You can do almost anything with JavaScript from spatial analysis to robust basemap servers. Test your knowledge with a more complex web map project. For example, make a web map with at least 2 toggleable layers.

    A big part of GIS is database entry, editing and maintenance. For example, SQL queries, inputs and deletions all fine-tune your data. Joins, relates and further SQL knowledge is greatly valued in the field. When given a database, explore the data models within it. Understand the structure of the database.

    This database design structure are often represented in UML diagrams. Most design work for data models use it. Come up with a project and practice using your new SQL skills. If an employer asks for a portfolio, you have some good examples to share.

    This is because R can visualize and analyze spatial data. It places emphasis on statistics, but it can do both. And for this reason, R is often recommended:.