Geog 593 – GISci Programming : Geog 593 – GISci Programming
Lecturer - Jun Liang
Department of Geography @ UNC, Chapel Hill
August 23rd, 2007
Email: liangj@email.unc.edu
Lecture 1 : Lecture 1 1-1 Introduction
What is GIS?
Data Software People Hardware
Data input, management, analysis, result publish/output
TOOL VS SCIENCE (Similar comparison - software VS computer science)
TOOL View – in many application fields
SCIENCE View – Spatial Analytical Components, Algorithms, called GISci
1-2 GIS Software (Cont.) : 1-2 GIS Software (Cont.) Comparisons between them:
Command line is flexible, but is more difficult to learn.
GUI driven software is easy to learn, but is not flexible.
Example:
Measurement tool in Arcview –
Can measure distance between two or more clicks.
Can not take real number inputs.
1-2 GIS Software : 1-2 GIS Software GIS Software Examples – ESRI Products (ArcGIS 8.X, Arcview 3.X, Arc/Info), Intergraph, MapInfo, Grass, IDRISI, ERDAS, etc. They can be divided into two categories:
- Windows based / GUI Menu driven
Command Line Style
Question: Which is better?
1-3 What can GIS help us? : 1-3 What can GIS help us? Scenario 1 - All required works can be handled by using software, without scripts
- software has menu or combination of menus for all required works.
Scenario 2 - Some GIS projects can not be done with available software, without programming
- No required functions/menus
Scenario 3 - Some GIS projects are repeating works of a similar routine.
- Tedious
- Could not maintain standard output/format
1-4 Before Learning GIS Programming : 1-4 Before Learning GIS Programming Knowledge and Experiences Preparation
Geography – applications, map projections
GIS – Spatial Analysis/Modeling
Software – ArcView, ArcGIS, ArcInfo
Programming – Object Oriented Programming, COM - Component Object Model (http://arcobjectsonline.esri.com/).
Slide7 : No one is an expert in all 4 fields (geography, GISci, Software and Programming).
To be successful in this course, you will need a field (mostly your major) to apply GIS, and knowledge of using GIS software. Some related resources or tips for makeup:
Learning ArcGIS 9
Learning ArcGIS 9 Spatial Analyst
Customizing ArcGIS 9
(4) Introduction to Visual Basic
(5) Introduction to Python
1-5 What is Avenue : 1-5 What is Avenue Avenue is the customization and development environment of ArcView. With it, you can:
Customize the way ArcView looks
Modify ArcView’s standard tools
Create new tools
Integrate ArcView with other applications
Develop and distribute custom applications on top of ArcView
1-5 What is Avenue (Cont.) : 1-5 What is Avenue (Cont.)
1-5 What is Avenue (Cont.) : 1-5 What is Avenue (Cont.)
1-5 What is Avenue (Cont.) : 1-5 What is Avenue (Cont.)
1-5 What is Avenue (Cont.) : 1-5 What is Avenue (Cont.)
1-6 Understanding objects : 1-6 Understanding objects Some facts about Arcview and Avenue:
Arcview are customizable using Avenue
Menus, tools, buttons are all associated with build-in Avenue scripts, which can be modified.
Avenue is a macro language, which is built on the top of a library of classes created by ESRI.
1-6 Understanding objects (Cont.) : 1-6 Understanding objects (Cont.) Questions about classes:
What objects are
How classes organize objects
How requests put objects to work
How statements execute requests
How to get help on classes and requests
1-6 Understanding objects (Cont.) : 1-6 Understanding objects (Cont.) What are objects?
Has a definite set of characteristics or properties
Has a set of things it does
Has a current state
Example – car
Properties: make, model, model, 2/more doors, etc.
Actions: start, stop, turn left, turn right
State: direction (north), speed (60mph)
In Arcview, everything you work with is an object.
1-6 Understanding objects (Cont.) : 1-6 Understanding objects (Cont.) In Arcview, everything you work with is an object. When you open a view, you are working with a View Object. Example:
myView = av.GetActiveDoc
myScale = 10000
myView.GetDisplay.ZoomToScale(myScale)
Questions:
How many different kinds of documents ArcView has?
1-6 Understanding objects (Cont.) : 1-6 Understanding objects (Cont.) How classes organize objects?
Objects with similar characteristics are grouped together in a class. A class defines the properties and actions for a specific type of object.
Instance – An object created from a class is a instance of that class.
Example:
Car Class => Car1, Car2, Car3
View Class => View1, View2, View3
1-6 Understanding objects (Cont.) : 1-6 Understanding objects (Cont.) Inheritance indicates an “is a kind of” relationship. Example:
Chart
Layout
Project
SEd
Table
View
1-6 Understanding objects (Cont.) : 1-6 Understanding objects (Cont.) Aggregation indicates an “is composed of” relationship. (One direction)
A car is composed of an engine, four tires, a radio, and seats. And a radio is composed of tuner and cassette.
Project DocGUI
Document
DocWin Table
View TOC
Theme
1-6 Understanding objects (Cont.) : 1-6 Understanding objects (Cont.) Association describes the physical or conceptual connection between classes.
Example:
A car runs on gasoline.
A car is driven by a person.
A polygon is filled with a pattern.
1-7 Executing requests : 1-7 Executing requests Avenue statement syntax: Object.Request. Examples:
Add: include another object in a group of objects
aView.AddTheme
Find: search for the specified object and return a reference to it.
aView.FindTheme(“Roads”)
As: convert an object to an object of a different class
aNumber.AsString
Can: check if the object can perform the specified function
aTheme.CanEdit
Get: return a reference to an object aView.GetThemes
Has: Indicate if the object has the specified condition of state
Is: return true or false aButton.IsVisible
Make: create a new instance View.Make
Return: create a new object and return a reference to it
Set: assign an attribute of an object aButton.SetIcon
1-7 Executing requests (Continued) : 1-7 Executing requests (Continued) Evaluation from left to right
2 + 3 x 3 <> 2 + (3 x 3)
No declaration of variables
Make the name of a variable meaningful
Scope of variables
Global: variable name starts with a “_”
Local: variable name does not start with a “_”
Source code of all system scripts is available
Exercise : Exercise Instruction:
Create a new Arcview project, and a new view document “view1”.
Add three shape files to “view1”: states.shp, cities.shp, counties.shp. Location – I:\datashare\temp\593\lecture1\USA.
Please create a script which will perform the following tasks:
(1) set the following properties for current view document (“view1”):
Name: “united states.”
Creator: using your own name.
Comments: "this view includes three themes: cities.shp, states.shp, counties.shp."
(2) toggle the status of each theme as following:
If it is active, set it as not active.
If it is visible, set it as not visible.
If its legend is visible, set it as not visible.
(3) toggle the background color of view between yellow and blue.
(4) set the creator of your script with your own name, and comments as “my first avenue script.”
Note: please create a button and associate the script with it.
1-8 Sources for ESRI’s scripts : 1-8 Sources for ESRI’s scripts Sample scripts from ESRI
Help file from ESRI
ArcScripts: http://arcscripts.esri.com
GeoCommunity - Software Scripts: http://software.geocomm.com/scripts/
Scripts you developed in past.
1-9 Create an Avenue Script : 1-9 Create an Avenue Script Before creating a new Avenue script, make sure:
You know what you are doing – problem analysis, functions you will need/develop, etc.
Materials are ready – scripts you can borrow, sample input files.
Time cost – you can finish it within your time frame (complexity analysis).
1-9 Create an Avenue Script (Cont.) : 1-9 Create an Avenue Script (Cont.) Typical procedures:
Create a new script document
If necessary, you can load existing script into your current document.
Coding…
Compile, Debug, and modify your script until it works.
Associate your script with a button, menu, or tool.
1-9 Create an Avenue Script (Cont.) : 1-9 Create an Avenue Script (Cont.) Example:
Problem: Draw a circle based on three inputs – location user clicked will be the center; a value user input will be the radius; RGB values from user input will be used as color for the circle
Analysis: A dialog input windows for user input;; might borrow codes from view.pointTool ; it should be designed as a tool as well.
Coding in an empty script document:
1-9 Create an Avenue Script (Cont.) : 1-9 Create an Avenue Script (Cont.) Point Tool Code:
theView = av.GetActiveDoc
pt = theView.GetDisplay.ReturnUserPoint
theTheme = theView.GetEditableTheme
if (theTheme <> nil) then
thePrj = theView.GetProjection
if (thePrj.IsNull.Not) then
pt = pt.ReturnUnprojected(thePrj)
end
theField = theTheme.GetFTab.FindField("Shape")
theTheme.GetFTab.BeginTransaction
rec = theTheme.GetFTab.AddRecord
theTheme.GetFTab.SetValue(theField, rec, pt)
theTheme.GetFTab.EndTransaction
theTheme.GetFTab.GetSelection.ClearAll
theTheme.GetFTab.GetSelection.Set(rec)
theTheme.GetFTab.UpdateSelection
else
gp = GraphicShape.Make(pt)
theView.GetGraphics.UnselectAll
gp.SetSelected(TRUE)
theView.GetGraphics.Add(gp)
end
av.GetProject.SetModified(true)
1-9 Create an Avenue Script (Cont.) : 1-9 Create an Avenue Script (Cont.) Classes you may need for this script:
View
Point
MsgBox
Circle
Color
Symbol
GraphicShape
1-10 ArcView Avenue Library : 1-10 ArcView Avenue Library Obj: Class Obj is the most generic object class. It is the abstract superclass for all other classes in the ArcView class hierarchy. Any subclass of Obj inherits all the generic object behavior, including object management, persistence, and most importantly, the object request mechanism.
Attributes (Member Variables):
Name
Class
Functions/Behaviors/Requests:
GetClassName : String
HasInstances : Boolean
IsSubclassOf ( anotherClass ) : Boolean
1-10 ArcView Avenue Library (Cont.) : 1-10 ArcView Avenue Library (Cont.) <> anotherObj : Boolean
= anotherObj : Boolean
AsString : String
Clone : Obj
GetClass : Classes
GetName : String
Is ( aClass ) : Boolean
SetName ( aName )
Note all classes inherited from “OBJ” will inherit both its attributes and behaviors.
Please use Arcview’s online help for more information.
1-10 ArcView Avenue Library (Cont.) : 1-10 ArcView Avenue Library (Cont.) Another example: “View” class
Attributes:
Display a MapDisplay on which the themes and graphics are drawn.
Graphics is a GraphicList which contains the graphics drawn on top of the themes as well as those associated with a theme.
Projection is the projection used to convert all themes from decimal degrees to a planar screen.
Area Of Interest is the area of interest applied to all themes that support the concept. Setting the AOI for a theme defines the spatial extent of the theme.
Themes is a list of the themes contained in the views. Themes can be active or inactive, and visible or invisible. One theme can be the editable theme.
TOC is the Table Of Contents of the View. The width of the TOC can be set, as well as whether you can resize it or not.
1-10 ArcView Avenue Library (Cont.) : 1-10 ArcView Avenue Library (Cont.) Making Views
Make : View
MakeWithGUI ( aGUIName ) : View
Noticed functions and requests are grouped into different categories:
Changing the Structure of a View
AddTheme ( aTheme )
DeleteTheme ( aTheme )
FindTheme ( aName ) : Theme
FindThemeByClass ( aName, aClass ) : Theme
1-10 ArcView Avenue Library (Cont.) : 1-10 ArcView Avenue Library (Cont.) Getting and Setting Attributes (Partial List)
Getting and Setting Attributes
GetActiveThemes : List
GetBackgroundSymbol : Symbol
GetCoordinatePrecision : Number
GetDisplay : Display
GetEditableTheme : Theme
GetFindString : String
GetGraphics : GraphicList
GetProjection : Prj
GetThemes : List
GetTOC : TOC
GetTOCWidth : Number
GetUnits : UnitsLinearEnum
GetVisibleThemes : List
IsTOCUnResizable : Boolean
RefreshScale
ReturnAOI : Rect ReturnExtent : Rect
ReturnScale : Number
SetAOI ( anAOI )
SetBackgroundSymbol ( aFill )
SetCoordinatePrecision ( decimalPlaces )
SetCoordsDMS ( showDMS )
SetCoordsVisible ( isVisible )
SetEditableTheme ( aTheme ) : Boolean
SetInteractiveSnapping ( anFTheme, aSnapRule )
SetInteractiveSnappingPersistent ( isPersistent )
SetProjection ( aPrj )
SetScaleVisible ( isVisible )
SetTOCUnResizable ( isUnResizable )
SetTOCWidth ( aWidth )
SetUnits ( aUnit )
1-10 ArcView Avenue Library (Cont.) : 1-10 ArcView Avenue Library (Cont.) Interacting with the User (Apply Events Only)
MoveUserRect ( aRect ) : Boolean
ReturnUserCircle : Circle
ReturnUserLine : Line
ReturnUserPolygon : Polygon
ReturnUserPolyLine : PolyLine
ReturnUserRect : Rect
Select
SelectToEdit
Manipulating a View
Edit
Export : FileName
ExportToFile ( aFileName, aFormatString, aListOfParameters ) : FileName
Find ( aString ) : Boolean
GetAutoLabels ( aLabeler, unplaced )
GetOverlapLabelColor : Color
1-11 Controls in Avenue : 1-11 Controls in Avenue Similar to other programming languages, Avenue also has its controlling mechanism, using IF..THEN..ELSE, FOR loop, WHEN, etc. if..then..else
if ( expression1 ) then
request block1
end
if ( expression1 ) then
request block1
else
request block2
end
if ( expression1 ) then
request block1
elseif ( expression2 ) then
request block2
[else]
request block3
end
for each variable in collection [ by increment ]
request block
end
1-11 Controls in Avenue (Cont.) : 1-11 Controls in Avenue (Cont.) Example for IF..THEN..ELSE, FOR EACH loop
theView = av.GetActiveDoc
themeList = theView.GetThemes
if(themeList.count=0) then
MsgBox.info(“No theme available!”, “INFO”)
exit
Else
MsgBox.info(“You have “+themeList.count.AsString+” theme(s)”, “INFO”)
End
for each thm in themeList
thmName = thm.GetName
thmClass = thm.GetClassName
MsgBox.info(“Theme: “+thmName+” is “+thmClass, “Theme Info”)
End
‘This is program in class
1-11 Controls in Avenue (Cont.) : 1-11 Controls in Avenue (Cont.) while ( expression)
request block
end
Example:
while (true)
again = MsgBox.YesNo( "do it again", "DO IT", TRUE )
if (not again) then
break
end
end
1-12 String, List and Numbers : 1-12 String, List and Numbers A String is a fixed length sequence of characters. The String class provides a host of requests for comparing, converting, manipulating, formatting and examining these sequences.
Examples of String operations and requests:
aStr = “Hellow”
bStr = “Mike”
cStr = aStr ++ bStr ++”!”
MsgBox.info(cStr, “INFO”)
dStr = “10200”
dValue = dStr.AsNumber
bAStr = aStr.IsNumber
subAStr = aStr.Left(4)
upBStr = bStr.UCase
1-12 String, List and Numbers (Cont.) : 1-12 String, List and Numbers (Cont.) A List is an ordered collection of heterogeneous objects. An object in collection is called an element of that collection. Each element in a list is referenced through a list index number. The first index is always 0 and the last index is always List.Count - 1.
Create a list with the brace notation or the Make request.
myList = { "Red", 201, myView, anotherList }
OR
myList = List.Make
myList.Add( "Red" )
myList.Add( 201 )
myList.Add( myView )
myList.Add( anotherList )
You may access list’s member variables and functions, for example:
nElements = myList.Count
1-12 String, List and Numbers (Cont.) : 1-12 String, List and Numbers (Cont.) anotherList = {1, 3, 5, 7, 9}
anotherList.Insert(11)
anotherList.Remove(3)
anotherList.RemoveObj(3)
Str1 = “dog”
Str2 = “cat”
Str3 = “mouse”
strList = {Str1, Str2, Str3}
MsgBox.info(“Str1 is “+Str1, “INFO”)
Str1 = “another dog”
MsgBox.info(“Str1 is “+Str1, “INFO”)
You need to notice – list is a collection of references. If you change the content of a reference, you change the corresponding list member.
1-12 String, List and Numbers (Cont.) : 1-12 String, List and Numbers (Cont.) Number:
(1) Set Format
Number.SetDefFormat( "d.ddd" ) ' application default
aScript.SetNumberFormat( "d,dddd") ' script default
aNumber.SetFormat( "dd" ) ' object
Example: "d.dd" - at least one digit to the left of the decimal point and exactly two characters to the right.
(2) Conversion between number and other data types
aNumber.AsChar: Returns a string with one character. That character is the ASCII byte whose value is aNumber.
Example: charX = 34.AsChar
charX will be set as “
aNumber.AsString: Returns a string representation of aNumber.
Example: stringX = 1204.AsString
stringX will be set as “1204”
1-12 String, List and Numbers (Cont.) : 1-12 String, List and Numbers (Cont.) (3)Arithmetic Operations and Functions
+, -, *, /, ^, negate
aNumber.AsString
aNumber.Ceiling
aNumber.floor
aNumber.Truncate
aNumber.sqrt
aNumber.Cos
aNumber.Sin
aNumber.Tan
aNumber.Log
aNumber.Ln
aNumber.Round
aNumber.Mod
aNumber.IsNull
1-13 Interacting with Views and Themes : 1-13 Interacting with Views and Themes What can you do with Views and Themes?
Create a new View
Add Themes to a View
Change the order of themes in the table of contents.
Change the drawing symbol of a theme
Delete a theme
Select features in a theme
Set a projection
Add graphics to View
Attach graphics to a theme
Convert selected features from a theme to a new theme
ETC.
1-13 Interacting with Views and Themes (Cont.) : 1-13 Interacting with Views and Themes (Cont.) Object model for views and themes:
1-13 Interacting with Views and Themes (Cont.) : 1-13 Interacting with Views and Themes (Cont.) Example 1 – Create a SrcName from a table that contains x, y coordinates.
theView = av.GetActiveDoc
theVtab = av.GetProject.FindDoc(“Coords.txt”).GetVtab
xField = theVtab.FindField(“xcoord”)
yField = theVtab.FindField(“ycoord”)
xySrc = XYName.Make(theVtab, xField, yField)
theTheme = Theme.Make(xySrc)
theView.AddTheme(theTheme)
A SrcName identifies the data used to create an ArcView theme. An XYName is a kind of SrcName used to create XY event themes. An XY event theme is a point theme created from coordinate data carried in a VTab. When the XY event theme is created, ArcView creates an FTab which contains the points identified by the X and Y Fields. This FTab is rebuilt from the VTab when the project is restored; it is not explicitly saved to file.
1-13 Interacting with Views and Themes (Cont.) : 1-13 Interacting with Views and Themes (Cont.) Example 2 – Changing the order of themes in a view’s table of contents
theView = av.GetActiveDoc
theTHemeList = theView.GetThemes
‘the first theme becomes the last
theThemeList.Shuffle(theThemeList.Get(0), (theTHemeList.Count))
‘make the last theme active
theThemeList.Get(theThemeList.Count – 1).SetActive(true)
Theview.InvalidateTOC(nil)
theView.GetDisplay.Invalidate(true)
aTOC = aView.GetTOC
aTOC.SetOrderLocked
1-13 Interacting with Views and Themes (Cont.) : 1-13 Interacting with Views and Themes (Cont.) Example 3 – Chaning the symbol a theme is drawn with
theView = av.GetActiveDoc
theTheme = theView.GetThemes.Get(0)
theLegend = theTheme.GetLegend
‘Get the first symbol and change its color to blue
theSymbol = theLegend.GetSymbols.Get(0)
theSymbol.SetColor(Color.getBlue)
‘Update the legend to reflect the change and draw the theme
theTheme.UpdatedLegend
Example 4 – Deleting active themes
theView = ac.GetActiveDoc
for each t in theView.GetActiveThemes
if(MsgBox.YesNo(“Are you sure you want to delete theme “+t.asString+ “?”, “Delete Theme”, true)) then
theView.DeleteTheme(t)
end
Av.GetProject.SetModified(true)
1-13 Interacting with Views and Themes (Cont.) : 1-13 Interacting with Views and Themes (Cont.) Example 5 – Selecting features with the mouse
theView = av.GetActiveDoc
theTheme = theView.GetActiveThemes.Get(0)
theRectangle = theView.ReturnUserRect
theTheme.SelectByRect(theRectangle, #VTAB_SELTYPE_NEW)
Example 6 – Selecting features with graphic shapes
theView = ac.GetActiveDoc
theTheme = theView.GetActiveThemes.Get(0)
theGraphics = theView.GetGraphics.GetSelected
shapeList = {}
for each g in theGraphics
shapeList.Add(g.GetShape)
end
theTheme.SelectByShapes(shapeList, #VTAB_SELTYPE_NEW)
1-13 Interacting with Views and Themes (Cont.) : 1-13 Interacting with Views and Themes (Cont.) Example 7 – Set the background of current view to red color
theView = av.GetActiveDoc
color1 = Color.Make
color1.SetRgbList({255,255,0})
symbol1 = Symbol.Make(#SYMBOL_FILL)
symbol1.SetColor(color1)
symbolX = theView.GetBackgroundSymbol
theView.SetBackgroundSymbol(symbol1)
theView.Invalidate
Example 8 – Set propertis of current view
theView = av.GetActiveDoc
theView.SetCreator(“John Smith")
theView.SetComments(“Empty")
theView.SetName(“GEOG-EXAMPLE8")
1-14 MsgBox Class : 1-14 MsgBox Class The MsgBox class provides requests for modal interaction with the end-user. Some requests prompt for user input, while others only display messages. All requests require the user to acknowledge the MsgBox by clicking a response.
Class requests can be divided into two categories: display and input.
(1) Display requests
MsgBox.info(“A Message”, “A Title”)
MsgBox.Error(“A Message”, “A Title”)
MsgBox.Report(“A Long Message”, “A Title”)
(2) User Input requests
MsgBox.YesNo( aMsg, aTitle, defaultIsYes ) : Boolean
MsgBox.Input ( aMsg, aTitle, defaultString ) : String
MsgBox.MultiInput (aMsg, aTitle, labels, defaults): List
MsgBox.List (aList, aMsg, aTitle): Obj
MsgBox.MultiList (aList, aMsg, aTitle): List
1-14 MsgBox Class (Cont.) : 1-14 MsgBox Class (Cont.) Example A:
labels = { "catalog number", "size", "color", "price" }
defaults = { "2Y4445G", "4", "red", "24.99" }
order = MsgBox.MultiInput( "Make your order", "Order", labels, defaults )
MsgBox.ListAsString( order, "Here is your order", "LOOK" )
Example B:
theView = av.GetActiveDoc
theThemeList = theView.GetThemes
deleteThmList = MsgBox.MultiList (theThemeList, “Please choose themes you want to delete”, “Themes Selection”)
for each thm in deleteThmList
theView.DeleteTheme(thm)
end
av.GetProject.SetModified(true)
Exercises : Exercises Create a script, which will prompt a list of all point themes to user. User will choose one of them. The selected theme will be moved to the top and set to be active.
Draw a red circle on current view. The bounding square of the circle will be ¼ of the display area. Set circle’s center at the center of display area as well.
Design a script to diagnose if a person is overweight or underweight, using weight (pound) and height (feet). Using the following formulas:
- Standard Weight: sw = (height*30.48-105)/0.454
- Normal Weight: sw*0.9<=weight<=sw*1.1
- Over Weight: sw*1.1sw*1.2
- Thin: weight
More Exercises : More Exercises (4) Generate a random number between 1-100, and prompt a dialog for user to make a guess. If it matches the random number, prompt a message (how many times user tried) to user and stop the program, otherwise prompt user a message with information about the comparison (greater than, or smaller than) and ask user to make another guess.