TitlePages

Showing posts with label python addin. Show all posts
Showing posts with label python addin. Show all posts

Wednesday, 24 December 2014

ArcGIS Python Mapping Module


Arc Python to interact with Arc-map

What is ArcPy Mapping and Why is it actually used for :

Arcpy.mapping was built for the professional GIS analyst (as well as for developers). Traditionally, the scenarios listed above had to be done using ArcObjects and it often proved to be a very difficult programming environment to learn for the average GIS professional. Arcpy.mapping is a courser-grained object model, meaning that the functions are designed in a way that a single arcpy.mapping function can replace many lines of ArcObjects code. The following is a very simple example of how arcpy.mapping can be used to reference an existing map document and export it to a PDF document with only two lines of code.

To explore the Overall Arcpy mapping Module use the following PDF:

Arcpy Python Mapping Module


Code for Getting the reference to the MXD :

YourMXD= arcpy.mapping.MapDocument("path to the MXD")

To export the above MXD to PDF using arcpy:

arcpy.mapping.ExportToPdf(YourMXD,"your pdf file")



Get Reference to the Current Arcmap
Pointer to a MXD present on the Disk


Map Layout Document in the Arc map
Layout View of the Map Document

Arcpy.mapping is not a replacement for ArcObjects but rather an alternative for the different scenarios it supports. ArcObjects is still necessary for finer-grain development and application customization, whereas arcpy.mapping is intended for automating the contents of existing map documents and layer files.



Creating Geodatabases using Arcpy or Model builder

Creating Geo-databases in Arc Map

What is a Geodatabase:
  • A geodatabase is the common data storage and management framework for all the ArcGIS Products. It combines Geo (spatial data) with Database (data repository) to create a central data repository for all the spatial data storage and management in your ArcGIS platform.
  • It can be leveraged in desktop, server, or mobile environments and allows you to store GIS data in a central location for easy access and management.
The geodatabase offers you the ability to
  • Store a rich collection of spatial data in a centralized location.
  • Apply sophisticated rules and relationships to the data.
  • Define advanced geospatial relational models (e.g., topologies, networks).
  • Maintain integrity of spatial data with a consistent, accurate database.
  • Work within a multiuser access and editing environment.
  • Integrate spatial data with other IT databases.
  • Easily scale your storage solution.
  • Support custom features and behavior.
  • Leverage your spatial data to its full potential.
Arc-map geodatabase can be created using various way:
  1. Manually creating through Arc-Catalog
  2. Using the Model workflow to create it Programmatic-ally
  3. Using the Python integrated to Create Geodatabase Programmatic
  1. Model for Creating Feature Class
Model to create Geodatabase in ArcGIS
Set the workspace and OutputFC as the Model parameter

AddField will add a column to the newly created Feature class and can be populated with the user defined values

The Search, Insert or Update cursor can be used to manipulate the values present in the new Feature class

For achieving the above functionality it is advised to write a python code using the arcpy library.

To know more detailed step by step information about the creating a feature class in the Geodatabase
Click here - Create Geodatabase Feature Class - PDF




Arcpy Improvements in 10.1

Arc Python in ArcGIS 10.1

  1. Site package that adds ArcGIS functionality to Python
  2. Access to rich suite of geoprocessing tools
  3. Functions, classes and modules
  4. Helper functions like ListFeatureClasses, Describe
  5. Classes that can be used to create complex objects like Spatial Reference, Field Map
  6. Modules that provide specialized functionality like Mapping,SpatialAnalyst, NetworkAnalyst, DataAccess

Complete Introduction to Python concepts for beginners is available here

Python
ArcGIS + Python = ArcPython

For more info and advance Concepts use the folowing references: 

resources.ArcGIS.com
arcpy.wordpress.com
GIS Stack Exchange, Stack Overflow
Python References,Python Scripting for ArcGIS
GIS Tutorial for Python Scripting by Allen (Esri Press)
Learning Python by Lutz - The Python Standard Library
python.org
http://www.esri.com/training

Exporting the feature class to CSV Format


Exporting Geodatabase toComma Separated Value Format

