Tải bản đầy đủ (.pdf) (343 trang)

ArcPy and ArcGIS geospatial analysis with python by silas toms

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (4.19 MB, 343 trang )



ArcPyandArcGIS–GeospatialAnalysis
withPython


TableofContents
ArcPyandArcGIS–GeospatialAnalysiswithPython
Credits
AbouttheAuthor
AbouttheReviewers
www.PacktPub.com
Supportfiles,eBooks,discountoffers,andmore
Whysubscribe?
FreeaccessforPacktaccountholders
Preface
Whatthisbookcovers
Whatyouneedforthisbook
Whothisbookisfor
Conventions
Readerfeedback
Customersupport
Downloadingtheexamplecode
Downloadingthecolorimagesofthisbook
Errata
Piracy
Questions
1.IntroductiontoPythonforArcGIS
OverviewofPython
Pythonasaprogramminglanguage
Interpretedlanguage


Standard(built-in)library
Thegluelanguage
Wrappermodules
ThebasicsofPython
Importstatements


Variables
Forloops
If/Elif/Elsestatements
Whilestatements
Comments
Datatypes
Strings
Integers
Floats
Lists
Tuples
Dictionaries
Iterabledatatypes
Otherimportantconcepts
Indentation
Functions
Keywords
Namespaces
Zero-basedindexing
ImportantPythonModulesforGISAnalysis
TheArcPymodule
TheOperatingSystem(OS)module
ThePythonSystem(SYS)module

TheXLRDandXLWTmodules
Commonlyusedbuilt-infunctions
Commonlyusedstandardlibrarymodules
Summary
2.ConfiguringthePythonEnvironment
WhatisaPythonscript?
HowPythonexecutesascript
WhatisthePythoninterpreter?


WhereisthePythoninterpreterlocated?
WhichPythoninterpretershouldbeused?
Howdoesthecomputerknowwheretheinterpreteris?
MakePythonscriptsexecutablewhenclickedon
IntegratedDevelopmentEnvironments(IDEs)
IDLE
PythonWin
AptanaStudio3
IDEsummary
Pythonfolderstructure
Wheremodulesreside
UsingPython’ssysmoduletoaddamodule
Thesys.path.append()method
Summary
3.CreatingtheFirstPythonScript
Prerequisites
ModelBuilder
CreatingamodelandexportingtoPython
ModelingtheSelectandBuffertools
AddingtheIntersecttool

Tallyingtheanalysisresults
Exportingthemodelandadjustingthescript
Theautomaticallygeneratedscript
FilepathsinPython
Continuingthescriptanalysis:theArcPytools
TheIntersecttoolandstringmanipulation
Thestringmanipulationmethod1–stringaddition
Thestringmanipulationmethod2–stringformatting#1
Thestringmanipulationmethod3–stringformatting#2
AdjustingtheScript
AddingtheCSVmoduletothescript


Accessingthedata:Usingacursor
Thefinalscript
Summary
4.ComplexArcPyScriptsandGeneralizingFunctions
Pythonfunctions–Avoidrepeatingcode
Technicaldefinitionoffunctions
Afirstfunction
Functionswithparameters
Usingfunctionstoreplacerepetitivecode
Moregeneralizationofthefunctions
Summary
5.ArcPyCursors–Search,Insert,andUpdate
Thedataaccessmodule
Attributefieldinteractions
Updatecursors
Updatingtheshapefield
Adjustingapointlocation

DeletingarowusinganUpdateCursor
UsinganInsertCursor
Insertingapolylinegeometry
Insertingapolygongeometry
Summary
6.WorkingwithArcPyGeometryObjects
ArcPygeometryobjectclasses
ArcPyPointobjects
ArcPyArrayobjects
ArcPyPolylineobjects
ArcPyPolygonobjects
Polygonobjectbuffers
OtherPolygonobjectmethods
ArcPygeometryobjects


ArcPyPointGeometryobjects
Summary
7.CreatingaScriptTool
Addingdynamicparameterstoascript
Displayingscriptmessagesusingarcpy.AddMessage
Addingdynamiccomponentstothescript
CreatingaScripttool
Labellinganddefiningparameters
Addingdatatypes
AddingtheBusStopfeatureclassasaparameter
AddingtheCensusBlockfeatureclassasaparameter
AddingtheCensusBlockfieldasaparameter
Addingtheoutputspreadsheetasaparameter
Addingthespreadsheetfieldnamesasaparameter

AddingtheSQLStatementasaparameter
Addingthebusstopfieldsasaparameter
Inspectingthefinalscript
RunningtheScriptTool
Summary
8.IntroductiontoArcPy.Mapping
UsingArcPywithmapdocuments
Inspectingandreplacinglayersources
Fixingthebrokenlinks
Fixingthelinksofindividuallayers
ExportingtoPDFfromanMXD
Adjustingmapdocumentelements
Automatedmapdocumentadjustment
Thevariables
Themapdocumentobjectandthetextelements
Thelayerobjects
Replacingthedatasources


