Post on 26-Nov-2015
1of85
DevelopersCorner
Harold(Ted)DunsfordJr.MarkVanOrden
JiKadlec
October2009
2of85
TableofContentsTableofContents ______________________________________________________________2 1. DevelopersCorner__________________________________________________3
1.1. GeometryCheatSheet___________________________________________4 1.1.1. OverlayOperations:________________________________________________________8
1.2. Exercise1:AssembleaMapProject_______________________________10 1.2.1. Step1:StartaNewC#Application____________________________________________10 1.2.2. Step2:AddMapWindowComponents________________________________________11 1.2.3. Step3:AddMenuandStatusStrips___________________________________________13 1.2.4. Step4:AddtheMap_______________________________________________________15 1.2.5. Step5:AddtheLegendandToolbox__________________________________________16 1.2.6. Step6:LinkItAllTogether__________________________________________________18
1.3. Exercise2:SimplifyAustraliaDataLayers __________________________21 1.3.1. Step1:DownloadData_____________________________________________________21 1.3.2. Step2:CalculatePolygonAreas______________________________________________21 1.3.3. Step3:ComputeCentroids _________________________________________________23 1.3.4. Step4:SubsamplebyAttributes_____________________________________________24 1.3.5. Step5:ExportLayertoaFile________________________________________________25 1.3.6. Step6:RepeatwithRoadsLayer_____________________________________________25 1.3.7. Step7:SelectPoliticalBoundsbyClicking______________________________________26 1.3.8. Step8:ApplyLabeling _____________________________________________________27
1.4. ProgrammaticPointSymbology__________________________________29 1.4.1. AddaPointLayer_________________________________________________________29 1.4.2. SimpleSymbols___________________________________________________________32 1.4.3. CharacterSymbols________________________________________________________33 1.4.4. ImageSymbols___________________________________________________________37 1.4.5. PointCategories__________________________________________________________40 1.4.6. CompoundSymbols_______________________________________________________44
1.5. ProgrammaticLineSymbology___________________________________46 1.5.1. AddingLineLayers________________________________________________________46 1.5.2. OutlinedSymbols_________________________________________________________47 1.5.3. UniqueValues____________________________________________________________48 1.5.4. CustomCategories________________________________________________________49 1.5.5. CompoundLines__________________________________________________________50 1.5.6. LineDecorations__________________________________________________________53
1.6. ProgrammaticPolygonSymbology________________________________54 1.6.1. AddPolygonLayers _______________________________________________________54 1.6.2. SimplePatterns___________________________________________________________55 1.6.3. Gradients _______________________________________________________________56 1.6.4. IndividualGradients_______________________________________________________57 1.6.5. MultiColoredGradients____________________________________________________58 1.6.6. CustomPolygonCategories_________________________________________________60 1.6.7. CompoundPatterns_______________________________________________________61
1.7. ProgrammaticLabels___________________________________________62 1.7.1. FieldNameExpressions____________________________________________________63
3of85
1.7.2. MultiLineLabels _________________________________________________________64 1.7.3. TranslucentLabels________________________________________________________65
1.8. ProgrammaticRasterSymbology _________________________________66 1.8.1. DownloadData___________________________________________________________67 1.8.2. AddaRasterLayer________________________________________________________69 1.8.3. ControlCategoryRange____________________________________________________73 1.8.4. ShadedRelief ____________________________________________________________74 1.8.5. PredefinedSchemes_______________________________________________________75 1.8.6. EditRasterValues_________________________________________________________76 1.8.7. QuantileBreaks __________________________________________________________78
1.9. MapWindow4ConversionTips___________________________________80 1.9.1. Point___________________________________________________________________80 1.9.2. Extents _________________________________________________________________80 1.9.3. Shape __________________________________________________________________81 1.9.4. Shapefile________________________________________________________________82 1.9.5. Grid____________________________________________________________________83 1.9.6. GridHeader______________________________________________________________84 1.9.7. Image __________________________________________________________________84
1.10. ExtensionMethods ____________________________________________85
1. DevelopersCornerThis section gives a bit of an overview of geometric relationships, which are important forunderstandingsomeofthevectoranalysisoptions,andthengivessomeworkableexercisestodemonstratethecurrentcapabilitiesofMapWindow6.0.Thisshouldbethoughtofasakindofdevelopers preview, and not necessarily a comprehensive developers guide, which will bemade available before the MapWindow conference in Orlando in 2010. This part of thedocumentcoversusingMapWindowcomponents,stitchingtogetheraworkingGISbydraggingthe important components from the toolbox in visual studio, and then gives a detaileddescription of how to programmatically add layers and work with symbology or complexsymbolicschemes.
Ahugefocusforthe.NetversionofMapWindowistoputmuchmorecontrolintothehandsofdevelopers.Byprovidingeverythingintheformof.Netcomponents,itmakesitfarsimplertopickandchoosewhatsectionsoftheframeworkyouwanttoworkwith. Ifthemap isallyouneed,youdontneed tobotheradding the legendorourcustomstatusstripor the toolstrip.However,thosecomponentsareprovidedforyousothat ityoucanstitchtogetheraworkingGISwithoutwritingasinglelineofcode.
4of85
1.1. GeometryCheatSheetIn addition to organizing coordinates for drawing, the geometry classes provide a basicframework for testing topological relationships. These are spatial relationships that areprincipally concerned with testing how to shapes come together, for instance whether twoshapesintersect,overlap,orsimplytouch.Theserelationshipswillnotchangeevenifthespaceis subjected to continuous deformations. Examples include stretching or warping, but nottearingorgluing.
Theteststocomparetwoseparatefeatureslookattheinterior,boundary,andexteriorofbothfeatures thatarebeing compared. Thevarious combinations formamatrix illustrated in thefigurebelow.Itshouldbeapparentthatnotonlyaretheintersectionspossible,buteachregionwillhaveadifferentdimensionality.Apointisrepresentedasa0dimensionalobject,alineby1dimensionandanareaby2. Ifthetest isnotspecifictowhatdimension, itcanrepresentanydimensionasTrue.Likewise,ifitisrequiredthatthesetisempty,thenFalseisused.
Interior Boundary Exterior
Interior
Boundary
Exterior
Figure1:IntersectionMatrix
Graphically,weareillustratingtheintersectionmatrixfortwopolygons.Sometestscanberepresentedbyasinglesuchmatrix,orasingletest.Othersrequireacombinationofseveraltestsinordertofullyevaluatetherelationship.Whenthematrixisrepresentedinstringform,thevaluesare simply listed in sequenceasyouwould read thevalues from the top left row,throughthetoprowandthenrepeatingforthemiddleandbottomrows.Thefollowingareallpossiblevaluesinthematrix:
T:Valuemustbetruenonemptybutsupportsanydimensions>=0 F:Valuemustbefalseemptydimensions
5of85
0:Exactlyzerodimensions 1:Exactly1dimension 2:Exactly2dimensions
The following is a visual representation of the test or tests required in each case. A red Xindicatesthatthetestinthoseboundariesmustbefalse.Acoloredvaluerequiresthatthetestbetrue,butdoesntspecifyadimension.Agrayvalueindicatesthatthetestdoesntcareaboutthevalueofthatcell.
Contains:o Everypointoftheothergeometry isapointofthisgeometry,andthe
interiorsofthetwogeometrieshaveatleastonepointincommon.
o T*****FF*
o
I B EIBE
CoveredBy:o Everypointofthisgeometryisapointoftheothergeometry.
o T*F**F***,*TF**F***,**T*F***or**F*TF***
o
I B EIBE ,
I B EIBE ,
I B EIBE ,or
I B EIBE
Covers:o Everypointoftheothergeometryisapointofthisgeometry.
o T*****FF*or*T****FF*or****T*FF*
o
I B EIBE ,
I B EIBE ,or
I B EIBE
6of85
Crosses:o Geometrieshavesomebutnotallinteriorpointsincommon.
o T*T*****(forPoint/Line,Point/Area,Line/Area)
o
I B EIBE
o T*****T**(forLine/Point,Line/Area,Area/Line)
o
I B EIBE
o 0********(forLine/LineSituations)
o
I B EIBE
0
Disjoint:o Thetwogeometrieshavenopointincommon.
o FF*FF****
o
I B EIBE
Intersects:NOTDisjointo Thetwogeometrieshaveatleastonepointincommon.
7of85
Overlaps:o Thegeometrieshavesomebutnotallpointsincommon,theyhavethe
same dimension, and the intersection of the interiors of the twogeometrieshasthesamedimensionasthegeometriesthemselves.
o T*T***T**(forPoint/PointorArea/Area)
o
I B EIBE
o 1*T***T**(forLine/Line)
o
I B EIBE
1
Touches:o The two geometries have at least one point in common but their
interiorsdonotintersect.
o FT*******,F**T*****,orF***T****
o
I B EIBE ,
I B EIBE ,or
I B EIBE
Within:o Everypointof thisgeometry isapointof theothergeometryand the
interiorsofthetwogeometrieshaveatleastonepointincommon.
o T*F**F***
o
I B EIBE
8of85
1.1.1. OverlayOperations:Beingable to test theexisting relationshipsbetweengeometries isextremelyuseful fordoinganalysis,butmanytimesyouneedtoalterthegeometriesthemselves.Frequentlyyouwanttouseothergeometriestoaccomplishthis.Considerthecaseofaclippingoperation.Inthefigurebelow, the rivers extend beyond the boundaries of the state of Texas. Using an overlayoperationisexactlythekindofoperationthathelpswiththiskindofcalculation.Thesearenotlimitedtospecificscenarioslikepolygontopolygon.Insteadthesameterminologyappliestoallthegeometriesusingthefollowingdefinitions.
Figure2:BeforeandAfterClippingRiverstoTexas
Difference:o ComputesaGeometryrepresentingthepointsmakingupthisgeometry
thatdonotmakeuptheothergeometry.
o
9of85
Intersection:o Computesageometryrepresentingthepointssharedbythisgeometry
andtheothergeometry.
o SymetricDifference:
o Computesageometryrepresentingthepointsinthisgeometrythatarenotpresentintheothergeometry,andthepointsintheothergeometrythatarenotinthisgeometry.
o Union:
o Computesageometryrepresentingallthepoints inthisgeometryandtheothergeometry.
o
10of85
1.2. Exercise1:AssembleaMapProject
Putting together a GIS project has never been easier. Even a novice developer can takeadvantageofour readybuiltmapping controls,dragginganddropping themontoa solution.Becausethecomponentsarelargelyindependent,theycanberearrangedindifferentlayouts,or used separately. Furthermore, the extensive use of interfaces for the controls allows acontrol likethemapcontroltobeused interchangeablywithalternatecontrolsthatact likealegend.
In this firstexercise,wewill take theassembly stepby step. Ifyouhaveneverworkedwithanything besides the built in .Net controls, this exercise will be useful because it willdemonstratehowtoaddtheMapWindowcomponentstoyourvisualstudiodevelopertoolbox.Itwillalso show thebasicway that themost fundamentalmapcontrolscanbeadded to themap.
1.2.1. Step1:StartaNewC#ApplicationThefirststepoftheexerciseistocreateabrandnewapplication.Ratherthanworkingwithanexisting application, the goal here is to show that getting from a blank project to a fullyoperational GIS takes only a few minutes in order to add the components and link themtogether.Inaddition,noprogrammingcodeisrequired.Togettonewprojectdialoginvisualstudio, simply navigate to File, New, and choose Project from the context menu. This willdisplaytheNewProjectdialogdisplayedinfigure1.
Figure3:NewProjectDialog
11of85
Change thenameandpath tosomethingappropriate. In thiscase,wechoseBuild_A_MapandC:\dev\DotSpatialDev\Tutorial\Components\Ex1.MakesurethattheProjecttype isVisualC#andWindows.EnsurethattheTemplateissettoWindowsFormsApplication.ThenclickOK.
1.2.2. Step2:AddMapWindowComponentsThefirststep inanyproject istoensurethatyouhave loadedallofthedesignercontrolsandcomponents into theMapWindow toolbar. As this tutorialwascreated in thealpha stageofdevelopment youwillnotice thatnot allof the controlshaveunique representative iconsorotherhelpfulinstructions.Thereisalsoalargeassortmentofextracontrolsthatwereusedfordesigning MapWindow 6.0 that we may choose to remove from the toolbox for the publicrelease.Howeverthebasictechniquewillremainthesame.First,wewanttocreateanewtabtostoretheMapWindowtools. YoucandothisbyrightclickingonthetoolboxandselectingtheAddTaboptionfromthecontextmenu.
Figure4:AddMapWindowTab
Thiswillallowyoutoeditthenameofthetab. WechosetonamethetabMapWindowsothatwecouldeasilykeepthecontrolsfromtheMapWindow librarytogether. OnceyouhaveaddedaMapWindow tab, youwillwant to right click in theblank spacebelow that tabandselectChooseItemsfromthecontextmenu.
12of85
Figure5:ChooseItems
Thechooseitemsoptionlaunchesanewdialogwhichwillallowyoutoselectfromvariouspreloaded .Net controls aswell as some COM controls. However,we are going to use a thirdoption,andbrowsefortheDotSpatial.Desktop.dllfile.
Figure6:Browse
This, in turn, launches a file browser, and you will have to navigate to wherever theDotSpatial.Desktop.dll file is found on your local machine. On this machine it was in theC:\Dev_II\dotspatial\Releasefolder.
13of85
Figure7:SelectDotSpatial.dll
Onceyouhavechosenthisdocument,itwillcausea largenumberof tools tobeaddedtoyourtoolbox,asisillustratedinthefiguretotheright.
Figure8:MapWindowTools
1.2.3. Step3:AddMenuandStatusStripsAddinga.NetMenuStripisafastwaytogiveaccesstoaveryversatilenumberoftools,options,orothercapabilities. This isnot inanywayrequiredbytheMapWindowGIScomponents,butratherissimplyaconvenientstartingpointforanewapplication.TheMenuStripisfoundundertheAllWindows Forms tab in the toolbox. Simplydrag theMenuStrip listed thereonto themainform.
14of85
Figure9:DragaMenuStrip
Nextwewill switchback to theMapWindow controlsandadd two controls thataredirectlyassociated with the MapWindow components. The first is the SpatialToolStrip, which listsseveralbasicGISfunctionslikeaddingdatalayers,switchingbetweenzoomandpanmode,andzoomingtothefullextent.ThesecondistheSpatialStatusStrip.
Figure10:AddStatusandToolStrips
15of85
1.2.4. Step4:AddtheMapNow that theperipheralcontrolshavebeenadded,wecanstartadding thecontrols thatwillworkwithinthecentralpartofthemapproject.Inordertocleanlydivideupthescreenareaswith a minimum of custom programming, we will take advantage of a .Net SplitContainercontrol.Thiswilldividethecontentintotwoseparatepanelsthataresizeablebytheuser.
Figure11:AddaSplitContainerControl
Figure12:AddaMap
16of85
Oncetheseparatepanelsexist,wecanaddthemaptotheproject. Whenaddingthemap, itwill likelybethewrongsizeforthepanelthatwecreated. Inordertoallowtheusertoresizethemapso that italways is the rightsize for thepanel,change theDockproperty toFill.Thiscanbedonebychoosingthecentralrectangleinthedropdowneditorthatappearsinthepropertygridwhenyouclickonthedownarrow.
1.2.5. Step5:AddtheLegendandToolboxBecausetheLegendandToolboxcanbothexist insupportofthemap,and it isnotcriticaltohavebothofthesetoolsvisibleatthesametime,forthisprojectwewilltakeadvantageofthe.NetTabcontroltohelpreusethesamespacemoreeffectively.Becausethesecomponentsareinterchangeable,theTabcontrolisnotnecessary,andsecondsplitpanel,fixedpanels,oreventhirdpartydockingpanelsareallacceptablealternativesthatwillnotaffecttheproperbehaviorofthemap,legendortoolbox.
Figure13:AddaTabControl
Inthisinstanceweaddedthetabcontroltotheleftpanel,andchangedthetextonthetwotabstoreadLegendandToolbox.Thiscanbedonethroughthepropertygridthatappearswhenyouactivatethetabcontrolbyclickingonitafterithasbeenaddedtothemainform.
17of85
Figure14:AddLegend
Addingthe legendfollowssimilarrulestoaddingthemap. YoucansimplydragthisontopofthetabcontrolwhentheLegendtabisselected.Thiswillautomaticallytellthedesignerthatthe legendcontrolwillonlyappearwhentheLegendtab isselected. Likethemap,the legendshouldhaveitsdockpropertysettofillinordertotakeadvantageofthesplittercontrolsabilitytoresizethelayout.
Figure15:AddaToolbox
Althoughwearenotgoingtoenablethetoolboxinthisexercise,itwouldbeagoodideatoaddone. Thiswillenableus todirectlyuseour currentprojectas the startingpoint for thenextexercise. Toadd the toolbox,simplyswitch the tabcontrol to theToolbox tab. Then,draganddroptheToolManager.Likethelegendandthemap,youwillwanttosetthedocktofull.Onceyouhavedone this,selectback to theLegend tabso thatwhen theapplicationstarts itdefaultstoshowingthelegend,ratherthanthetoolbox.
18of85
1.2.6. Step6:LinkItAllTogether
We could technically run the project rightaway, but it would not appear to doanything.Theadddatabutton,forinstancemighthappilyopenafiledialog,butnothingwould happen when it was finished. Inorder for the status strip to showupdatesfrom themap,and inorder for the legendtoshowthe layers fromthemap,weneedto link things together. The map has aproperty for the Legend andProgressHandler. Settheseto legend1andmwStatusStrip1respectively.
Figure16:LinkMap
Figure17:LinkToolStrip
19of85
Thenext step is to link the tool strip to themap. This canbedoneby simplyactivating themwToolStrip,choosing theMappropertyand selectingmap1. Inorder for theapplication tounderstandwhat todowith thedata, a system reference to theDotSpatial.Data.dllmustbemade. This .dll is located in thesame fileas theDotSpatial.Desktop.dll thatwas reference toaccesstheGIScontrols. Nowthattheproject isconnectedtogether,wecanstartourprojectandrunitonsometestdata.
Thefirstthingtodoistogetsomedata.Foroursample,almostanydatainshapefileformatwilldo,butinthespiritofimprovingonlinedataawareness,thisbookfeaturesmanyonlinedatasourcesthatshouldprovideuptodateGISdata.
HelpTipSometimeslinkscanbecomebrokenoroutofdate.Incaseslikethis,itisoftenusefultolookatthefirst
partoftheaddressandthensearchfordatamanually.Example:insteadof
http://www.census.gov/geo/cob/bdy/co/co00shp/co99_d00_shp.zip ,youcoulduse
http://www.census.gov
?
Therawdatainthiscaseisstoredintheformofazipfile.Mostmodernoperatingsystemscanunzip filesautomatically,but in theevent thatyouneedanunziputility,a free,open sourceutility called 7zip is available for download from http://www.7zip.org. Once you havedownloadedandextractedtheshapefiles,youwillseea.shp,a.shxanda.dbffileallwiththesamenamebeforetheextension.ThisisthebasicfileformatknownasanESRIshapefile,andisacommonlyusedformatforGISanalysisbecauseitisportableandhasanopenstandardandsoiswidelycompatiblebetweendifferentGISsoftwarevendors.
20of85
Figure18:CensusData
The figureabove illustrates theviewof thecontinentalUnitedStates. Because thedataalsoincludescountiesinHawaii,AlaskaandPuertoRico,itwillbenecessarytozoomalittletozeeaviewliketheoneabove.ThemapstartsautomaticallyinthePanmode.Inthismode,youcanclickonthemapwithyourleftmousebuttonanddragthemapinadirectiontohaveitupdatethe view. You can also use the mouse wheel to zoom in or out of the scene. The basicoperationfollowstheoperationoftheUserssectionforMapWindow6.0,andsoyoucangetamuchmoredetailedpictureofwhatispossiblewithyourmap.
21of85
1.3. Exercise2:SimplifyAustraliaDataLayers
1.3.1. Step1:DownloadDataForthisexercise,weneedsomethematicvectorlayersthatrepresentmorethanjustpolygons.In honor of the Sydney Free and Open Source Software for Geospatial (FOSS4G) 2009Conference,forwhichthisdocument isbeingwritten,IamdownloadingsomebasicAustraliandatasets. SometimesbasicGISdata isofferedonsites for free inthehopesofpromotingthedatawithgreaterdetail.
http://www.usgsquads.com/prod_digital_international_vector_maps.htm
Forthisexercise,wedownloadedtheAUSCities,AUSLakes,AUSPolitical,AUSPopulatedAreas,andAUSMajorTransportationshapefiles.Thesefilesarestoredinzipformat,soyouwillhaveto unzip them first (see exercise 1). I found that the cities shapefile in this example wasmisleadingbecause itdoesnotcontainanyofthemajorpopulatedcityareas. Instead,beforewedoanyprogrammaticsymbolizing,wecangetbetterpointsthatareabetterrepresentationof the cities from the polygons that are populated areas. To do this, you can use theMapWindow6.0applicationtoconvertthepopulatedareaspolygonsintocities.
1.3.2. Step2:CalculatePolygonAreas
Figure19:AddData
After clicking the green plus to open a file dialog, browse for theaustralia_populated_areas.shpshapefileyoujustdownloadedandextracted.Whenitopens,you should see the polygons that represent large city areas, mostly at the outer limits ofAustralia.Sincethepolygonsaresmallcomparedtothesizeoftheentirecontinent,wecanseethatthecityregionsareinfactpolygonsbyzoomingintotheSydneyarea.
22of85
Figure20:SydneyPolygon
Wewill eventually like tobe able to distinguish the largest cities. Because thedownloadedpolygons dont contain any information about the population or area,wewill use the areacalculationtooltocalculateareasforeachofthepolygons.Theunitsoftheareawillbelargelymeaninglessbecause the linearunitsare indecimaldegrees,but thevalueswillbeuseful forseparatingthe largercitiesfromthesmallones. Toseethetoolbox,simplychangethetabtotheToolboxtab.
Figure21:CalculateAreas
HelpTipSincethisexercisewasconstructedusingaprereleaseversion,laterversionsmightnothavethesamelayout.Viewingthetoolboxmightbean
optionmadeavailablethroughtheViewmenu,soifthetoolboxtabisnotobvious,checktheviewmenu
foranoptionforaddingthetoolboxtab.
?
Theresultingshapefilehastobereaddedtothemap.Inthiscase,anewfieldhasbeenaddedto the resulting shapefile that shows the area. While this isnot asuseful aspopulation forselectinglargecities,itatleastshouldgiveusanothertooltoworkwith.
23of85
Figure22:NewlyAddedAreas
1.3.3. Step3:ComputeCentroids Nowthatwehaveawaytoatleastorderthecitiesbywayofareas,wecannowcreateasimplecitieslayerfromtheexistingpolygons.Wecandothisbyusingthecentroidtool.
Figure23:CalculateCentroid
Theshapefilecreatedbycalculatingthecentroidswillnowbeagoodrepresentationofthecitylocationsforbuiltupareas,andinaddition,itwillgiveusanapproximatemeasureofthesizeofthebuiltupareausingtheareaattribute.
24of85
Figure24:TooManyCities
1.3.4. Step4:SubsamplebyAttributesAscanbeseenfromthe figureabove,therearea fewtoomanycitiesvisibletomakeagoodmap. In order to build a cities shapefilewith just the largest cities,we can add the newlycreatedcitiesshapefiletothemap.Wecanthenusetheselectbyattributesability,andinthiscasechoose[Area]>.01asthecriteria.
Figure25:Area>.01
25of85
Figure26:CreateLayer
Inordertocreateanewlayerwiththefeatureswehaveselected,wecanrightclickonthecitieslayerinthelegend.ByhighlightingtheSelectiontabinthecontextmenu,wegaintheabilitytocreatealayerfromtheselectedfeatures.Thiswillcreateanewinmemoryshapefilethatisnotyetassociatedwithatruedatalayer.
1.3.5. Step5:ExportLayertoaFile
Figure27:ExportLayer
Exporting the layerwill save thisnewly created city layerwith just the citieswith the largestareas.
1.3.6. Step6:RepeatwithRoadsLayerBecausetheroadsshapefileisactuallyquitelarge,wemightwanttolimitthatshapefileaswell.
26of85
Figure28:PrimaryRoads
1.3.7. Step7:SelectPoliticalBoundsbyClicking
Figure29:SelectMajorAreas
Selectingbyattributes isnottheonlywaytonarrowdownthefeaturesthatyouwanttouse.First,make sure that the layer youwant to interactwith is selected in the legend. Thiswillpreventcontentfromotherlayersfrombeingselectedatthesametime.Nextyoucanactivatethe selection toolbyusing thebutton in the toolstrip indicated in the figureabove. Holdingdownthe[Shift]keyallowsyoutoselectmultiple layersatonetime. Onceyouhaveselectedthemajorpolygons,createanew layerthesamewaybyusingthecreate layerfromselectionoption inthe legend. Finally,exportthedatatocreateasimplifiedcontinentalshapefile. ThiswillmakelabelingexerciseseasierbecausetheresultwillnotbeclutteredbylabelingthesmallislandsaroundAustralia.
27of85
Figure30:ActivateLabeling
1.3.8. Step8:ApplyLabeling
Figure31:ApplyLabels
28of85
Figure32:AppliedLabels
29of85
1.4. ProgrammaticPointSymbologyUnliketheprevioussection,wherewewereassumingthatthereaderwouldperformeachstep,in this section,wewillexplore themostbasic featuresof theextremelypowerful symbologytoolkitprovidedbyDotSpatial,but listedundercompletely independentobjectives. Thesearesubdivided into 5 basic categories: Points, Lines, Polygons, Labels, and Rasters. Acomprehensivesetofcascading forms launched from theLegendprovideabuilt insystemsothat users can get started editing symbology right away using the built in components.However, thissection isnotaboutmastering thebuttonson thedialogs. Rather, thissectionmakestheassumptionthatyouareeitherwritingaplugin,orelsearebuildingyourownGISsoftwareusingourcomponents.Insuchacase,youmightwanttobeabletoautomaticallyaddcertaindatasets,andcontrolthesymbologyautomatically,behindthescenes.
InpreviousversionsofMapWindow,setting thecolorof theseventhpoint in theshapefile toredwasextremelysimple,butthetradeoffwasthatanythingmorecomplexwasnotinherentlysupported in thebaseprogram. Instead,developerswouldhave towrite theirown code tomake symbolize the layer based on attributes. MapWindow 6 introduces thematic symbolclassesthatonthesurfaceappeartobemuchmorecomplicated.However,wewillshowthataccessorshavebeenprovidedtostillalloweasyaccesstothesimpleststeps,butalsoprovideabasicstructurethatmakessymbolizingbyattributesmuchsimplerthaninpreviousversions.
Tobeginthisexercise,wewillneedthedatasetscreatedaspartofexercise2.Wewillalsobeworkingwithacopyofthevisualstudioprojectthatwecreatedinexercise1,tohammerinthepointthatyoudonotneedtobeworkingwiththeMapWindow6executable,butrathercanbeworkingdirectlywiththecomponentsinanewproject.Thefirststepistoexploreaddingdatatothemapprogrammatically.
1.4.1. AddaPointLayer
AddAPointLayerToTheMapObjective:
FeatureSet fs = new FeatureSet();
fs.Open(@"[YourFolder]\Ex3\Data\CitiesWithAreas.shp");
IMapFeatureLayer myLayer = map1.Layers.Add(fs);
Thethreelinesofcodeaboveareallthatisneededtoprogrammticallyaddthecitieswithareasshapefile to themap. The first line creates an external FeatureSet class. This is useful foropeningandworkingwithshapefiles.Thesecondlinereadsthecontentfromthevectorportionoftheshapefileintomemory.The@symboltellsC#thatthelineshouldbereadliterally,andwont use the \ character as an escape sequence. You can substitute [YourFolder]with thefolder containingtheseexercisesonyourcomputer. Finally,the last lineaddsthedatatothemap,andreturnsalayerhandlethatcanbeusedtocontrolthesymbology.Icanaddthelines
30of85
ofcodeaboveinthemainformbyoverridingtheOnShownmethod.Thatway,whentheformisshownforthefirsttime, it launchesthemap. TheFeatureSetvariablegivesusaccesstoalltheinformationstoreddirectlyintheshapefile,butorganizedintofeatureclasses.
Figure33:FeatureSetandFeatures
Thesimplifiedclassdiagramsfromabovegiveanideaofwhatkindsofinformationyoucanfinddirectlyon theFeatureSetclass,or inoneof the individualFeatures. TheDataTablepropertyreturnsastandard.NetSystem.Data.DataTable,filledwithalloftheattributeinformation.ThistableisalsousedbytheSelectByAttributeexpression.TheEnvelopeisthegeographicboundingboxfortheentiresetoffeatures.TheFeaturespropertyisthelistoffeaturesthemselves.Thisis enumerable, so you can cycle through the list and inspect each of the members. TheFeatureTypesimplytellswhetherornottheFeatureSetcontainspoints,linesorpolygons.
TheothersignificantvectordataclassshownhereistheFeature.TheBasicGeometryclasslistsallofthevertices,organizedaccordingtoOGCgeometricstructures,suchasPoints,LineStrings,Polygons, andMultiGeometriesof the various types. Becausewewere interested inmakingextensibledataproviders,wedidnot require thesebasicgeometricclasses to supportall themathematicaloverlayand relateoperations thatcanbe found in thevarious topology suites.Instead,theroleoftheBasicGeometryistoprovidethedataonlyinterface.
31of85
Wedidnotoverlook thepossibilityofwanting toperform,say,an intersectoperationwithanother feature. Insteadofbuilding themethoddirectly into the featureclass,wehaveinsteadbuildextensionmethods so that fromaprogrammatic viewpoint, itwill look likeanyIFeaturewillbeabletoperformIntersectioncalculations.
Figure34:ExtensionMethod
Typingaperiodafteraclassin.Netwilldisplayanautomaticlistofoptions.Continuingtotypenormallyfiltersthislistofoptions,sothatyoucanveryrapidlynarrowthedisplayeditemsandreducethechanceforspellingmistakes.Italsogivesyouaninstantbrowsewindowtoexplorethe options on a particular class. This autocompletion tool is referred to as MicrosoftIntellisense. Theexactappearanceofthisfunctionwilldependontheversionofvisualstudio,aswellaswhetherornotyouhaveanyextensions likeReSharper loaded. IfXMLcommentshavebeengeneratedfortheproject,(whichtheyhavebeenforMapWindow6.0)youwillnotonly see themethods,propertiesandeventsavailable,butyouwillalso seehelp foreachofthesemethodsthatextendstotheright.
Methodsareidentifiedbyhavingapurplebox.Extensionmethodsarerepresentedbyapurpleboxwithabluearrowtotherightofthatbox. Insteadofhavingtheprogrammingcodebuiltintotheclass,thecodeisactuallyseparate,inanexternalstaticmethod.Usingthistechnology,itbecomeseasy toassociateabehavior like Intersectsdirectlywith the feature,butwithouteveryexternaldataproviderhavingtorewritetheintersectioncodeitself.
32of85
1.4.2. SimpleSymbols
MakeYellowStarsObjective:
private void MakeYellowStars(IMapFeatureLayer myLayer) { myLayer.Symbolizer = new PointSymbolizer(Color.Yellow, PointShapes.Star, 16); } Becauseweknow inadvancethatweareworkingwithpoints,wedonthavetoworkdirectlywiththeexistingclasses,orusecasting.Wecansimplyusetheconstructor.IfwepassmyLayerfromtheearliercode intothemethodabove,wewillautomaticallycreatetheoutpointshowninthefollowingimage.
Figure35:YellowStar
Onethingthatyoumightnoticeisthatthebordersofthestarsarehardtoseebecauseweonlyspecifiedonecolor,andthatcolorwasthefillcolor.Inordertogivethestarsblackoutlines,weneedtocallaslightlydifferentmethod.
myLayer.Symbolizer = new PointSymbolizer(Color.Yellow, PointShapes.Star, 16); myLayer.Symbolizer.SetOutline(Color.Black, 1);
33of85
Figure36:YellowStarswithOutlines
Youwillnoticethatthe layerdoesnotcontrolthesecharacteristicsdirectly. Instead, itusesaclasscalledaSymbolizer.Symbolizerscontainallofthedescriptivecharacteristicsnecessarytodraw something. They have a few simple accessors that allow us toworkwith the simplesituations like theone listedabove. In thissituation,wearenotworriedaboutascheme,orcomplexsymbolsthathavemultiple layers. Amethod likeSetOutlinemayormaynotworkasexpectedineverycase,sincesometypesofsymbolsdonotevensupportoutlines.However,ifwe inspect theparameters thatwe can control above,we alreadyhave thebasic symbologyoptionsthatwereprovidedinpreviousversionsofMapWindow.
1.4.3. CharacterSymbols
UseCharacterSymbolsObjective:
Inadditiontothebasicsymbols,MapWindow6.0alsoprovidesaccesstousingcharactersasasymbol. This is a very powerful system since character glyphs are vectors, and thereforescalable. They look good evenwhenprinting to a large region athigh resolution. It is alsoincrediblyversatile.Notonlycanyouusepreexistingsymbolfonts(likewingdings)thatareonyourcomputer,thereareopensourcefontsthatprovideGISsymbols.Onehelpfulsitethathaslots of GIS symbol fonts that can be downloaded for free is found here:http://www.mapsymbols.com/symbols2.html. For this exercise, we are downloading andunzipping the military true type fonts from the site. Downloading and unzipping the fileproducesa filewith theextension .ttf,which isa true type font. Thenextstep is to find theFontsoptionintheControlPanel.
34of85
Figure37:FontsinControlPanel
Clickingonthisfolderwillopenthefoldershowingallofthecurrentlyinstalledtruetypefonts.Rightclickanywhere inthisfolderthat isnotdirectlyononeoftheexistingfonts,andyouwillexpose thecontextmenushown in the following figure. ChooseInstallNewFont. Youwillhavetobrowsetoyourrecentlydownloadedandunzipped.ttffile.InthiscaseweareusingtheMilitary.ttffile.
Figure38:RightClicktoInstallNewFont
35of85
Wecanverifythatthenewfont isavailabledirectlybyrunningMapWindow6.0,orournewlycreate program, adding a point layer, and then symbolizingwith character symbols. To usecharactersymbols,doubleclickonthesymbolinthelegend.ThiswillopenthePointSymbolizerDialog. There isaComboboxnamedSymbolTypewhichenablestheusertochooseanewsymboltype.Inthiscase,wewanttochooseCharacter.
Figure39:SwitchToCharacters
Figure40:ChooseMilitary
Onceyouselectmilitary,theiconslistedbelowinthecharacterselectiondropdownshouldbereplacedwith the newmilitary symbols thatwe have just downloaded. BecausemanyGIS
36of85
systemsusetruetypefonts,itispossibleforMapWindowtoshowfonttypesfromprecreatedprofessional fontsets. Havingverified thatwehavesuccessfullyenabled thesoftware tousethenewmilitaryfonttype,wewillnowattempttouseoneofthesesymbolsprogrammatically.Todrawplanes,wewillchoosethecharacterM,whichdrawsacharacterofaplane,andspecifytheuseof theMilitary fontname. Wecanalsospecify that theywillbeblueandwillhaveapointsizeof16.
myLayer.Symbolizer = new PointSymbolizer('M', "Military", Color.Blue, 16);
Figure41:MilitaryPlaneCharacters
Asasidenote,theMilitaryfontisslightlyabnormalinthatithasahugeamountofwhitespaceat the bottom of each glyph. Attempting to center the font vertically will cause problemsbecauseofallthewhitespace.Asaresult,anaddedlineofcodecatchesthispossibilityandusesthewidthforcenteringinstead.Sincethesesymbolsmaynotbeexactlysquare,thismayplacethemilitarysymbolsslightlyoffcenter. However,moreprofessionallycreatedsymbolswillbecenteredcorrectlysincetheywillhavearealisticheightvaluethatcanbeusedforcentering.Itis also possible to create custom glyphs for use as point symbols using various font editorsoftwarepackages. Agoodcommercialexample isFontCreator,whichhasa30dayfreetrialandcanbepurchasedforabout$100here:http://www.highlogic.com/download.html. Inthespiritofopensource,however,therearealsoopensourceoptionsavailablesuchasFontForge:http://fontforge.sourceforge.net/ and Font Editor: http://fonteditor.org/ both of which arecompletelyfree.
37of85
1.4.4. ImageSymbols
UseImageSymbolsObjective:
Sometimes,itsimplyisntpossibletoworkwithfonts,however,andanimageispreferable.Insuchacase,youcanusealmostanykindofimage.Rememberthatifyouhavelotsofpoints,itisbettertobeworkingwithsmallerimages.Asanexample,youcandownloadthiswikimediatigericontoworkwith:
http://upload.wikimedia.org/wikipedia/commons/thumb/f/f5/Tiger_Icon.svg/48pxTiger_Icon.svg.png
Tousethissymbolprogrammatically,firstdownloadthe imagetoafile. Onceyouhavesavedthe image file,you reference itusingeitherstandard file loadingmethods for images,orelseyoucanembed the fileasa resource tobeused. Wewill lookatembedding the imageasaresource.First,fromsolutionexplorer,addaresourcefilenamedImages.
Figure42:AddaNewItem
38of85
Figure43:Images.resxResource
ChooseResourcesFile from theavailableTemplates, thenname theresource file Images,andclickAdd. Fromsolutionexplorer,simplydoubleclickthenewlyaddedImagesresourcefiletoopenit.Addingitthefirsttimeshouldautomaticallyopentheresourcefileasatab.UndertheAddResourceoptioninthetoobarjustbelowtheImages.resxtab,chooseAddExistingFile
Figure44:AddanExistingFile
Thensimplybrowsetothefilewejustdownloaded,andaddittotheresourcefile.Tomakeiteasiertofind,wecanrenamethefileTiger.
39of85
Figure45:RenametoTiger
Now,wecanprogrammaticallyreferencethisimageanytimeusingtheImages.Tigerreference.Besuretobuildtheprojectafteraddingthe imagetotheresourcefile,orelsetheIntellisensewillnotshowtheTigerimageyet.AddingtheimagetoaresourcefilesetsuptheframeworkforthefollowinglineofcodewherewewillspecifytousetheTigerimageforthepointsymbology:
myLayer.Symbolizer = new PointSymbolizer(Images.Tiger, 48);
Figure46:TigerImages
40of85
1.4.5. PointCategories
UsePointSymbolCategoriesObjective:
Forthenext topic, Iwill introducetheconceptofcasting. Inmanycases,methodsorpropertiesaresharedbetweenmanydifferenttypesofclasses.Whenthatistrue,theinterfacemayprovide the sharedbase class, insteadof the class type that isactuallybeingused. Forinstance, if you are working with points, the Symbolizer that is being used should be aPointSymbolizer.ThishasasharedbaseclasswiththeFeatureSymbolizer.
Figure47:SymbolizerClassDiagram
Toillustrateinheritance,theclassdiagramaboveshowsthethreemainfeaturesymbolizers,oneforpoints,onefor lines,andoneforpolygons. What ismost importanthere isthattherearesome characteristics that will be shared. Properties, methods and events on theFeatureSymbolizerclasswillalsoappearoneachof the specializedclasses. Meanwhile,eachindividual typehasa collectionof classes thatactuallydo thedrawing,but these classesaredifferentdependingontheclass.Inthesameway,wecansetupcategories,butitworksmuchmoreeasily ifweknowwhatkindof feature layerweareworkingwith. Whenworkingwithcategories,schemes,andsoon,knowingthatweareworkingwithapointlayeristhedifference
41of85
betweenhavingtocasteverysingleobjecteverytime,andonlyhavingtocastthefeaturelayeronce.
WewillbesymbolizingbasedontheAreafield.Theareaswerecalculatedfromthepolygonsinexercise2,sowecanbeassuredthatthecitieswithareasshapefilethatweareaddinghasanAreafield,and lookingatthetablebelow,wecanseethatareasonablecutoffforpickingthelargestcitiesmightbe.01squaredecimaldegrees.
Figure48:LargeAreaCities
Thesourcecodethatwearegoingtousehasseveralpartstoit.First,wearegoingtocastthelayertoaMapPointLayersothatweknowweareworkingwithpointdata.Afterthat,wecreatetwo separatecategories,using filterexpressions to separatewhat isdrawnbyeachcategory.Finally,we add the new scheme as the layers symbology. When themap is drawn, itwillautomaticallyshowthedifferentschemetypesinthelegendusingwhateverwespecifyhereasthelegendtext.
IMapPointLayer myPointLayer = myLayer as IMapPointLayer; if(myPointLayer == null) return; PointScheme myScheme = new PointScheme(); myScheme.Categories.Clear(); PointCategory smallSize = new PointCategory(Color.Blue, PointShapes.Rectangle, 4); smallSize.FilterExpression = "[Area] < .01"; smallSize.LegendText = "Small Cities"; myScheme.AddCategory(smallSize); PointCategory largeSize = new PointCategory(Color.Yellow, PointShapes.Star, 16); largeSize.FilterExpression = "[Area] >= .01"; largeSize.LegendText = "Large Cities"; largeSize.Symbolizer.SetOutline(Color.Black, 1); myScheme.AddCategory(largeSize); myPointLayer.Symbology = myScheme;
42of85
Figure49:CityCategoriesbyArea
The square brackets in the filter expression are optional, but recommended to help clarifyfieldnamesintheexpression.Whatissignificanthereisthatwedidnothavetowritecodetoactually loopthroughallofthecityshapes,testtheareaattributeprogrammatically,andthenassignasymbolschemebasedonthecharacter.Instead,wesimplyallowthebuiltinexpressionparsingtotakeoverandhandlethedrawingforus.Thisallowsforprogrammerstoworkwiththeobjectsinawaythatdirectlymimicshowusersworkwiththesymbologycontrols.Andjustlikethelayerdialogcontrolsallowyoutospecifyschemes;thoseschemescanalsobecontrolledprogrammatically.
IMapPointLayer myPointLayer = myLayer as IMapPointLayer; if (myPointLayer == null) return; PointScheme myScheme = new PointScheme(); myScheme.Categories.Clear(); myScheme.EditorSettings.ClassificationType = ClassificationTypes.Quantities; myScheme.EditorSettings.IntervalMethod = IntervalMethods.Quantile; myScheme.EditorSettings.IntervalSnapMethod = IntervalSnapMethods.Rounding; myScheme.EditorSettings.IntervalRoundingDigits = 5; myScheme.EditorSettings.TemplateSymbolizer = new PointSymbolizer(Color.Yellow, PointShapes.Star, 16); myScheme.EditorSettings.FieldName = "Area"; myScheme.CreateCategories(myLayer.DataSet.DataTable); myPointLayer.Symbology = myScheme;
43of85
Figure50:QuantileAreaCategories
TherearealargenumberofsettingsthatcanbecontrolleddirectlyusingthePointScheme. Inthisillustrationtheclassificationtypeisquantities,butthiscanalsobeUniqueValuesorcustom.The categories canalwaysbeeditedprogrammaticallyafter theyare created,but this simplycontrolswhatwillhappenwhen theCreateCategoriesmethod isultimately called. Asof theSydneyalpharelease(Oct.2009)noteveryIntervalMethodissupported,butQuantileandEqualInterval are both supported. The interval snapmethods include none, rounding, significantfigures,andsnappingtothenearestvalue.Thesecanhelptheappearanceofthecategoriesinthe legend,but itcanalsocause trouble. In thisparticularcase,wehave toset theroundingdigitstoafairlyhighnumber(5)orelsemanycategoriessimplyshowarangeof00andhaveno members. With Significant figures, the IntervalRoundingDigits controls the number ofsignificant figures instead. Oneproperty isdeceptive in itspower. The TemplateSymbolizerpropertyallowsyoutocontrolthebasicappearanceofthecategories foranypropertythat isnotbeingcontrolledbyeitherthesizeorcolorramping.Forexample,ifwewantedtoaddblackborderstothestarsabove,wewouldsimplyaddthattothetemplatesymbolizer. Inthiscasewe chose to make them appear as stars and controlled them to have equal sizes sinceUseSizeRangedefaultstofalse,butUseColorRangedefaultstotrue.
44of85
Figure51:AvailableFeatureEditorSettings
Thesettingsshownintheexerciseaboverepresentasmalltasteoftheschemeoptionsthatareprogrammatically available. You can also control the color range,whetherornot the colorsshould be ramped or randomly created, a normalization field, an exclusion expression toeliminateoutliersandinthecaseofpolygons,aconsistentlyappliedgradient.
1.4.6. CompoundSymbols
YellowstarsinaBlueCircleObjective:
One of the new additions to how symbols work is that you are no longer restricted torepresentingthingsusingasinglesymbol. Complexsymbolscanbecreated,simplybyaddingsymbols to the Symbolizer.Symbols list. There are three basic kinds of symbols, Simple,Characterand Imagebased. Thesehave somecommoncharacteristics, like theAngle,OffsetandSize,whicharestoredonthebaseclass.Inthederivedclasses,thecharacteristicsthatarespecific to the subclass control those aspectsof symbology. For creatingnew symbols, theSubclasscanbeused. Forworkingwith individualsymbols inthecollection,youmayneedtotestwhattypeofsymbolyouareworkingwithbeforeyouwillbeabletocontrolitsproperties.
45of85
Figure52:PointSymbolClassDiagram
Theclassdiagramaboveshowstheorganizationoftheindividualsymbols.
PointSymbolizer myPointSymbolizer = new PointSymbolizer(Color.Blue, PointShapes.Ellipse, 16); myPointSymbolizer.Symbols.Add( new SimpleSymbol(Color.Yellow, PointShapes.Star, 10)); myLayer.Symbolizer = myPointSymbolizer;
Figure53:BlueCircleswithYellowStars
46of85
1.5. ProgrammaticLineSymbology
1.5.1. AddingLineLayers
AddLineLayerObjective:
Linelayersoperateaccordingtothesamerulesaspointsforthemostpart,exceptthatinsteadofindividualsymbols,wecanhaveindividualstrokes.Thedefaultsymbologyistohaveasinglelinelayerofarandomcolorthatisonepixelwide.
FeatureSet fs = new FeatureSet(); fs.Open(@"[Your Folder]\Ex3\Data\MajorRoads.shp"); IMapFeatureLayer myLayer = map1.Layers.Add(fs);
Figure54:AddLineLayer
SimpleLinesymbols
BrownRoadsObjective:
private void BrownRoads(IMapFeatureLayer myLayer) {
myLayer.Symbolizer = new LineSymbolizer(Color.Brown, 1); }
47of85
Figure55:BrownLines
1.5.2. OutlinedSymbols
YellowRoadswithBlackOutlinesObjective:
The line symbology is similar to the point symbology in that it also shares certain shortcutmethods like SetOutline. The distinction is that unlike the simple symbol, strokes cannotcomepreequippedwithanoutline.Instead,theappearanceofanoutlineiscreatedbymakingtwopasseswithtwoseparatestrokes.Thefirststrokeiswider,andblack.Thesecondstrokeisnarrowerandyellow.Theresultisasetoflinesthatappeartobeconnected.Inordertogetacleanlookattheintersections,alltheblacklinesaredrawnfirst. Then,alltheyellowlinesaredrawn.Thisway,theintersectionsappeartohavecontinuouspathsofyellow,ratherthaneveryindividualshapebeingterminatedbyacurvingblackoutline.
LineSymbolizer road = new LineSymbolizer(Color.Yellow, 5); road.SetOutline(Color.Black, 1); myLayer.Symbolizer = road;
48of85
Figure56:YellowRoadswithOutlines
1.5.3. UniqueValues
RoadsColoredbyUniqueTileIDObjective:
Oneof themoreusefulabilities is tobeable toprogrammaticallyapplysymbologybyuniquevalues,withouthaving toworryaboutwhat thosevaluesareornegotiate theactual color ineach case. Simply specifya classification typeofUniqueValuesanda classification field,andMapWindowdoestherest.Inthiscase,thedefaulteditorsettingswillcreateahuerampwithasaturationand lightness intherangefrom .7to .8. Theeditorsettingscanbeusedtocontrolthe acceptable range using the Start and End color. There is a Boolean property calledHueSatLight. If this is true, then the ramp is created by adjusting the hue, saturation andlightnessbetweenthestartandendcolors.Ifthisisfalse,thenthered,blueandgreenvaluesarerampedinstead.Inbothcases,alpha(transparency)isrampedthesameway.
49of85
LineScheme myScheme = new LineScheme(); myScheme.EditorSettings.ClassificationType = ClassificationTypes.UniqueValues; myScheme.EditorSettings.FieldName = "tile_id"; myScheme.CreateCategories(myLayer.DataSet.DataTable); myLayer.Symbology = myScheme;
Figure57:RoadswithUniqueValues
1.5.4. CustomCategories
CustomRoadCategoriesObjective:
Inthepreviousexample,thelegendshowsacollapsiblefieldnameinordertoclarifythemeaningofthevaluesappearingforeachcategory.ThiscanalsobeaccomplishedmanuallybycontrollingtheAppearsInLegendpropertyon thescheme. If this is false,thecategorieswillappeardirectlybelowthelayer.Whenitistrue,youcancontrolthetextinthelegendusingthescheme itself. Showing thisprincipal inaction, in thissamplewewillshow thecode thatwillprogrammatically set up two categories, and also have them appear under a scheme in thelegend.
LineScheme myScheme = new LineScheme(); myScheme.Categories.Clear(); LineCategory low = new LineCategory(Color.Blue, 2); low.FilterExpression = "[tile_id] < 36"; low.LegendText = "Low"; LineCategory high = new LineCategory(Color.Red, Color.Black, 6, DashStyle.Solid, LineCap.Triangle); high.FilterExpression = "[tile_id] >= 36";
50of85
high.LegendText = "High"; myScheme.AppearsInLegend = true; myScheme.LegendText = "Tile ID"; myScheme.Categories.Add(low); myScheme.Categories.Add(high); myLayer.Symbology = myScheme;
Figure58:CustomLineCategories
1.5.5. CompoundLines
LineswithMultipleStrokesObjective:
Each individual LineSymbolizer is made up of at least one, but potentially several strokesoverlapping each other. The two main forms of strokes that are supported natively byMapWindow are Simple Strokes and Cartographic Strokes. Cartographic strokes have a fewmoreoptions thatallow forcustomdashconfigurationsaswellasspecifying linedecorations.Decorationsarebasicallyjustpointsymbolsthatcanappearattheendofthestroke,orevenlyarrangedalongthelengthofthestroke.
51of85
Figure59:StrokeClassHierarchy
In thisexample,wewill takeadvantageof severalpowerful symbologyoptions. Wewillusecartographicstrokesinordertocreatetwoverydifferenttypeoflinestyles.Inthefirstcase,wewillcreatebrownrailroadties. UsingthestandardDotoptionforasimplecartographic linewouldnotworkbecausethedotscreatedareproportionaltothe linewidth. However,withacustomdashpattern, it ispossibletosetthe linessothatthedashesarethinnerthanthe linewidthitself.Thetwonumbersusedinthedashpatterndonotrepresentoffsets,butratherthelengthsof thedash and nondash elements that alternate. This is convenient, since for ourrepeatingties,wereallyonlyneedtospecifytwonumbers.
The second layer of the symbol will be dark gray rails. In this case, the dash pattern iscontinuous,sowewillnotneed tochange it. However, therailsdontpersist thewholewayacrossthe linethewaythetiesdo. Instead,wewanttohavetwothin linesthatappearalongthepathwidth.Todothis,wetakeadvantageofaCompoundArray.Withthecompoundarray,youareexpressingtheactualoffsetsforthestartandendpositionsalongthecompoundarray,where0istheleftofthelineand1istheright.Insomecases,linesthataretwothinmaynotgetdrawnatall,sotrytoensurethatthewidthofthelinesrepresentedintheCompoundarrayworkouttobejustslightlylargerthan1toensurethatthelinesultimatelygetdrawn.
Inthecodebelow,thestartandendcapsarealsospecified.Bydefaultthesearesettoround,whichwillendupproducinggraycirclesateachoftheintersections.Byspecifyingthattheendcapsshouldbeflat,noextensionwillbeaddedtoendsofthelines.Roundedcapslookthebest
52of85
forsolid linesbecause itcreatesakindofrounded,buffered looktoroadsthatarewiderthanonepixel.
LineSymbolizer mySymbolizer = new LineSymbolizer(); mySymbolizer.Strokes.Clear(); CartographicStroke ties = new CartographicStroke(Color.Brown); ties.DashPattern = new float[] {1/6f, 2/6f}; ties.Width = 6; ties.EndCap = LineCap.Flat; ties.StartCap = LineCap.Flat; CartographicStroke rails = new CartographicStroke(Color.DarkGray); rails.CompoundArray = new float[]{.15f,.3f,.6f,.75f}; rails.Width = 6; rails.EndCap = LineCap.Flat; rails.StartCap = LineCap.Flat; mySymbolizer.Strokes.Add(ties); mySymbolizer.Strokes.Add(rails); myLayer.Symbolizer = mySymbolizer;
Figure60:MultiStrokeRailRoads
53of85
1.5.6. LineDecorations
LinesDecoratedbyStarsObjective:
One of the new features with this generation of MapWindow is the ability to add pointdecorations to lines. Each decoration has one symbolizer and can operate with severalpositioningoptions. Eachstrokecansupportmultipledecorations,so there isagreatdealofcustomizable patterns available. The decorations can also be given an offset so that thedecorationcanappearononesideofthelineoranother.Inthiscase,wewillbeaddingyellowstarstoablueline.
LineDecoration star = new LineDecoration(); star.Symbol = new PointSymbolizer(Color.Yellow, PointShapes.Star, 16); star.Symbol.SetOutline(Color.Black, 1); star.NumSymbols = 1; CartographicStroke blueStroke = new CartographicStroke(Color.Blue); blueStroke.Decorations.Add(star); LineSymbolizer starLine = new LineSymbolizer(); starLine.Strokes.Clear(); starLine.Strokes.Add(blueStroke); myLayer.Symbolizer = starLine;
Figure61:LineswithStarDecorations
54of85
1.6. ProgrammaticPolygonSymbology
1.6.1. AddPolygonLayers
AddaPolygonLayertotheMapObjective:
Polygon layers are another representation of vector content where there is an area beingsurroundedbyaboundary.Polygonscanhaveanynumberofholes,whicharerepresentedasinnerringsthatshouldnotbefilled.However,inordertorepresentashapelikeHawaii,whichhasseveralislands,asasingleshape,youwoulduseaMultiPolygoninstead.AMultiPolygonisstill considered to be a geometry and will respond to all of the geometry methods, likeIntersects. Wecanadd thepolygon shapefile the sameway thatweadded thepointor lineshapefiles.
Polygonsymbolizersareslightlydifferentfromtheothertwosymbolizersbecauseinthecaseofpolygons,wehavetodescribeboththebordersandtheinterior.Sincethebordersarebasicallyjust lines, rather than replicatingall the symbologyoptionsaspartof thepolygon symbolizerdirectly,eachpolygonsymbolizerreferencesalinesymbolizerinordertodescribetheborders.This isa similar strategy to reusing thePointSymbolizer inorder todescribe thedecorationsthatcanappearonlines.
FeatureSet fs = new FeatureSet(); fs.Open(@"[Your folder]\Ex3\Data\MajorBoundaries.shp"); IMapFeatureLayer myLayer = map1.Layers.Add(fs);
Figure62:AddMajorBoundaries
55of85
1.6.2. SimplePatterns
SpecifyBluePolygonsObjective:
Thesimplesttaskwithpolygons istosetthefillcolorforthosepolygons. Youwillseethat specifying only an interior fill creates a continuous appearance, since the normalboundariesareadjacentandallthesamecolor.
private void BluePolygons(IMapFeatureLayer myLayer) { PolygonSymbolizer lightblue = new PolygonSymbolizer(Color.LightBlue); myLayer.Symbolizer = lightblue; }
Figure63:BlueFillOnly
Figure64:WithBlueBorder
56of85
PolygonSymbolizer lightblue = new PolygonSymbolizer(Color.LightBlue); lightblue.OutlineSymbolizer = new LineSymbolizer(Color.Blue, 1); myLayer.Symbolizer = lightblue;
1.6.3. Gradients
FullLayerGradientObjective:
Oneofthemoreelegantsymbologyoptionsistoapplyagradient.Thesecanvaryintypefromlinear, tocircular to rectangular,with themost frequentlyused typeofgradientby farbeinglinear. If youwant to apply a continuous gradient across the entire layer, you can use thedefault category and simply specify the symbolizer. Unlike the previous examplewherewedirectly setup theoutline symbolizer, in thisexampleweare takingadvantageof the sharedmethodSetOutlinewhichdoesthesamething.Forpoints,thismethodcontrolsthesymbolsthemselves. For lines, this adds a slightly larger stroke beneath the existing strokes. Forpolygons,thiscontrolsthelinesymbolizerthatisusedtodrawtheoutline.Thegradientangleisspecifiedindegrees,movingcounterclockwisefromthepositivexaxis.
PolygonSymbolizer blueGradient = new PolygonSymbolizer(Color.LightSkyBlue, Color.DarkBlue, 45, GradientTypes.Linear); blueGradient.SetOutline(Color.Yellow, 1); myLayer.Symbolizer = blueGradient;
57of85
Figure65:ContinuousBlueGradient
1.6.4. IndividualGradients
ShapeSpecificGradientsObjective:
Anotherpossiblesymbologyistocreatethegradientssothattheyareshapespecific.Thisisnotreallyrecommendedinthecaseoflargenumbersofpolygonsbecausethedrawinggetslinearlyslower for each specific drawing call. You candraw thousandsofpolygonswithone callbyhaving only one symbolic class to describe all the polygons. In the case of a few hundredclasses, thisdistinction isnot reallynoticeable. To rapidlycreatedifferentcategories,wecantake advantage of the nam fieldwhich is different for each of themajor shapes thatweselectedaspartofexercise1inordertocreatethebasicpolygonshapefile.
58of85
Figure66:MajorBoundariesFields
PolygonSymbolizer blueGradient = new PolygonSymbolizer(Color.LightSkyBlue, Color.DarkBlue, -45, GradientTypes.Linear); blueGradient.SetOutline(Color.Yellow, 1); PolygonScheme myScheme = new PolygonScheme(); myScheme.EditorSettings.TemplateSymbolizer = blueGradient; myScheme.EditorSettings.UseColorRange = false; myScheme.EditorSettings.ClassificationType = ClassificationTypes.UniqueValues; myScheme.EditorSettings.FieldName = "nam"; myScheme.CreateCategories(myLayer.DataSet.DataTable); myLayer.Symbology = myScheme;
Figure67:IndividualGradients
1.6.5. MultiColoredGradients
59of85
CoolColorswithGradientObjective:
OnethingthatmayseemlessthanobviousisthatinthepreviousexercisewespecifiedthattheUseGradient property should be false. This does not prevent the template symbolizer fromhavingagradient.Instead,itpreventsthesymbolizerfromoverridingtheoriginal,presumablysimpler,templatewithagradientsymbol.Thegradientsymbolwillbecalculatedusingacolorfromthecolorrange,butthenwillmaketheupperleftalittlelighterandthelowerrightalittledarker. Thatway,youcanhavethesamesubtlegradientapplied,butstillusedifferentcolorsforeachcategory.Toboot,thedefaultpolygonsymbolizerhasaborderthatisthesamehue,butslightlydarker,whichtendstocreateaniceoutlinecolor.
PolygonScheme myScheme = new PolygonScheme(); myScheme.EditorSettings.StartColor = Color.LightGreen; myScheme.EditorSettings.EndColor = Color.LightBlue; myScheme.EditorSettings.ClassificationType = ClassificationTypes.UniqueValues; myScheme.EditorSettings.FieldName = "nam"; myScheme.EditorSettings.UseGradient = true; myScheme.CreateCategories(myLayer.DataSet.DataTable); myLayer.Symbology = myScheme;
Figure68:UniqueCoolColorsWithGradient
60of85
1.6.6. CustomPolygonCategories
CustomPolygonCategoriesObjective:
An important terminologydifferencehere thatwehavebeenusing is thedifferencebetweenSymbolizerandSymbology. WithSymbology,wearealwaysreferringtoascheme,whichcanhavemanycategories. WithaSymbolizer,weare talkingaboutcontrollinghow thoseshapesare drawn for one category. By default, all the feature layers startwith a scheme that hasexactlyonecategory,whichhasasymbolizerwithexactlyonedrawingelement(symbol,lineorpattern).TheSymbolizerpropertyonalayerisashortcuttothetopmostcategory.Ifyouhaveseveralcategories,itmaybebettertocontrolthesymbolizersexplicitlythantousetheshortcut.Labelshavebeenaddedtothelayerbelowinordertoillustratethatthetwopinkshapesareinfact shapes that startwithN. The actual labeling codewill be illustrated under a separatesectionunderlabeling.
PolygonScheme scheme = new PolygonScheme(); PolygonCategory queensland = new PolygonCategory(Color.LightBlue, Color.DarkBlue, 1); queensland.FilterExpression = "[nam] = 'Queensland'"; queensland.LegendText = "Queensland"; PolygonCategory nWords = new PolygonCategory(Color.Pink, Color.DarkRed, 1); nWords.FilterExpression = "[nam] Like 'N*'"; nWords.LegendText = "N - Words"; scheme.ClearCategories(); scheme.AddCategory(queensland); scheme.AddCategory(nWords); myLayer.ShowLabels = true; myLayer.Symbology = scheme;
Figure69:CustomCategories
61of85
1.6.7. CompoundPatterns
MultiLayerPatternsObjective:
Like the other previous symbolizers, polygon symbolizers can be built out of overlappingdrawingelements. In thiscase theyare referred toaspatterns. Themainpatternscurrentlysupportedaresimple,gradient,pictureandhatchpatterns.Simplepatternsareasolidfillcolor,whilegradientpatternscanworkwithgradientssetupasanarrayofcolorsorganizedinfloatingpointpositionsfrom0to1.Theanglecontrolsthedirectionoflinearandrectangulargradients.Hatchpatterns canbebuilt from anenumerationofhatch styles. Picturepatterns allow forscalingandrotatingaselectedpicturefromafile.
Figure70:PatternClassDiagram
Onethinginparticulartonoteaboutthisnextexampleisthatinallthepreviousexampleswithmultiplepatterns,wesimplyclearedoutthedefaultpatternthatwasautomaticallycreatedaspartofthesymbolizer.Whenweaddanewpattern,thenewpatterngetsdrawnontopofthepreviouspatterns,sothelastpatternaddedhasthehighestdrawingpriority.Inthecodebelow,thenewpatternhasitsbackgroundcolorsettotransparent,yetintheimagebelowweseethatthecoloringisredstripesagainstabluebackground.Thepatternbelowtheredstripepatternisthedefaultpattern,andwillberandomlygeneratedasadifferentcoloreachtime.
62of85
PolygonSymbolizer mySymbolizer = new PolygonSymbolizer(); mySymbolizer.Patterns.Add( new HatchPattern(HatchStyle.WideDownwardDiagonal, Color.Red, Color.Transparent)); myLayer.Symbolizer = mySymbolizer;
Figure71:Hatchpatterns
1.7. ProgrammaticLabels
LabelsObjective:
Forthefirstexamplewithlabels,wewillshowaddingyourowntextinawaysothatthesametextgetsadded toall the features. Thisuses thedefault settings,andyou can see from thedefaultsettings that there isnobackground,andeach labelhas the leftsidealignedwith thecenterpointbydefault.
IMapLabelLayer labelLayer = new MapLabelLayer(); labelLayer.Symbology.Categories[0].Expression = "Test"; myLayer.ShowLabels = true; myLayer.LabelLayer = labelLayer;
63of85
Figure72:AddingTestlabels
1.7.1. FieldNameExpressions
FieldNameLabelsObjective:
Thefieldname inthiscasedescribesthenameoftheterritory. Inorderforthenamefieldtoappearinthelabeltext,wesimplyencloseitinsquarebrackets.Thisputstogetheraversatilescenariowhereyoucanbuildcomplexexpressionswithvariousfieldnames. Youcanalsouseescapecharacterstocreatemultilinelabels.
IMapLabelLayer labelLayer = new MapLabelLayer(); ILabelCategory category = labelLayer.Symbology.Categories[0]; category.Expression = "[nam]"; category.Symbolizer.Orientation = ContentAlignment.MiddleCenter; myLayer.ShowLabels = true; myLayer.LabelLayer = labelLayer;
64of85
Figure73:FieldNameLabels
1.7.2. MultiLineLabels
MultiLineLabelsObjective:
Creatingmultiline labels issimple,sinceallyouhave todo isuse thestandard .Netnewlinecharacter,which inC# isaddedusingthe/n,while invisualbasicyouwouldcombinethetwostringswithavbNewLineelementbetweenthem. Therelativepositionofthemultiple lines iscontrolledbytheAlignmentpropertyonthe labelSymbolizer. Inordertominimizeconfusion,the labels follow the same organizationwith a scheme, categories and symbolizers. A filterexpressionalsoallowsustocontrolwhichlabelsareadded.
IMapLabelLayer labelLayer = new MapLabelLayer(); ILabelCategory category = labelLayer.Symbology.Categories[0]; category.Expression = "[nam]\nID: [Cnt_nam]"; category.FilterExpression = "[nam] Like 'N*'"; category.Symbolizer.BackColorEnabled = true;
65of85
category.Symbolizer.BorderVisible = true; category.Symbolizer.Orientation = ContentAlignment.MiddleCenter; category.Symbolizer.Alignment = StringAlignment.Center; myLayer.ShowLabels = true; myLayer.LabelLayer = labelLayer;
Figure74:MultiLineLabels
Multiple label categories canbe createdandadded to the scheme in the sameway that thefeaturesetswere able to add different categories. The labels also allow for the font to becontrolled,aswellasthetextcolor,backgroundcolorandopacityofeither.
1.7.3. TranslucentLabels
TranslucentLabelsObjective:
Thebackgroundcolor in thiscasehasbeenset to transparentbyspecifyinganalphavalueofsomething lessthan255whensettingtheBackColor. Frequently,thereareopacitypropertiesavailable inaddition to theactualcolor,but that is just there forserializationpurposesand issimplyashortcuttothealphachannelofthecolorstructure. Thisexamplealso illustratestheuseofthecompoundconjunctionORinthefilterexpression.Otherpowerfultermsthatcanbe used are AND and NOT as well as the combined expression Is Null which is caseinsensitiveandcanidentifynullvaluesseparatelyfromemptystringsforinstance.Noticethatis
66of85
not =nullwhichdoesntworkwith .NetDataTables. For thenegativeyou coulduse NOT[nam]isnull.
IMapLabelLayer labelLayer = new MapLabelLayer(); ILabelCategory category = labelLayer.Symbology.Categories[0]; category.Expression = "[nam]\nID: [Cnt_nam]"; category.FilterExpression = "[nam] = 'Tasmania' OR [nam] = 'Queensland'"; category.Symbolizer.BackColorEnabled = true; category.Symbolizer.BackColor = Color.FromArgb(128, Color.LightBlue); category.Symbolizer.BorderVisible = true; category.Symbolizer.FontStyle = FontStyle.Bold; category.Symbolizer.FontColor = Color.DarkRed; category.Symbolizer.Orientation = ContentAlignment.MiddleCenter; category.Symbolizer.Alignment = StringAlignment.Center; myLayer.ShowLabels = true; myLayer.LabelLayer = labelLayer;
Figure75:TranslucentLabels
1.8. ProgrammaticRasterSymbology
67of85
1.8.1. DownloadData
DownloadaRasterLayerObjective:
Inadditiontothevectordatathatwehavebeenlookingatsofar,MapWindowalsosupportsanumberofrasterformats.Rastersareconsidereddistinctfromimagesforusinthatthevisualrepresentation thatwe see is derived from the valuesmuch in theway thatwe derive thepolygon images from the actual data. With rasters, you typically have a rectangulararrangementofvalues thatareorganized in rowsandcolumns. Fordatasets thatdonthavecompletesampling,aNoDatavalueallowstherastertoonlyrepresentaportionofthetotalarea.
Becauseof theexistenceofextensibledata formatproviders, there isnoway to tell justhowmany formatsMapWindowwillsupportat the timeyouare reading this. Wehavecreatedapluginthat isexclusivetothewindowsplatformusingFrankWarmerdansGDAL librariesandC#linkagefiles.ThepluginexposesmanyoftherasterandimagetypessupportedbyGDALtoMapWindow 6, or any project that adds our ApplicationManager component. While thesituationmay change before the beta release, for the SidneyAlpha, only one grid format issupportednatively(thatiswithoutusingGDAL)andthatisabgdformat.Thisisnotaproblemfor independent developers because of our clever system that enables you to add a singleApplicationManager to the project and empower your own projectwith all the data formatextensionsthatworkwithMapWindow6.However,sincethatwontbecoveredatthisstageofthetutorials,wewillusetheMapWindow6applicationtoconvertarasterfiletotheformatweneed.AgoodproviderofGISdataistheUSGS.Theyprovidemanyformsofdatafromaroundtheworld,but in thiscaseweare interested inanelevationdataset. Ausefulwebutility forbrowsingthewebiscalledEarthExplorer.http://edcsns17.cr.usgs.gov/EarthExplorer/
68of85
Figure76:EarthExplorer
Ifthe linkabovedoesntwork,youcantrysearchingforUSGSand lookingfor linksthatallowyoutosearchfrodatabyregion.Themapapplicationisaneasytousesystemthatprovidesa1,2,3Datadownloadexperience that is tobeenvied. Unfortunately, the system isalsounderheavydemand,soyouwillhavetobeconservativewithyourrequestsfromthissite.
To get data, simply zoom into a region of interest and you will see that they have lots ofinterestingdatasets. For thisdemo, Iactivated theSRTMdata format,whichgivesusdigitalelevationinformation.Youwillhavetobearegistereduserinordertodownloaddatafromthissite,andnotallthedataisfree.Inthiscase,IdownloadedaBILfileforthisdemonstration,butother formatsareavailable, includingDTED. Both formatsare supportedbyMapWindowbyusingGDAL.Thedownloadedfilewillbezipped,soyouwillhavetounzipthefilebeforeyoucanopen itwithMapWindow6. Beforewecanworkwiththedataprogrammatically,wewilluseMapWindow6tochangethedataformattobgd.ThisisactuallyassimpleasopeningtheBIL,rightclickingonthelegendandchoosingexportdata.Dontworryifthecoloringlooksstrange.Itisusualforthenodatavaluestodistortthecoloringuntiltheycanbeproperlyexcludedfromthesymbology.Fornow,weareonlyconcernedwithconvertingtheformattoan*.bgdfile.
69of85
Figure77:ExportData
Figure78:SaveasBgd
Youwill see lotsofother formats available, and these are thewrite formats thathavebeenexposedbytheGDALplugin,plusanyformatsthataresupportedforrastersbyotherproviders.Youwillnoticethat*.bgdisattheendofthelist,andthatistheproviderthatwewillbeusingfortherestofthedemonstration.Savethedownloadedfileasabgdfile.
1.8.2. AddaRasterLayer
AddARasterLayerObjective:
70of85
Raster r = new Raster(); r.Open(@"[Your Folder]\Ex3\Data\DEM\Elevation.bgd"); IMapRasterLayer myLayer = map1.Layers.Add(r);
Onethingthatshouldbefairlyobviousrightawayisthatwhilesimilartothepreviousexamples,a raster is a completely different data object. Instead of working with features andconcentrating on ideas like geometries, rasters give you direct access to the numerical datastored ingrid form. Inheritanceatdifferent levels is certainlyused,butmostof thatoccursunder thehood. TheRasterclassgivesyoua friendlyuser interface thatworks regardlessofwhatkindofdriversareopperatingunderthehood.Theprimarybenefittoyouisthatwritingthecodebecomesalotsimplerbecauseyoudontneedtoworryaboutwhatkindofrasteryouareworkingwith.
Figure79:DefaultRaster
Onefairlyobviousdrawbackwiththesymbologyaboveisthatitisalmostcertainlybeingthrownoffbyanunexpectednodatavalue. Wecanusethesymbolizer interfaceforrasters ineitherMapWindow6.0oryournewprojectbydoubleclickingnexttotheelevationlayerinthelegend.Thiswilllaunchadialogliketheonebelow.
71of85
Figure80:Statistics
Wecanseerightawaythatofthemanysamplepointsthatweretaken fromthis image,onlyoneortwovaluesintheextremeupperrangeof32,000and65,000respectivelycanthrowofftheentiresymbolicrangeforthisraster.Wecanrepairthiseasilybyslidingthesymbolicslidersdowntotheleftendoftheplot.Whatislessobviousuntilyoustartzoominginisthatalmostallofthevaluesareeffectivelynodatavaluesof0andareshowinguponourplot. Youcanusethemousewheeltozoom intoandoutofhistogram,but inthiscase itwillbeverydifficulttoseewhat is goingon as long as the range includes zero. There is a trick thatwe can do inspecificallythissituation.Whatwewilldoismanuallyenterarangefrom1to250andfrom250to 600 in the editable values column in the data grid above the graph. Thiswont directlychangethegraph.Instead,itwillenableaninnovativefeaturetoworkonthegraph.AZoomToCategoriesoptionwhenrightclicking thegraphallowsus tozoom into therangespecifiedbythecategoriesabove.
72of85
Figure81:ZoomToCategories
Figure82:AfterZoom
We can see from the statistics here, that the large percentage of the points occur betweenabout1and150,witha sizeablehumpup toabout300. Wewillput thebreak slider in theminimum thatoccursataroundavalueof150,oryoucanuse150as theexact range in thevaluescolumnagain.Theresultisthatwecangetamuchmorecleanlysymbolizedrasterwhen
73of85
we are done. The nodata region is still white, but now we can see a much betterrepresentationofthevaluesthatwedohavesincewehaveeliminatedtheoutliners.
Figure83:AfterAdjustments
So inorder toset thisupprogrammatically,wewould like to firstofalledit the rangeof thecategoriesthatareautomaticallygeneratedwhenaddingthedatalayersothatwehavearangefrom1150andfrom150to800.
1.8.3. ControlCategoryRange
ControlCategoryRangeObjective:
Theonly thing tonoticewhen controlling the range is that you can control the range valuesindependently frommodifying the legend text. Inorder toupdate the legend textbasedonothersettings,wecanusetheApplyMinMaxsettings.Alternately,wecouldhavesetthelegendtextdirectly,justaswecanfortheothercategories.
private void ControlRange(IMapRasterLayer myLayer){ myLayer.Symbolizer.Scheme.Categories[0].Range = new Range(1, 150); myLayer.Symbolizer.Scheme.Categories[0].ApplyMinMax(myLayer.Symbolizer.EditorSettings); myLayer.Symbolizer.Scheme.Categories[1].Range = new Range(150, 800); myLayer.Symbolizer.Scheme.Categories[1].ApplyMinMax(myLayer.Symbolizer.EditorSettings); myLayer.WriteBitmap(); }
74of85
Figure84:ProgrammaticRestrictRange
1.8.4. ShadedRelief
AddLightingObjective:
myLayer.Symbolizer.Scheme.Categories[0].Range = new Range(1, 150); myLayer.Symbolizer.Scheme.Categories[0].ApplyMinMax(myLayer.Symbolizer.EditorSettings); myLayer.Symbolizer.Scheme.Categories[1].Range = new Range(150, 800); myLayer.Symbolizer.Scheme.Categories[1].ApplyMinMax(myLayer.Symbolizer.EditorSettings); myLayer.Symbolizer.ShadedRelief.ElevationFactor = 1; myLayer.Symbolizer.ShadedRelief.IsUsed = true; myLayer.WriteBitmap();
75of85
Figure85:WithLighting
1.8.5. PredefinedSchemes
UseGlacierColoringObjective:
There are several predefined color schemes that can be used. All of the preset schemesbasically use two separate ramps that subdivide the range and apply what is essentially acoloring theme to the two ranges. Those ranges are easilly adjustable using the rangecharacteristicson thecategory,butshouldbeadjustedafter theschemehasbeenchosen,orelseapplyingthenewschemewilloverwritethepreviousrangechoices.
myLayer.Symbolizer.Scheme.ApplyScheme(ColorSchemes.Glaciers, myLayer.DataSet); myLayer.Symbolizer.Scheme.Categories[0].Range = new Range(1, 150); myLayer.Symbolizer.Scheme.Categories[0].ApplyMinMax(myLayer.Symbolizer.EditorSettings); myLayer.Symbolizer.Scheme.Categories[1].Range = new Range(150, 800); myLayer.Symbolizer.Scheme.Categories[1].ApplyMinMax(myLayer.Symbolizer.EditorSettings); myLayer.Symbolizer.ShadedRelief.ElevationFactor = 1; myLayer.Symbolizer.ShadedRelief.IsUsed = true; myLayer.WriteBitmap();
76of85
Figure86:Glaciers
1.8.6. EditRasterValues
FixRasterValuesObjective:
Previously,wehavebeenusingtrickstocolortheelevationbutwherewedirectly ignoredthevalues thatwere either nodata values that read 0, or else apparently bad data values thatshowed impossiblevalues like65,000. Inthissectionwewillusetherasterdataclass itself inorder to repair the values programmatically. This will only alter the copy that we have inmemoryandwillnotoverwritethevaluestothediskunlesswespecificallyinstructittodoso.Intheexamplebelow,wecancyclethroughallofthevalues intherasterusingtheNumRowsandNumColumnspropertiestogiveusanideaofwhattheboundsareontheloops.TheValueproperty takesadouble index,andwillworkwithwhatever the realdata type isandconvertthatdatatypeintodoubles.Wecanusethistoquicklycleanupthevaluesontherasterbeforeweevercreatealayer.Wecanalsoassignthenodatavalueontherastersothatitmatchesthe0values thatcovera largeportionof the raster. Thiswillautomaticallyeliminate it from thestatisticalcalculationssothatourdefaultsymbologyshouldlookbetter.
77of85
Raster r = new Raster(); r.Open(@"C:\dev\MapWindow6Dev\Tutorial\Components\Ex3\Data\DEM\Elevation.bgd"); r.NoDataValue = 0; for(int row = 0; row < r.NumRows; row++) { for(int col = 0; col < r.NumColumns; col++) { if (r.Value[row, col] > 600) r.Value[row, col] = 600; } } IMapRasterLayer myLayer = map1.Layers.Add(r);
Figure87:DefaultSymbologyofFixedRaster
Thislooksalotbetter,andifwedoubleclickontheelevationlayer,wecantakealookatwhatthestatisticalplotautomaticallyshows. In thenext figure,wecansee that thedefault rangeshowsvaluesfrom1to600,anddoesnotincludeinthestatisticalsummarythevaluesthatwehavenow labeledasnodatavalues. Assigningthenodatavaluecanberiskybecausetheremaybevaluesthatwereusingtheoldnodatavalue.Thiscaneasilybefixedbycyclingthroughtherasterinthesamewayandadjustingvaluessothattheyworkwiththegivenstatistics.
78of85
Figure88:AfterFixingRaster
1.8.7. QuantileBreaks
QuantileBreakValuesObjective:
JustliketheFeatureSets,RasterscanusetheEditorSettingspropertyinordertocustomizehowtobuildschemes,ratherthanhavingtospecifytheschemesdirectly.Thisiswhereourpreviouseditstofixtherastervaluesbecomemore important. Ifwehadtriedtoapplyquantilebreaksbefore,insteadofcoloringtherasterappropriately,wewouldhavehadallbutoneoftherangesread00.Now,wegetareasonablerange.
myLayer.Symbolizer.EditorSettings.IntervalMethod = IntervalMethods.Quantile; myLayer.Symbolizer.EditorSettings.NumBreaks = 5; myLayer.Symbolizer.Scheme.CreateCategories(myLayer.DataSet); myLayer.Symbolizer.ShadedRelief.ElevationFactor = 1; myLayer.Symbolizer.ShadedRelief.IsUsed = true; myLayer.WriteBitmap();
79of85
Figure89:QuantileBreaks
Figure90:RasterSymbologyClasses
80of85
1.9. MapWindow4ConversionTipsIn this section,weassume that youmightbeadeveloperwith somepreexistingexperiencewithMapWindow 4. Because the underlying object libraries are very different, itmight beconfusingforaMapWindow4developertogetstartedworkingwiththeobjectsinMapWindow6.Themostchallengingideasinvolvetheintroductionofinheritanceandextensibleinterfaces.
1.9.1. Point
MapWinGIS.PointClass:
ThePointclasswasformerlyaclassthatprovidedrapidaccesstoX,YandZvalues.ThisclasshasbeenreplacedbytheCoordinateclass.APoint,asdefinedbytheOGCSimple Feature Specification, has geometry methods like Intersects, and isindependentlyavailable inMapWindow6,buthasmanymorecapabilitiesthat juststoringacoordinatelocation.Therefore,thecoordinateclasshastakenoverastheclasstouse.
1.9.2. Extents
MapWinGIS.ExtentsClass:
TheExtentsclassinMapWindow4wasaboundingboxthatdefinedatwoorthreedimensional region. The new class introduces a Minimum and a Maximumcoordinate,whichhastheX,YandZvaluesforthelowerandupperboundsineachcase. This also provides accessors for controlling the X, Y, Height and Widthproperties,whicharecalculatedfromtheMinimumandMaximumcoordinates.
81of85
1.9.3. Shape
The Shape class inMapWindow 4was a generic feature and providedbasicaccesstothecoordinates,andgavethegeographicextentsforthatshape.Intheoldmodel,theonlyconnectivitybetweenashapeand theattributeswasthattheywouldbothhavethesame index. Inthenewversion,aFeaturehasaDataRow,whichprovidesdirectaccesstotheattributesspecifictothisfeature.Italsohas theEnvelope,whichdescribes thebounds,andyoucandirectlyaccessthe coordinates. Because some features are complex, likemultipolygons, theBasicGeometryisprovided,whichorganizesthecoordinatesaccordingtotheOGCdefinitionslikePolygons,LineStrings,orPoints.
MapWinGIS.ShapeClass:
82of85
1.9.4. Shapefile
MapWinGIS.ShapefileClass:
InMapWindow4,therewasanassumptionthattherewasonly going to everbeone supported vector format, andthat formatwas the shapefile. InMapWindow 6.0, theintroduction of extensible data providers implies thatmanydifferentdata sourceswillbepossible. Therefore,the name FeatureSet seemed more appropriate.FeatureSet classes contain accessors to the Envelope, aDataTable of attributes, as well as a cached array ofvertices. The ShapeIndices class is a special shortcut toallow for effective use of the vertices class, and iscurrentlybeingusedtospeeduprenderingoperations.AReproject method is also available on the FeatureSet,which will change the inmemory coordinates withoutchangingtheoriginalfile.
Regardless of whether you are working with an image,raster, or featureSet, they derive from the same basicclass, called a DataSet. The DataSet provides simpleinformation like the Name, and Projection informationthat are shared across formats. Selection is supportedhere, but it should be understood that there is adisconnect between the featureset and the layer beingdrawn. Layers control how a particular DataSet issymbolizedanddrawninthemap.However,theabilityto
discoverthefeaturesthatarewithinanenvelope,orelsethathaveattributesthatmatchanSQLqueryissupportedandusedattheleveloftheFeatureSet.
The FeatureSet is interesting because it acts as both a base class, meaning that aPolygonShapefile ultimately inherits from FeatureSet, but it also acts as awrapper class. Inotherwords,when the user programmatically creates a new FeatureSet, there is noway toknowwhatkindsofclasseswillbenecessaryinordertoaccessthedataonafile,orpossiblyadatabaseorweb service. Therefore,weprovide the FeatureSet as a kindofwrapper for aninternalIFeatureSet.WhentheOpenmethodiscalled,internally,theFeatureSetclassrequestsanewIFeatureSetfromthedefaultDataManager.Anyrequestsforfeaturesorotherpropertiesaresimplypassedtotheinternalfeatureset.
83of85
1.9.5. Grid
MapWinGIS.GridClass:
The grid classwas awrapper class that could internally represent an integer,float,short,orevendoublegrid.Themaingoalofthegridclasswastobeabletocyclethroughtherowsandcolumnsofarasterdatafileandgetorsetthevariousnumericvalues.
Thenewrepresentation iscalledaRaster. UnliketheMapWindowGrid,Rasterscanhavemultiplebands,with eachband alsobeing aRaster. The vast setofpropertiestotheleftmayseemintimidating,butrealistically,thereareonlyafewproperties thatarecritical. The first is theValueproperty. This iswhere theactualvaluesarestored.Toaccessthevalueonrow7andcolumn6,youwouldsimplyaccessdoubleval=myRaster.Value[7,6]. Regardlessofwhatthesourcedata isstoredas, thevalueaccessedherewillbeconverted intodoublevalues.Thismakesiteasiertowritecode,becauseyoudonthavetohandleeachoftheseparatepossibilitiesindependently.
TheothercriticalvaluesareNumRowsandNumColumns.Thesearenecessarysothat you knowhow to cycle through the values form theValueproperty. ThefinalbitofinformationthatisespeciallyimportantistheBoundsproperty.Manyof the properties to the left are actually just shortcut accessors to theRasterBounds property. This iswhere the information is kept that stores thegeospatialpartoftherastercontent.WiththeBoundsproperty,youcancontrolthepositionofaraster inspace. TheNoDataValue isalsouseful,as itcanhelpchangehowstatisticsarecalculated.
84of85
1.9.6. GridHeader
MapWinGIS.GridHeaderClass:
TheHeaderwasan importantpartof thegrid. Itdefined thespatiallocationslikethelowerleftXandlowerleftYcoordinatesaswellasdefiningacellsize. Oneofthe limitationsoftheMapWindow4gridswasthattheydidnotsupportskewterms.InMapWindow6.0,theskewisfullysupportedanduses AffineCoefficients as the source of most of the other properties.However, inorder todefine theboundaries themselves, it isnotenough tosimplyhavetheaffinecoefficients,whicheffectivelydescribethecellsizeandskewrelationshipsaswellasthepositionoftheupperleftcell.Youalsoneedthenumberof rows and columns inorder to get a valid rectangle that canenclosetheentireraster.TheEnvelopeisarectangularformthatcompletelycontainstheraster.
1.9.7. Image
MapWinGIS.ImageClass:
The Image class was specifically designed for workingwith images, and was not really designed for dataanalysis. Thenew ImageData class supportsa Valuesmethodsimilartothevaluesofaraster,butisactuallyanarrayofbytevalues.Theformatoftheimagewillchangehow those byte values are organized. The Strideproperty is thenumberofbytes inagiven row. This isnotalways strictly related to thenumberofcolumnsassome image formats use algorithms that may requireslightly more columns than have actual data. TheBytesPerPixelgivesan ideaofwhetheryouareworkingwithaGrayValue,RGBorARGBimage.Withimages,thegeospatial location and sizing is controlled via aWorldFile.
85of85
1.10. ExtensionMethods
RastersExtensions
Notallofthemethodsaresupporteddirectlyonaraster.Manyusefulmethodsareactuallysupported inthe formofExtensionMethods. Fortheraster, this includes useful methods that can alter the raster bounds, likeTranslate,or Scale,orRotate. Butotheruseful abilities likeCreateHillShadeactuallyusetherastervaluesthemselves inordertocalculateafloatingpointvaluethathelpstocontroltheshadedreliefaspectofanyimagethatiscreatedfromaraster.OthermethodslikeGetRandomValues,andGetNearestValuearehelpful fordoing analysis,butoneof themost criticalmethods isCellToProjandProjToCell,whichallowsthedevelopertoeasilygobackandforthbetweengeospatialcoordinatesandtherowandcolumnindicies.
FeatureExtensions
TheFeature,andinfactanyclassthatimplementstheIFeatureinterfacewillbeextendedwiththegeometrymethodsthataresocriticaltovectorcalculations.These not only include the overlay operations like Intersection, Union andSymmetricDifference,butalltheteststhatyoumightwanttouse liketouchesorwithin.SomeofthebonusmethodsaremethodslikeArea,whichcalculatestheareasofpolygons.AnotherisCentroid,whichcalculatesthecenterofmassforgeometries.ConvexHullcanbeusedtosimplifyageometryinthesamewaythatyouwouldsimplifysomethingbywrappingitwithanelasticband.Itdrawsstraight lines past concave sections, and follows around with the convexportions. The Distance tool finds the minimum distance between twogeometries,and the IsWithinDistance simplychanges theDistancecalculationtotestitagainstathreshold.