Let start creating an python addin for converting the feature class in your geodatabase to CSV format.So that everyone can understand your feature class and its values.
  • If you are very new to python addin then go through- How to start with python addin 
  • The input feature class and output csv file path are hard coded in the sample program
  • For dynamic conversion get the path of the files through a variable and pass it as a parameter to the defined functions
Comma Seperated values
CSV Fromat



def ex_fc_to_csv(fc, out_csv):
    """
    Export all vertex in a line or poly feature class to a csv with OID
   
    example

        import geom_snippets
        geom_snippets.ex_fc_to_csv(r"c:\proj\fc1.shp", r"c:\proj\fc1.csv")

    output csv looks like this

        1,56019.99998067904,69118.00001450378
        1,56159.99998080942,69026.0000144181
        1,56359.999980995686,68913.00001431286
        2,34985.00002508866,68936.00001433428
        2,35178.000025268404,68805.00001421227

    """
    import csv
    import json

    with open(out_csv, 'w') as csvfile:
        csvwriter = csv.writer(csvfile, delimiter=',', lineterminator='\n')

        with arcpy.da.SearchCursor(fc,
                                   field_names=("OID@","SHAPE@JSON")) as cursor:
            for row in cursor:
                geom = json.loads(row[1])
                for path in geom['paths']:
                    for pt in path:
                        csvwriter.writerow([row[0]] + pt)

Friday, 12 December 2014

How to create a simple python add-in tool for ArcGIS Desktop

How to create a simple python add-in for ArcGIS Desktop


TOOL USED:  Python Add-in Assistant

WORKING OF THE TOOL:
Creating a Simple python add-in assistant for ArcGIS Desktop to add a Fishnet table to the ArcMap using the python
Type of Python Add-in: Tool Type
Function: At the end of drawing a rectangle on the ArcMap a fishnet with specified rows and columns should appear on the Screen
A python add-in tool is very similar to a button. But, a tool requires user to interact with the map application based on that interaction some business logic will get executed. The Zoom In tool Description: Zoom In in ArcMap will be a great example, when the user draws a rectangle on the ArcMap ,then the map will be redrawn with that rectangle as an extent.
Below steps will help you to create both Toolbox as well as a Tool on it

PROCEDURE:
Steps to Create a Toolbar for your Tool:
1.     To create your own toolbar. Open the Add-n assistant and Go to Add-in Contents tab and give the information about the add-in which you are going to create.
Note: A tool can reside on a Toolbar but cannot sits on a Menu
2.     Click the Add-In Contents tab and begin declaring your add-in customizations. A tool can reside on a toolbar but not on a menu. See creating an add-in toolbar for more detailed procedure.
3.     To Create the tool on your new Toolbar
Right-click the new toolbar and choose New Tool on the right click Menu.
Python addin assistant window

At once you have finished giving out the information and details about the add-in. Click on Save button at the bottom of the wizard. All the necessary files and folders will get created within the working folder of your add-in assistant.
Now it is the time to work on the main code. Go to the python script located on the install folder and open it using your Python idle. Code will appear as shown below with the class name same as your button name.
Note: Do not change the button name as it is directly linked with the button and registered in the your Config.xml file

 
Onclick() methof of the addin button class
The Onclick () method shown on idle will get executed on when the user click on the tool . But I our case the fishnet should get created whenever the user draw the tool is selected and draw an rectangle on the Map. So to do that OnRectangle () method of the python add-in will comes in to Picture. Replace on click method with OnRectangle () method as shown below:


Fishnet content added to On Rectangle method


·         The code will check for any preexistence of fishnet on the memory using the Exist() Method and deletes if anyone is already there using the Delete_Management() function.
·         CreateFishnet_management is the core function which is going to do the actual work after supply all the necessary parameters to it
·         Refresh the active view to redraw the Map and return the path of the fishnet to the calling function.







Wednesday, 26 November 2014

Custom Geoprocessing Tool


Arcobjects Geoprocessing Procedure:



1. Create a geoprocessor object and set its properties.
2. Set the appropriate values for the tool’s parameters.
3. Execute a tool using the geoprocessor object’s Execute() method.