Adjustinglayervisibility
Generatingabufferfromthebusstopsfeatureclass
Intersectingthebusstopbufferandcensusblocks
Populatingtheselectedbusstopandbufferfeatureclasses
Updatingthetextelements
ExportingtheadjustedmaptoPDF
RunningthescriptinthePythonWindow
Summary
9.MoreArcPy.MappingTechniques
Usingarcpy.mappingtocontrolLayerobjects
Layerobjectmethodsandproperties

Definitionqueries
Controllingthedataframewindowextentandscale
AddingaLayerobject
Exportingthemaps
Summary
10.AdvancedGeometryObjectMethods
CreatingaPythonmodule
The__init__.pyfile
Addingadvancedanalysiscomponents
AdvancedPolygonobjectmethods
Generatingrandompointstorepresentpopulation
Usingthefunctionswithinascript
CreatinganXLSusingXLWT
Summary
11.NetworkAnalystandSpatialAnalystwithArcPy
TheNetworkAnalystextension
UsingNetworkAnalyst
CreatingaFeatureDataset
Importingthedatasets
CreatingtheNetworkDataset


AccessingtheNetworkDatasetusingArcPy
Breakingdownthescript
TheNetworkAnalystmodule
AccessingtheSpatialAnalystExtension
Addingelevationtothebusstops
UsingMapAlgebratogenerateelevationinfeet
Addinginthebusstopsandgettingelevationvalues
Thefinalresult

Summary
12.TheEndoftheBeginning
Gettingfieldinformationfromfeatureclasses
AccessingtheListFields’properties
Listcomprehensions
Creatingthefieldinformationfunctions
Queryingfeatureclassinformation
GeneratingFileGeodatabasesandfeatureclasses
Generatingafeatureclass
Settingupthescripttoolparameters
Environmentalsettings
Resolutionandtolerancesettings
Summary
Index



ArcPyandArcGIS–GeospatialAnalysis
withPython



ArcPyandArcGIS–GeospatialAnalysis
withPython
Copyright©2015PacktPublishing
Allrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem,
ortransmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthe
publisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.
Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyofthe
informationpresented.However,theinformationcontainedinthisbookissoldwithout

warranty,eitherexpressorimplied.Neithertheauthor,norPacktPublishing,andits
dealersanddistributorswillbeheldliableforanydamagescausedorallegedtobecaused
directlyorindirectlybythisbook.
PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthe
companiesandproductsmentionedinthisbookbytheappropriateuseofcapitals.
However,PacktPublishingcannotguaranteetheaccuracyofthisinformation.
Firstpublished:February2015
Productionreference:1210215
PublishedbyPacktPublishingLtd.
LiveryPlace
35LiveryStreet
BirminghamB32PB,UK.
ISBN978-1-78398-866-2
www.packtpub.com



Credits
Author
SilasToms
Reviewers
AlessioDiLorenzo
DaraO’Beirne
MarkPazolli
MarjorieRoswell
CommissioningEditor
AshwinNair
AcquisitionEditor
HarshaBharwani
ContentDevelopmentEditor

AkashdeepKundu
TechnicalEditor
DeeptiTuscano
CopyEditors
AartiSaldanha
AdithiShetty
ProjectCoordinator
MiltonDsouza
Proofreaders
SimranBhogal
JoannaMcMahon
BernadetteWatkins
Indexer
PriyaSane
ProductionCoordinator
AlwinRoy
CoverWork
AlwinRoy




AbouttheAuthor
SilasTomsisageospatialprogrammerandanalystwithaloveofgeography,history,
food,andsports.HeresidesintheSanFranciscoBayAreaandcan’tdecidewhichsideof
theBayismorebeautiful.Hereceivedabachelor’sdegreeinGeographyfromHumboldt
StateUniversityandiscurrentlypursuingamaster’sdegreeinGISatSanFranciscoState
University.WithabackgroundinGISanalysisforcitygovernmentsandenvironmental
consulting,SilaslovesthecombinationofGISandPythonforanalysisautomationand
datamanipulation.