In order to create a geoprocessor object, the IGeoProcessor2 interface can be used. This interface
is defined in the geoprocessing library of ArcObjects and is implemented by the GeoProcessor
CoClass.

IGeoProcessor2 gp = new GeoProcessorClass();
//add the result of geoprocessing as a new layer to Map
gp.AddOutputsToMap = true;
//if output of geoprocessing exists before the execution of tool
//it will be overwritten
gp.OverwriteOutput = true;

Assume that you want to create Thiessen polygons for the cities FeatureClass to create proximal
zones for all cities. The proximal zones represent full areas where any location inside the zone is
closer to its associated city than any other city. Based on the Create Thiessen Polygons reference
page, you have to provide at least an input point FeatureLayer and the path to the output
FeatureClass.
In order to create and set each parameter, the IVariantArray interface of the System library must
be used.

IVariantArray parameters = new VarArrayClass();

Each parameter has to be added to the IVariantArray interface in the exact order that is specified
on the tool’s reference page.

//in_features
parameters.Add(@"D:\DataFolder\fileGDB.gdb\cities");
//out_feature_class
parameters.Add(@"D:\DataFolder\fileGDB.gdb\citiesThiessen");
//fields_to_copy(Optional)
parameters.Add("ALL");

As it is illustrated on the Create Thiessen Polygons reference page, the third parameter is optional.
You can simply not add any value to IVariantArray or, as shown in the preceding code, you can
provide an appropriate value for the optional parameter. You can skip the optional parameter
using an empty string as input to IVariantArray’s Add() method. For example, look at the
reference page of the Buffer tool; you can see that three of the seven available parameters are
mandatory. The following code demonstrates how to skip the fourth parameter and specify the
fifth parameter:

//1-in_features
parameters.Add(@"D:\test.gdb\cities");
//2-out_feature_class
parameters.Add(@"D:\test.gdb\citiesBuffer");
//3-buffer_distance_or_field
parameters.Add("50 kilometers");
//4-line_side(Optional)
parameters.Add("");
//5-line_end_type(Optional)
parameters.Add("ROUND");
//6 &7 there is no need to provide empty string
//for the rest of parameters since you don't want to set them
After setting all the required parameters, all you need to run a tool is to call the Execute() method
of the geoprocessor object. The Execute() method solicits the name of the tool and its parameters.

gp.Execute("CreateThiessenPolygons_analysis", parameters, null);
The following code shows the complete code for this example. In order to run the code, you need to
add references to the Geoprocessing and System libraries of ArcObjects:
IGeoProcessor2 gp = new GeoProcessorClass();
//add the result of geoprocessing as a new layer to Map
gp.AddOutputsToMap = true;
//if output of geoprocessing exists before the execution of tool
//it will be overwritten
gp.OverwriteOutput = true;
IVariantArray parameters = new VarArrayClass();
//in_features
parameters.Add(@"D:\DataFolder\fileGDB.gdb\cities");
//out_feature_class
parameters.Add(@"D:\DataFolder\fileGDB.gdb\citiesThiessen");
//fields_to_copy(Optional)
parameters.Add("ALL");
//or parameters.Add("");
gp.Execute("CreateThiessenPolygons_analysis", parameters, null);


The Geoprocessing library of ArcObjects is accessible through the ESRI.ArcGIS.Geoprocessing
namespace. This library contains a few hundred types which can be used to run and manage tools
and GIS workfl ows. You learned earlier in this section that IGeoProcessor2 is the main interface of
this library and the easiest way to run a geoprocessing tool is to call its Execute() method.
However, using IGeoProcessor2 is not the only approach to run a geoprocessing tool or model.
There are some managed assemblies created by Esri to performing geoprocessing in a managed
way. A managed way means there is a native .NET assembly (the Geoprocessor assembly) that is
a wrapper for some types in the Geoprocessing library of ArcObjects, and there are other .NET
assemblies for each system toolbox.
These native .NET assemblies provide an even easier way to run a system tool. In general, the
procedure for running a tool using the Geoprocessor-managed assembly is the same as running a tool