WorkingforAriniGeographics,SilasishelpinggovernmentsunderstandhowGIScan
organizeandsimplifythemanagementofinfrastructureandtheenvironment.Thisdual
roleasaprogrammerandanalystallowshimtousePythonandGIStoquicklyproduce
geospatialdataandtools.Combinedwithwebmapping,thesetoolsaretransforminghow
governmentsworktoservethepublic.HealsoteachesworkshopsonArcPyandweb
mappingattheCityCollegeofSanFrancisco,whilehopingtoonedayfinishhismaster’s
thesis.
SilashasworkedasarevieweronthebookPythonGeospatialAnalysis,PacktPublishing
andisworkingonthebookPythonGeospatialDevelopment,PacktPublishingtobe
publishedin2015.
Iwouldliketothankmygirlfriend,Christine,forherencouragementandpatience.I
wouldliketothankmyboss,GabrielPaun,forhisinspirationandforpushingmeto
becomeatrueGISprofessional.IwouldliketothankthefacultyatHSUandSFSUfor
theirhelpalongtheway,andIwouldliketothankmyfamilyfortheirbeliefinmeandfor
neveraskingmeifIwasgoingtobecomeateacherwithmygeographydegree(even
thoughIhaveandIloveit!).



AbouttheReviewers
AlessioDiLorenzoisamarinebiologistandhasanMScinGeographicalInformation
Systems(GIS)andRemoteSensing.Since2006,hehasbeendealingwiththeanalysisand
developmentofGISapplicationsdedicatedtothestudyandspreadofenvironmentaland
epidemiologicaldata.Heisexperiencedintheuseofthemainproprietaryandopensource
GISsoftwareandprogramminglanguages.
DaraO’BeirneisacertifiedGISProfessional(GISP)withovereightyearsofGISand
Pythonexperience.DaraearnedbothhisBachelorsandMastersofArtsdegreesin
geographyfromSanFranciscoStateUniversity.DaraiscurrentlyaGISAnalystworking
atAriniGeographicsinSantaClara,CA.BeforejoiningAriniGeographics,Darawasa
GISAnalystandtechnicalleadatTowillInc.,aGISandLandSurveyingcompanyin

NorthernCalifornia.AtTowill,Daraplayedacentralroleindevelopingandimplementing
proceduresrelatedtothecollectionandanalysisofLiDARdataforenvironmentaland
engineeringapplications.PriortoTowill,DaragainedhisprofessionalGISexperience
workingfortheGoldenGateNationalRecreationAreamanagedbytheNationalPark
Service,oneofthelargesturbanparksystemsintheworld,whichincludesNational
treasures,suchasAlcatraz,MuirWoods,andtheMarinHeadlands.HisMaster’sThesis
examinedtheerrorsassociatedwithmeasuringtreeheightsinanurbanenvironmentwith
bothtraditionalfieldmethodsandairborneLiDARdata.
Iwouldliketothankmywife,Kate,anddaughter,AnyaO’Beirne,fortheirpatienceand
assistanceduringthereviewofthisbook.
MarjorieRoswellisawebdeveloperandmapmakerfromBaltimore,MD.She
purchasedherfirstGISin1991,andbuiltanapplicationtoassistcitizencallerstothe
BaltimoreOfficeofRecycling.Recentprojectsincludeinteractivemapsoflegislative
scores,politicalendorsements,committees,electiondata,andadvocacyinterests.
HersitedetailsCongressionalcommitteemembership,while
thesiteisdevotedtomappingandchartingfederalfoodand
farmpolicy.
MarjorieistheauthorofDrupal5ViewsRecipes,PacktPublishing.Shewasthetechnical
reviewerofjQueryUI1.10,TheUserInterfaceLibraryforjQuery,PacktPublishing.
MarkPazolliisanengineeranddatascientistwhousesArcGISandPythontohelphis
employersdecipherthemountainsofdatatheykeepontheassetsoftheWestern
Australianelectricalnetwork.HehasqualificationsinElectricalEngineering,Computer
Science,andAppliedMathematics.Heappreciatesexcellentdesignandenjoysbuilding
interestingthings.



www.PacktPub.com



Supportfiles,eBooks,discountoffers,and
more
Forsupportfilesanddownloadsrelatedtoyourbook,pleasevisitwww.PacktPub.com.
DidyouknowthatPacktofferseBookversionsofeverybookpublished,withPDFand
ePubfilesavailable?YoucanupgradetotheeBookversionatwww.PacktPub.comandas
aprintbookcustomer,youareentitledtoadiscountontheeBookcopy.Getintouchwith
usat<>formoredetails.
Atwww.PacktPub.com,youcanalsoreadacollectionoffreetechnicalarticles,signup
forarangeoffreenewslettersandreceiveexclusivediscountsandoffersonPacktbooks
andeBooks.

/>DoyouneedinstantsolutionstoyourITquestions?PacktLibisPackt’sonlinedigital
booklibrary.Here,youcansearch,access,andreadPackt’sentirelibraryofbooks.


Whysubscribe?
FullysearchableacrosseverybookpublishedbyPackt
Copyandpaste,print,andbookmarkcontent
Ondemandandaccessibleviaawebbrowser


×