86
Overview Topics in this section Introduction Relationship to MapGuide Geospatial Platform API Documentation Setting Up Visual Studio Sample Applications Please send us your comment about this page

AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

Embed Size (px)

Citation preview

Page 1: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

Overview

Topicsinthissection

IntroductionRelationshiptoMapGuideGeospatialPlatformAPIDocumentationSettingUpVisualStudioSampleApplications

Pleasesendusyourcommentaboutthispage

Page 2: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

Introduction

TheAutoCADMap3D2009GeospatialPlatformAPIisusedformanaginggeospatialdatainamap.ItsharesmanyclassesandmethodswithAutodeskMapGuide®EnterpriseandMapGuideOpenSource,soapplicationswrittenforoneproductcanworkinanotherwithminimalmodification.

TheGeospatialPlatformAPIisnotthesameastheAutoCADMap3DObjectARX.NETAPI.FordetailsaboutthisAPIseetheObjectARX.NETDeveloper’sGuideandtheObjectARX.NETAPIReference.

Pleasesendusyourcommentaboutthispage

Page 3: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

RelationshiptoMapGuide

ManypartsoftheGeospatialPlatformAPIaresharedbetweenAutoCADMap3DandMapGuideWebServerExtensions.Therearedifferencesintheproducts,though,thataffecthowtheAPIisused.

TheMapGuideAPIisdesignedtobeusedinawebserverenvironment,andisavailableinPHP,Java,and.NET.AutoCADMap3Disdesignedtobeusedinadesktopenvironmentandexposesonlya.NETAPI.

AutoCADMap3DstoressomeresourceinformationdirectlyintheDWGfile,whileMapGuideusesanexternalrepository.ThisisexplainedinmoredetailinResources.TheMapGuiderepositoryisstructuredlikeafilesystem,withahierarchyoffolders.Toensureasmuchconsistencybetweentheproductsaspossible,AutoCADMap3Dusesasimilarstructureforitsinternalrepository.

SomemethodsintheGeospatialPlatformAPIarenotvalidinAutoCADMap3D,andwillthrowanexceptionifcalled.GenerallythesewillbemethodsthatdonothavecorrespondingfunctionalityintheAutoCADMap3Denvironment.Forexample,AutoCADMap3Ddoesnothavetheconceptofpermissionsonresourcessoanymethodsdealingwithpermissionsareinvalid.TheseareidentifiedintheAPIReference.

AllmapdatainaMapGuideapplicationiswrittenandreadthroughFDOconnections.Thismeansthatupdatesoccurimmediately.AutoCADMap3DworkswithdatastoredintheDWGfileaswellasFDOdata.Dependingonthemethodchosen,updatesinaAutoCADMap3Dapplicationmaybecachedandnotwrittendirectlytothefeaturesource.

DifferencesinoperationbetweenAutoCADMap3DandMapGuidemeanthatinsomecasestheGeospatialPlatformAPIhasadifferentimplementationintheproducts.AutoCADMap3DincludesasetofclassesthatextendtheAPI.Forexample,theGeospatialPlatformAPIhasanMgLayerBaseclass.AutoCADMap3DextendsthisintheAcMapLayerclass.

Page 4: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

AllclassesthatarepartoftheGeospatialPlatformAPIbeginwiththeprefixMg.ClassesthatextendtheGeospatialPlatformAPIforuseinAutoCADMap3DbeginwiththeprefixAcMap.

AutoCADMap3DincludesthefollowingenumsthatarenotpartoftheGeospatialPlatformAPI:

EditMode

HighlightMode

AutoCADMap3Dalsoincludeseventhandling,whichisnotapartoftheGeospatialPlatformAPI.FormoredetailsseetheGeospatialPlatformSupplementReference.

Pleasesendusyourcommentaboutthispage

Page 5: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

GeospatialPlatformAPIDocumentation

ThedocumentationfortheGeospatialPlatformAPIisin3places:

AutoCADMap3DGeospatialPlatformDeveloper’sGuide(thisguide)

AutoCADMap3DGeospatialPlatformAPIReference

AutoCADMap3D.NETReferenceSupplement

TheGeospatialPlatformAPIreferencecontainsdocumentationaboutclassesandmethodsthatarecommontoAutoCADMap3DandMapGuide.WhenamethodbehavesdifferentlyinAutoCADMap3Dthisisnotedinthereference.

TheGeospatialPlatformSupplementReferencecontainsdocumentationaboutclassesandmethodsthatareusedonlywithinAutoCADMap3D.InmostcasestheclassesextendclassesintheGeospatialPlatformAPIReference.

TheGeospatialPlatformAPIworkswiththeFeatureDataObjects(FDO)API.FDOdocumentationisavailablewithAutoCADMap3D,bothintheproductinstallationhelpfolderandintheSDK.

Note TheAPIReferencesareavailableinCHMformat.TheDeveloper’sGuidesareavailableinPDFandCHMformat.ToviewallCHMdocumentationaspartofonehelpsystem,opensdk.doc.main.chm.

Pleasesendusyourcommentaboutthispage

Page 6: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

SettingUpVisualStudio

TousetheGeospatialPlatformAPI,followtheinstructionsintheAutoCADMap3DObjectARX.NETDeveloper’sGuide.Addthefollowingreferencetotheproject:

AcMapApiMgd.dll

ThisassemblycontainstheGeospatialPlatformAPIandaddsthenamespaceOSgeo.MapGuide.ItislocatedintheAutoCADMap3Dinstallationfolder.

Pleasesendusyourcommentaboutthispage

Page 7: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

SampleApplications

TheSDKincludessampleapplicationsintheMapSamples\Platformfolder.SeetheDeveloperSamplesGuidefordetails.ThesamplesserveasagoodintroductiontomanyaspectsoftheGeospatialPlatformAPIandcanbeusedasastartingpointfordevelopingcustomapplications.

Pleasesendusyourcommentaboutthispage

Page 8: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

Resources

Topicsinthissection

IntroductionWorkingWithResourcesDifferencesBetweenAutoCADMap3DandMapGuideSample-UsingResources

Pleasesendusyourcommentaboutthispage

Page 9: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

Introduction

IntheGeospatialPlatformAPI,resourcesarethefilesandconfigurationinformationnecessarytodrawlayersandmaps.Therearevarioustypesofresourcesrequired.Forexample,aFeatureSourcedescribesthelocation,type,andotherdetailsneededforaccesstoGISfeaturedata.ALayerDefinitiondefinesthedataandstyleforalayer.

Resourcesarestoredinaresourcerepository.AutoCADMap3DhasasinglerepositorynamedLibrary.ThisrepositoryiscontainedwithintheDWGfile.

MapGuideusesmultiplerepositories.TheLibraryrepositorycontainspersistent,site-widedata.ThereisasingleLibraryrepositoryforeachMapGuidesite.TherearemultipleSessionrepositories,eachonecontainingdatafromasingleMapGuidesession.Sessionrepositoriesareuniquetoanindividualsessionandcannotbeshared.AllMapGuiderepositoriesaremanagedonthesiteserver.

AllowableresourcetypesaredefinedasstaticmembersoftheclassMgResourceType.SomeresourcetypesapplyonlytoMapGuide.

ThefollowingresourcetypesarevalidforbothMap3DandMapGuide:

ResourceType Description

FeatureSource Containstherequiredparametersforconnectingtoageospatialfeaturesource.

LayerDefinition Containstherequiredparametersfordisplayingandstylingalayer.Layerscanbedrawinglayers,vectorlayers,orgrid(raster)layers.

Page 10: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

SymbolDefinition Definesasymboltobedisplayedonamap.

ThefollowingresourcetypesareonlyvalidforMapGuide:

ResourceType Description

ApplicationDefinition DefinesaflexibleWeblayoutfortheFusionframework.

DrawingSource ContainstherequiredparametersforconnectingtoaDWGfile.

Folder Afolderintheresourcerepository.

LoadProcedure ContainstherequiredparametersforloadingnewdataintotheMapGuiderepository.

Map Containstherun-timedefinitionofamap.

MapDefinition Definesaninitialmapstate,usedasthebasisforcreatingarun-timemap.

PrintLayout DefinesthecomponentsofaprintedmapcreatedfromMapGuide.

Selection Containsselectioninformation.

SymbolLibrary Definesalibraryofsymbols.

WebLayout DefinesthecomponentsofaWeblayoutforaMapGuideViewer.

Resourcerepositoriesarestructuredlikedirectories,withfolders,subfolders,anddocuments.EachresourceisanXMLdocumentintherepository,namedwitha

Page 11: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

uniqueresourceidentifier.Aresourceidentifierismadeupofthefollowingparts:

Repositorytype—either“Library”or“Session”.Map3Donlyuses“Library”.

Repositoryname—forlibraryrepositories,anemptystring.Forsessionrepositories,auniquesessionidentifierassignedbythesiteserver.

Path—thepathtothefoldercontainingtheresource.

Name—theresourcename,withouttheextension.

Resourcetype—theresourcetype(theextension).ThismustmatchoneoftheallowabletypesdefinedinMgResourceType.

Forexample,thefollowingcouldbeanameforafeaturesourceineitherMap3DorMapGuide:

Library://Samples/CityOutline.FeatureSource

ThefollowingcouldbeanameforamapdefinitioninMapGuide:

Session:70ea89fe-0000-1000-8000-005056c00008_en//Map.MapDefinition

ResourceService

Resourcesaremanagedbytheresourceservice,anMgResourceServiceobject.

InAutoCADMap3D,useAcMapServiceFactorytogettheresourceservice:

MgResourceServiceresourceService=

AcMapServiceFactory.GetService(MgServiceType.ResourceService)

asMgResourceService;

InMapGuide,useMgSiteConnectiontogettheresourceservice:

MgSiteConnectionsiteConnection=newMgSiteConnection();

siteConnection.Open(userInfo);

MgResourceServiceresourceService=

siteConnection.CreateService(MgServiceType.ResourceService)

Page 12: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

asMgResourceService;

ResourceDependencies

Resourcesmaydependonotheritems:

Someresourcesareselfsufficientanddonotrefertoanyotherresourcesorfiles.

Someresourcesreferenceotherresources.Forexample,layerdefinitionsandfeaturesourcesarestoredasseparateresources.Alayerdefinitionresourcecontainsareferencetotheresourcesforthefeaturesourcesthatareusedinthatlayer.

Someresourcesuseassociatedresourcedata.Forexample,thisisusedtostoreconfigurationinformationforODBC/WMS/Rasterfeaturesources.

ResourceSchemas

ResourcesarestoredintherepositoryasXMLdocuments.ApplicationsthataddormodifyresourcesmustensurethattheXMLvalidatesagainsttheappropriateschema.

ForAutoCADMap3D,theschemasareavailableaspartoftheSDK,intheSchemafolder.

ForMapGuide,theschemasareinstalledwiththeserverfiles,inInstallDir\Server\Schema.

TheschemasaredocumentedintheXMLSchemasmoduleoftheGeospatialPlatformReference.

Pleasesendusyourcommentaboutthispage

Page 13: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

WorkingWithResources

ResourcesintherepositorycanbemanagedbyusingtheMgByteSource,MgByteReader,andMgByteSinkobjects.

ToconvertastringrepresentationoftheXMLdataintodataforaresource,firstcreateanMgByteSource.NewMgByteSourceobjectscanbeinitializedwithastringorthecontentsofafile.GetanMgByteReaderfromthebytesourceandpassthattoMgResourceService.SetResource().

Forexample,ifanexternalfilecontainsthestringrepresentationoftheXMLforalayerdefinition,thefollowingwouldreadthecontentsofthefileandstoreitintherepository.

MgResourceIdentifierrID_layer=newMgResourceIdentifier(

@"Library://Data/Zoning.LayerDefinition");

MgByteSourcelayer_byteSource=newMgByteSource(xmlFilePath);

layer_byteSource.SetMimeType("text/xml");

resourceService.SetResource(rID_layer,

layer_byteSource.GetReader(),null);

TherearemanywaysofmodifyingtheXMLinaresource.Thebestmethodtouseinagivensituationdependsonthedevelopmentenvironment,thedeveloper’sfamiliaritywithagiventechnique,andthedesiredresult.Somepossibilitiesaredescribedinthefollowingsections.OthertechniquesforworkingwithXMLdataareequallyvalid.

xsd.exe

For.NETdevelopment,usedwithAutoCADMap3DandtheASP.NETAPIofMapGuide,itispossibletousethetoolxsd.exe,whichisavailablewiththeSDKthatcomeswithMicrosoftVisualStudio.xsd.exereadsanXMLschemaandgenerates.NETclassesforworkingwithXMLdocumentsbasedontheschema.xsd.execangeneratebothVB.NETandC#classes.

Page 14: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

Tousexsd,atypicalcommandis:

xsd.exeLayerDefinition-1.0.0.xsd/c/l:cs/n:OSGeo.MapGuide.Schema.LayerDefinition

Foranexampleofhowtousetheseclasses,seetheDeveloperSamplesGuide.

Formoreinformationonxsd,seehttp://msdn.microsoft.com.

layerdefinitionfactory.php

MapGuideincludeslayerdefinitionfactory.php,whichcontainsPHPmethodsforworkingwiththeLayerDefinitionschema.Thesemethodsaredesignedtohandlemostbasictaskswithlayerdefinitions,butdonotprovidecompletesupportforallpossibilities.TheycreatetheXMLbysubstitutingstringsintoexternaltemplates.Itisrelativelyeasytoadaptthetechniquesfromlayerdefinitionfactory.phpforusewithadifferentschemaortotranslatethemintooneoftheotherdevelopmentlanguages.

AutodeskMapGuideStudio

OneofthesimplestwaystocreateXMLtemplatesistouseAutodeskMapGuideStudiowithAutodeskMapGuideEnterpriseorMapGuideOpenSource.UsingStudio,createtheresourceswiththedesiredvalues,thensavethemasXML.Theresultingfilecanbeeditedusingatexteditor,XMLeditor,orwithtechniqueslikethoseinlayerdefinitionfactory.php.

DocumentObjectModel

Finally,allofthedevelopmentlanguagessupportversionsoftheDocumentObjectModel(DOM)API,whichisageneral-purposeAPIforworkingwithandvalidatingXMLfiles.UsingtheDOMAPIrequiresconvertingdataintoastring,thenconvertingthatstringintoanXMLdocument.Forexample,thefollowingtakesresourcedatafromtherepositoryandloadsitintoanXMLdocument:

//usingSystem.Xml;

MgByteReaderbyteReader=

resourceService.GetResourceContent(resourceId);

XmlDocumentdoc=newXmlDocument();

doc.LoadXml(byteReader.ToString());

Page 15: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

ModifytheXMLdocumentusingstandardDOMmethods,thenconvertitbacktoastringandre-savetheresource.

StringxmlString=doc.DocumentElement.OuterXml;

resourceService.SetResource(resourceId,

newMgByteReader(xmlString,"text/xml"),null);

Pleasesendusyourcommentaboutthispage

Page 16: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

DifferencesBetweenAutoCADMap3DandMapGuide

ThePlatformAPIhasbeenmadetobeasconsistentaspossiblebetweenAutoCADMap3DandMapGuide.However,therearesomedifferences,especiallyinthewaytheyhandleresources.

AutoCADMap3DdoesnotuseApplicationDefinition,DrawingSource,Folder,LoadProcedure,Map,MapDefinition,PrintLayout,Selection,SymbolLibrary,orWebLayoutresources.

InAutoCADMap3D,theresourcesarestoredinsidetheDWGdrawingfileoraDWTtemplatedrawing,notinanexternaldatabase.Thismeansthatresourcesandtheirpathsarespecifictothatdrawing.Inotherwords,thesamerepositorypathinanotherdrawingmaynotbedefined,ormayrefertoadifferentresource.Ifyouneedtoshareresourcesbetweendrawings,youmustaddthemtoeachdrawing.

SessionrepositoriesarenotsupportedinAutoCADMap3D.AllresourcesmustbestoredintheLibraryrepository.

AutoCADMap3Ddoesnotuseresourceheaders.Foranymethodthatallowsthem,forexampleSetResource(),enternullforthatparameter.

ThefollowingmethodsinMgResourceServicearenotsupportedinAutoCADMap3D:

ApplyResourcePackage()

ChangeResourceOwner()

GetRepositoryContent()

GetRepositoryHeader()

GetResourceHeader()

Page 17: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

UpdateRepository()

Themethodofspecifyingtheresourcedataforafilediffers.InMapGuide,theprocedureis:

1. InthefeaturesourceXML,providethenameoftheSDFfile.Forexample:

<Value>%MG_DATA_FILE_PATH%

HydrographicPolygons.sdf</Value>

2. UseResourceService.SetResourceData()tospecifythelocationoftheresourcedata(theSDFfile)ondisk.

InAutoCADMap3D,theprocedureistospecifytheabsolutelocationoftheresourcedatainthefeaturesourceXML.Forexample:

<Parameter>

<Name>File</Name>

<Value>C:\MapObjectARXSDK\MapSamples\Platform\BuildMap\Data\SDF\Buffered.sdf</Value>

</Parameter>

NocalltoResourceSerivce.SetResourceData()isrequired.AutoCADMap3DdoesuseResourceService.SetResourceData()forstreams,butonlyfortheconfigurationinformationforODBC/WMS/Rasterfeaturesources.

Pleasesendusyourcommentaboutthispage

Page 18: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

Sample-UsingResources

Thisexampleshowshowtoaddaresourceprogrammatically,usingexternalfilesthatcontaintheXMLfortheresources.

Topicsinthissection

TheXMLFilesAddingTheResourcePointsToWatch

Pleasesendusyourcommentaboutthispage

Page 19: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

TheXMLFiles

ThissampleusesdatafromtheBuildMapdevelopersample.WhenyourunBuildMap,itwritesthesefilestothedirectorycontainingBuildMap.dll.SeetheDeveloperSamplesGuidefordetails.

OnefileisZoning.layer.Thisspecifiesallthepropertiesfordrawingonelayerinamap.Notethe<ResourceId>element,whichreferstotheresourceforthefeaturesource.

<?xmlversion="1.0"encoding="utf-8"?>

<LayerDefinition

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:xsd="http://www.w3.org/2001/XMLSchema"

version="1.0.0">

<VectorLayerDefinition>

<ResourceId>Library://Data/SDF/Zoning.FeatureSource

</ResourceId>

<FeatureName>Schema:Zoning</FeatureName>

<FeatureNameType>FeatureClass</FeatureNameType>

<Geometry>Geometry</Geometry>

<VectorScaleRange>

<AreaTypeStyle>

<AreaRule>

<LegendLabel/>

<AreaSymbolization2D>

<Fill>

<FillPattern>Solid</FillPattern>

<ForegroundColor>a03cafda</ForegroundColor>

<BackgroundColor>FF000000</BackgroundColor>

</Fill>

<Stroke>

<LineStyle>Solid</LineStyle>

<Thickness>0.0</Thickness>

<Color>FF000000</Color>

<Unit>Centimeters</Unit>

</Stroke>

</AreaSymbolization2D>

</AreaRule>

</AreaTypeStyle>

Page 20: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

</VectorScaleRange>

</VectorLayerDefinition>

</LayerDefinition>

ThesecondfileisZoning.FeatureSource,whichdefinesthepropertiesofanSDFfeaturesource.TheFileparameterpointstothelocationondisk.SeeFeatureServiceformoredetails.

<?xmlversion="1.0"encoding="utf-8"?>

<FeatureSourcexmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<Provider>OSGeo.SDF.3.3</Provider>

<Parameter>

<Name>File</Name>

<Value>C:\Map3DSDK\MapSamples\Platform\BuildMap\Data\SDF\Zoning.sdf</Value>

</Parameter>

<Parameter>

<Name>ReadOnly</Name>

<Value>False</Value>

</Parameter>

</FeatureSource>

Pleasesendusyourcommentaboutthispage

Page 21: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

AddingTheResource

TousetheXMLfilestocreatethelayerandthefeaturesource,useMgResourceService.SetResource().Forexample:

//Addthelayerdefinition.

//Itwillbestoredintherepositoryusingtheresource

//identifier.

MgResourceIdentifierrID_layer=newMgResourceIdentifier(

@"Library://Data/Zoning.LayerDefinition");

//Note:Modifythisdirectorytopointtothelocationof

//theXMLfiles.

StringxmlDirectory=@"C:\Map3DSDK\"

+@"MapSamples\Platform\BuildMap\bin\Debug\";

//ReadtheXMLfile,thensaveitscontentsintheresource

//repository.

MgByteSourcelayer_byteSource=

newMgByteSource(xmlDirectory+"Zoning.layer");

layer_byteSource.SetMimeType("text/xml");

resourceService.SetResource(rID_layer,

layer_byteSource.GetReader(),null);

//Addthefeaturesource

//Note:ThelayerdefinitionXMLrefersto

//'Library://Data/SDF/Zoning.FeatureSource'so

//wemustusethatnamehere.

MgResourceIdentifierrID_feature_source=

newMgResourceIdentifier(

@"Library://Data/SDF/Zoning.FeatureSource");

MgByteSourcefeature_byteSource=new

MgByteSource(xmlDirectory+"Zoning.FeatureSource");

feature_byteSource.SetMimeType("text/xml");

resourceService.SetResource(rID_feature_source,

feature_byteSource.GetReader(),null);

Thenaddthelayertothecurrentmap.Forexample:

Page 22: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

MgLayerBaselayer=AcMapLayer.Create(rID_layer,

resourceService);

layer.SetName("NewLayer");

AcMapMapcurrentMap=AcMapMap.GetCurrentMap();

currentMap.GetLayers().Add(layer);

Pleasesendusyourcommentaboutthispage

Page 23: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

PointsToWatch

InthefeaturesourceXML,theprovidername(forexample,OSGeo.SDF.3.3)mustmatchoneoftheprovidernameslistedintheoutputofMgFeatureService.GetFeatureProviders().

Inthelayerdefinition,theResourceIdvaluemustmatchthepathofthefeaturesource.Intheexampleabove,thispathisusedinthelayerdefinition:

<ResourceId>Library://Data/SDF/Zoning.FeatureSource

</ResourceId>

Sothecorrespondingpathmustbeusedwhenthefeaturesourceiscreated.Forexample:

MgResourceIdentifierrID_feature_source=

newMgResourceIdentifier(

@"Library://Data/SDF/Zoning.FeatureSource");

CreatenewlayersusingthestaticmethodAcMapLayer.Create().

CreatenewlayergroupsusingtheAcMapLayerGroupconstructorAcMapLayerGroup(groupName).

Pleasesendusyourcommentaboutthispage

Page 24: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

FeatureService

Topicsinthissection

OverviewDefiningFeatureSourcesJoinsAddingFeatureClassestoaMapSelectingFeatureDataRepresentationofGeometrySelectingUsingtheAPIUpdatingFeaturesCreatingSDFfiles

Pleasesendusyourcommentaboutthispage

Page 25: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

Overview

AfeaturesourcerepresentsasingleFDO(FeatureDataObjects)connection.FDOisanAPIforreadingandwritinggeospatialdatainavarietyofformats.FormoredetailsaboutFDO,seethedocumentationincludedwithAutoCADMap3DandtheSDK,orvisitfdo.osgeo.org.

FeatureServiceprovidesacommonAPIforreadingandwritingfeaturedatafromdatasourcesforwhichanFDOproviderexists.

Differentfeaturesourceshavedifferentcapabilities.Forexample,anOracleSpatialdatabasewillhavemorecapabilitiesthananODBCconnection.Somefeaturesourcescanhavemultipleschemas.

Oneschemainafeaturesourcecandescribemultiplefeatureclasses.Forexample,asingleSDFfilecouldcontainafeatureclassforroadsandanotherfeatureclassforhydrography.

InAutoCADMap3D,asingleFDOfeatureclasscorrespondstoasinglemaplayer.Therecannotbemorethanonefeatureclassperlayer,andalayercontainingfeaturedatacannotcontainAcDbentities.

Note AllFeatureServiceoperationsworkwithfeaturesbelongingtothecurrentmap.Togetthecurrentmap,callAcMapMap.GetCurrentMap().

Pleasesendusyourcommentaboutthispage

Page 26: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

DefiningFeatureSources

TodefineafeaturesourcewithinAutoCADMap3D,createaresourceidentifierforthefeaturesourceandstoreitintheresourcerepository.ThencallMgResourceService.SetResource()withthreeparameters:

AnMgResourceIdentifierthatcontainsthepathintheresourcerepositoryfortheresource.

AnMgByteReaderthatprovidestheXMLdescribingthefeaturesource.ThisconformstoFeatureSource.xsd.

Anullparameterfortheresourceheader.ThisisnotusedbyAutoCADMap3D.

Therepositorypathisoftheform

Library://resourcePath/resourceName.FeatureSource

resourcePathisoptional,butFeatureSource(casesensitive)ismandatory.Forexample,thefollowingcreatesanMgResourceIdentifier:

MgResourceIdentifierparcelId=

newMgResourceIdentifier("Library://parcels.FeatureSource");

TheexactformoftheXMLdescribingthefeaturesourcevariesdependingontheFDOprovider.SeetheschemadocumentationforFeatureSource.xsdandtheConnectionAPIsectionofTheEssentialFDOfordetails.DifferentFDOprovidersacceptdifferentparameters,asdescribedinTheEssentialFDO.Forexample,theAutodesk.Raster.3.2provideracceptsasingleparameter,DefaultRasterFileLocation.ThisissetinaName/ValueparameterintheXMLdata.

<?xmlversion="1.0"encoding="utf-8"?>

<FeatureSource

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

Page 27: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<Provider>Autodesk.Raster.3.2</Provider>

<Parameter>

<Name>DefaultRasterFileLocation</Name>

<Value>C:\some\folder\rasterfile.jpg</Value>

</Parameter>

<ConfigurationDocument>config://rasterfile.jpg

</ConfigurationDocument>

<LongTransaction/>

</FeatureSource>

Someprovidersrequireadditionalconfiguration.Forexample,theAutodesk.Raster.3.2providerrequiresgeoreferencinginformationtodefinethelocationandresolutionoftherasterdataforsomerasterfileformats.Thiscanbeinaworldfileinthesamefolderastherasterfile,oritcanbeinaseparateFDOconfigurationfile.WMSandODBCproviderscanalsorequireseparateconfigurationfiles.

Forthoseprovidersthatdorequireaconfigurationfile,theFeatureSourceXMLcontainsa<ConfigurationDocument>elementthatpointstoresourcedata.CallMgResourceService.SetResourceData()tosetthedata.Thedatanamemustmatchthenameinthe<ConfigurationDocument>element.TheBuildMapsampleusesconfig://aspartoftheresourcedataname,butthisisnotrequired.

Topicsinthissection

Example:DefiningaVectorFeatureSourceExample:DefiningaRasterFeatureSource

Pleasesendusyourcommentaboutthispage

Page 28: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

Example:DefiningaVectorFeatureSource

Definingavectorfeaturesourcerequirescreatingthefeaturesourcedefinitionandstoringitintheresourcerepositoryusingthefeaturesourceresourceidentifier.ThefollowingexampleassumesthatSDFpathisastringcontainingthefilepathofanSDFfile.ItcreatesafeaturesourcewitharesourceidentifierofLibrary://feature.FeatureSource.

Therearemanywaystocreateafeaturesourcedefinition.Onemethod,usedinthesampleapplicationsandthefollowingexample,usesclassesgeneratedusingtheVisualStudiotoolxsd.exeonFeatureSource.xsd.FeatureSourceTypeandNameValuePairTypeareclassesgeneratedthisway.

Note ResourceservicerequiresdatatobeUTF-8encoded.

//Gettheservices

MgResourceServicers;

rs=AcMapServiceFactory.GetService(MgServiceType.ResourceService)

asMgResourceService;

MgFeatureServicefs;

fs=AcMapServiceFactory.GetService(MgServiceType.FeatureService)

asMgFeatureService;

MgResourceIdentifierfsId=newMgResourceIdentifier(

"Library://feature.FeatureSource");

//Createthefeaturesourcedefinitionwitharequired

//parameterofFileandanoptionalparameterofReadOnly

stringxmlString;

FeatureSourceTypefsType=newFeatureSourceType();

fsType.Provider="OSGeo.SDF.3.2";

NameValuePairTypeparam=newNameValuePairType();

param.Name="File";

param.Value=SDFpath;

NameValuePairTypeparam2=newNameValuePairType();

Page 29: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

param2.Name="ReadOnly";

param2.Value="false";

fsType.Parameter=newNameValuePairType[]{param,param2};

//Serializethefeaturesourceobjectmodeltoxmlstring

using(StringWriterwriter=newStringWriter())

{

XmlSerializerxs=newXmlSerializer(fsType.GetType());

xs.Serialize(writer,fsType);

xmlString=writer.ToString();

}

//ConverttheUnicodestringtoUTF8bytesforResourceService

byte[]unicodeBytes=Encoding.Unicode.GetBytes(xmlString);

byte[]utf8Bytes=Encoding.Convert(Encoding.Unicode,

Encoding.UTF8,unicodeBytes);

//CreateabytereadercontainingtheXMLfeature

//sourcedefinition.Storethedefinitionintherepository

MgByteSourcexmlSource=newMgByteSource(utf8Bytes,

utf8Bytes.Length);

rs.SetResource(fsId,xmlSource.GetReader(),null);

Pleasesendusyourcommentaboutthispage

Page 30: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

Example:DefiningaRasterFeatureSource

Definingarasterfeaturesourceissimilartodefiningavectorfeaturesource.Theparametersvarydependingontheprovider.Mostrasterfilesdonotcontaincoordinatesysteminformation,soitmustbeobtainedsomeotherway.ThiscanbedoneusingaworldfileorthroughadditionalconfigurationfortheFDOprovider.Thefollowingexampleusesthesecondmethod,addingresourcedatacontainingtheconfigurationinformation.

Theresourceidentifiercontainsthelocationintheresourcerepositoryforthefeaturesourcedefinition.

MgResourceIdentifierrasterId=newMgResourceIdentifier(

"Library://rasterFeature.FeatureSource");

stringxmlString;

FeatureSourceTypefsType=newFeatureSourceType();

fsType.Provider="Autodesk.Raster.3.2";

NameValuePairTypeparam=newNameValuePairType();

param.Name="DefaultRasterFileLocation";

param.Value=@"C:\some\folder\rasterfile.jpg";

fsType.Parameter=newNameValuePairType[]{param};

fsType.ConfigurationDocument="config://rasterfile.jpg";

fsType.LongTransaction="";

//Serializethefeaturesourceobjectmodeltoanxmlstring

using(StringWriterwriter=newStringWriter())

{

XmlSerializerxs=newXmlSerializer(fsType.GetType());

xs.Serialize(writer,fsType);

xmlString=writer.ToString();

}

byte[]unicodeBytes=Encoding.Unicode.GetBytes(xmlString);

byte[]utf8Bytes=Encoding.Convert(Encoding.Unicode,

Encoding.UTF8,unicodeBytes);

Page 31: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

MgByteSourcexmlSource=

newMgByteSource(utf8Bytes,utf8Bytes.Length);

MgResourceServicers;

rs=AcMapServiceFactory.GetService(MgServiceType.ResourceService)

asMgResourceService;

rs.SetResource(rasterId,xmlSource.GetReader(),null);

TheconfigurationinformationvariesdependingontheFDOprovider.TheWMS,ODBC,andRasterprovidersmayneedadditionalconfigurationinformation.RefertotheFDOdocumentationintheMapSDKandintheAutoCADMap3Dinstallationfolderformoredetails.

Thefollowingreadstheconfigurationfromafileandstoresitintheresourcerepository.Ensurethatthedatanamematchesthe<ConfigurationDocument>elementinthefeaturesourcedefinition.

MgByteSourcesource;

source=newMgByteSource(@"C:\some\folder\rasterconfig.xml");

rs.SetResourceData(rasterId,"config://rasterfile.jpg",

MgResourceDataType.Stream,source.GetReader());

Pleasesendusyourcommentaboutthispage

Page 32: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

Joins

Joinsextendafeaturesourcebycombiningitwithdatafromanotherfeaturesource,similartoadatabasejoin.TheyarecommonlyusedtocombineGISdatawithdatafromadatabase.

Forexample,anSDFfilecontainingthefollowingproperties:

parcelgeometry

parcelID

couldbejoinedwithanODBCdatabasecontainingthefollowingproperties:

parcelID

ownername

assessmentvalue

landusedesignation

Thejoinisdefinedinthefeaturesourcedefinition.Eachjoinrequires2featureclasses.TheprimaryfeatureclasscontainsthegeometryfordisplayinAutoCADMap3D.Thesecondaryfeatureclassdoesnotneedgeometry,butitmusthaveapropertythatmatchesapropertyintheprimaryfeatureclass.Intheexampleabove,theSDFfilecontainstheprimaryfeatureclassandtheODBCdatabasecontainsthesecondaryfeatureclass.

Inmostcasesthefeatureclasseswillbefromdifferentfeaturesources,butitispossibletocreateaself-referencingjoinwithin1featureclassorajoinbetween2featureclassesinthesamefeaturesource.

Tocreateajoinedfeaturesource,beginwiththesecondaryfeaturesource.Thisdoesnotrequireanythingspecial.Forexample,thefollowingisasimpleconnectiontoanODBCdatabase:

<FeatureSource

Page 33: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:xsd="http://www.w3.org/2001/XMLSchema"

xsi:noNamespaceSchemaLocation="MapFeatureSource-1.0.0.xsd"

version="1.0.0">

<Provider>OSGeo.ODBC.3.2</Provider>

<Parameter>

<Name>Password</Name>

<Value></Value>

</Parameter>

<Parameter>

<Name>GenerateDefaultGeometryProperty</Name>

<Value>false</Value>

</Parameter>

<Parameter>

<Name>ConnectionString</Name>

<Value></Value>

</Parameter>

<Parameter>

<Name>DataSourceName</Name>

<Value>OWNERS</Value>

</Parameter>

<Parameter>

<Name>UserId</Name>

<Value></Value>

</Parameter>

<ConfigurationDocument></ConfigurationDocument>

<LongTransaction></LongTransaction>

</FeatureSource>

Theprimaryfeaturesourcedefinesthejoin.Itmustidentifythesecondaryfeaturesourceandwhichpropertiesaretobeusedforthejoin.Forexample,thefollowingisafeaturesourcedefinitionforanSDFfilewithajointoanODBCdatabase:

<FeatureSource

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:xsd="http://www.w3.org/2001/XMLSchema"

xsi:noNamespaceSchemaLocation="MapFeatureSource-1.0.0.xsd"

version="1.0.0">

<Provider>OSGeo.SDF.3.2</Provider>

<Parameter>

<Name>ReadOnly</Name>

<Value>false</Value>

</Parameter>

<Parameter>

<Name>File</Name>

<Value>C:\some\folder\Parcels.sdf</Value>

</Parameter>

Page 34: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

<ConfigurationDocument></ConfigurationDocument>

<LongTransaction></LongTransaction>

<Extension>

<Name>Parcels_Joins1</Name>

<FeatureClass>SHP_Schema:Parcels</FeatureClass>

<AttributeRelate>

<AttributeClass>Fdo:Parcels</AttributeClass>

<ResourceId>Library://ODBC_1</ResourceId>

<Name>Parcels</Name>

<AttributeNameDelimiter>|</AttributeNameDelimiter>

<RelateType>LeftOuter</RelateType>

<ForceOneToOne>true</ForceOneToOne>

<RelateProperty>

<FeatureClassProperty>APN</FeatureClassProperty>

<AttributeClassProperty>APN</AttributeClassProperty>

</RelateProperty>

</AttributeRelate>

</Extension>

</FeatureSource>

The<Extension>elementdefinesthejoin.<Name>isthenameofthejoin,usedinalayerdefinitionthatreferencesthefeaturesource.Ifafeaturesourcedefinesmorethanonejointheymusthavedifferentnames.<FeatureClass>isafeatureclassintheprimaryfeaturesource.

<AttributeRelate>definesajointoasinglefeaturesource.Itispossiblefortheprimaryfeaturesourcetohavejoinstomorethanonesecondaryfeaturesource.Thisisrepresentedbymultiple<AttributeRelate>elements.Asanexample,theownerinformationcouldbeinonedatabasetableandassessmentinformationcouldbeinanother.

Foreachjoin,<AttributeClass>definestheschemaandfeatureclassinthesecondaryfeaturesource.<ResourceId>istheresourceidentifier.<RelateType>isthetypeofjoin.ThisreleaseofAutoCADMap3Dsupportsleftouterjoinsandinnerjoins.

Thejoincanhavemultiple<RelateProperty>elements.Thesedefinethefieldsthatmustmatchforthejoin.

StorethefeaturesourcedefinitionusingMgResourceService.SetResource(),asdescribedinDefiningFeatureSources.

Page 35: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

Pleasesendusyourcommentaboutthispage

Page 36: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

AddingFeatureClassestoaMap

Toaddafeatureclasstoamap,createalayerdefinitionforthenewlayerandaddittotheresourcerepository.CreateanAcMapLayerandsetitslayerdefinition.AddthelayertothemapusingAcMapMap.GetCurrentMap().GetLayers().Add().

Creatingthelayerdefinitionissimilartocreatingthefeaturesourcedefinition.SeeDefiningFeatureSources.ThelayerdefinitionusestheLayerDefinition.xsdschema,whichincludesstylinginformation.SeeLayerDefinitionfordetails.

The<FeatureName>elementinthelayerdefinitionisoftheform

schemaName:className

whereschemaNameandclassNamearevalidforthefeaturesource.CallMgFeatureService.GetSchemas()togettheschemanamesforafeaturesourceandMgFeatureService.GetClasses()togettheclassnamesforaschema.

Thefollowingexamplecreatesalayerdefinitionforarasterlayerandaddsthelayertothecurrentmap.

AcMapMapcurrentMap=AcMapMap.GetCurrentMap();

stringlayerDefName="Library://rasterlayer.LayerDefinition";

MgResourceIdentifierlayerId=new

MgResourceIdentifier(layerDefName);

//Useclassesfromxsd.exetobuildthelayer

definition

LayerDefinitionTypelayerDef=newLayerDefinitionType();

GridLayerDefinitionTypegridLayerDef=new

GridLayerDefinitionType();

layerDef.Item=gridLayerDef;

gridLayerDef.ResourceId=rasterId.ToString();

gridLayerDef.FeatureName="rasters:classname";

gridLayerDef.Geometry="Image";

Page 37: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

GridScaleRangeType[]ranges=newGridScaleRangeType[1];

gridLayerDef.GridScaleRange=ranges;

ranges[0]=newGridScaleRangeType();

ranges[0].ColorStyle=newGridColorStylizationType();

GridColorRuleType[]colorRules=newGridColorRuleType[1];

ranges[0].ColorStyle.ColorRule=colorRules;

colorRules[0]=newGridColorRuleType();

colorRules[0].LegendLabel="";

colorRules[0].Color=newGridColorType();

colorRules[0].Color.ItemElementName=ItemChoiceType.Band;

colorRules[0].Color.Item="1";

ranges[0].RebuildFactor=1;

//SerializethelayerdefinitiontoXML

stringlayerDefString;

using(StringWriterwriter=newStringWriter())

{

XmlSerializerxs=newXmlSerializer(layerDef.GetType());

xs.Serialize(writer,layerDef);

layerDefString=writer.ToString();

}

//ConvertUnicodetoUTF-8

unicodeBytes=Encoding.Unicode.GetBytes(layerDefString);

utf8Bytes=Encoding.Convert(Encoding.Unicode,Encoding.UTF8,

unicodeBytes);

//Createabytereadercontainingthelayer

sourcedefinition

xmlSource=newMgByteSource(utf8Bytes,utf8Bytes.Length);

rs.SetResource(layerId,xmlSource.GetReader(),null);

//AddthelayertotheMap

MgLayerBaselayer=newAcMapLayer(layerId,rs);

layer.Name="newLayer";

currentMap.GetLayers().Add(layer);

Thisaddsthenewlayertotheendofthelayercollection,atthetopofthedraworder.

Layerscanbeorganizedintogroups.Toaddalayertoagroupcall

Page 38: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

AcMapLayer.SetGroup()withthegroupname.

Pleasesendusyourcommentaboutthispage

Page 39: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

SelectingFeatureData

IndividualfeatureswithinafeaturesourceareidentifiedbyuniquefeatureIDs.TheformoftheIDdependsonthefeaturesource.CallMgFeatureService.GetClassDefinition()togetthefeatureclassdefinition.CallMgClassDefinition.GetIdentityProperties()togetalistofallpropertiesthatareidentityproperties.

Togetthecurrentlyselectedfeaturesforamap,callAcMapMap.GetFeatureSelection().ThisreturnsanMgSelectionBaseobject.Asingleselectioncancontainfeaturesfrommultiplelayersandclasses.CallMgSelectionBase.GetLayers()togetalllayerscontainingselectedobjects,orselectanindividuallayer.

Forexample,tofindselectedfeaturesontheParcelslayer,

AcMapMapcurrentMap=AcMapMap.GetCurrentMap();

MgFeatureServicefs=

AcMapServiceFactory.GetService(MgServiceType.FeatureService)

asMgFeatureService;

MgLayerCollectionlayers=currentMap.GetLayers();

MgLayerBaseparcelsLayer=layers.GetItem("Parcels");

stringfcName=parcelsLayer.GetFeatureClassName();

MgSelectionBaseselection=currentMap.GetFeatureSelection();

stringselectionFilter=selection.GenerateFilter(parcelsLayer,

fcName);

MgFeatureQueryOptionsqueryOpts=newMgFeatureQueryOptions();

queryOpts.SetFilter(selectionFilter);

MgFeatureReaderfeatureReader;

MgResourceIdentifierfsId=new

MgResourceIdentifier(parcelsLayer.GetFeatureSourceId());

featureReader=fs.SelectFeatures(fsId,fcName,queryOpts);

AselectionconsistsofoneormorefeatureIDs.Toprocessthefeaturesina

Page 40: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

selection,createanMgFeatureReaderthatcontainstheselectedfeatures,thencallMgFeatureReader.ReadNext()toadvancethroughthefeaturereader.TocreatetheMgFeatureReader()fortheselectedfeaturesinalayer,callMgSelectionBase.GenerateFilter(),whichcreatesafiltertoselectthefeatures.ThencreateandinitializeanMgFeatureQueryOptionsobject.Finally,callAcMapFeatureService.SelectFeatures().

AnMgFeatureReaderiteratesthroughalistoffeaturesfromasinglefeaturesource.Toadvancetothenextfeatureinthereader,callMgFeatureReader.ReadNext().

Pleasesendusyourcommentaboutthispage

Page 41: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

RepresentationofGeometry

AutoCADMap3Dcanrepresentgeometricdatain3differentforms:

AGFtextformat,whichisanextensionoftheOpenGeospatialConsortium(OGC)WellKnownText(WKT)format.Thisisusedtorepresentgeometryasacharacterstring.

BinaryAGFformat.TheisusedbytheFDOtechnologysupportingtheFeatureService.

Internalrepresentation,usingMgGeometryandclassesderivedfromit.

ToconvertbetweenAGFtextandtheinternalrepresentation,useanMgWktReaderWriterobject.CallMgWktReaderWriter.Read()toconvertAGFtexttoMgGeometry.CallMgWktReaderWriter.Write()toconvertMgGeometrytoAGFtext.

ToconvertbetweenbinaryAGFandtheinternalrepresentation,useanMgAgfReaderWriterobject.CallMgAgfReaderWriter.Read()toconvertbinaryAGFtoMgGeometry.CallMgAgfReaderWriter.Write()toconvertMgGeometrytobinaryAGF.

Forexample,ifyouhaveaWKTrepresentationofthegeometry,youcouldcreateageometryobjectasfollows:

MgWktReaderWriterwktReaderWriter=newMgWktReaderWriter();

MgGeometrygeometry=wktReaderWriter.Read(wktGeometry);

Pleasesendusyourcommentaboutthispage

Page 42: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

SelectingUsingtheAPI

SelectionscanbecreatedprogramaticallywiththePlatformAPI.Thisisdonebyqueryingdatainafeaturesource,creatingafeaturereaderthatcontainsthefeatures,thenconvertingthefeaturereadertoaselection(MgSelectionobject).

Tocreateafeaturereader,applyaselectionfiltertoafeatureclassinthefeaturesource.Aselectionfiltercanbeabasicfilter,aspatialfilter,oracombinationofthetwo.ThefilterisstoredinanMgFeatureQueryOptionsobject.

Basicfiltersareusedtoselectfeaturesbasedonthevaluesoffeatureproperties.Forexample,youcoulduseabasicfiltertoselectallroadsthathavefourormorelanes.

Spatialfiltersareusedtoselectfeaturesbasedontheirgeometry.Forexample,youcoulduseaspatialfiltertoselectallroadsthatintersectacertainarea.

Topicsinthissection

BasicFiltersSpatialFilters

Pleasesendusyourcommentaboutthispage

Page 43: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

BasicFilters

Basicfiltersperformlogicaltestsoffeatureproperties.Youcanconstructcomplexqueriesbycombiningexpressions.Expressionsusethecomparisonoperatorsbelow:

Operator Meaning

= Equality

<> Notequal

< Lessthan

<= Lessthanorequalto

> Greaterthan

>= Greaterthanorequalto

LIKE Usedforstringcomparisons.The“%”wildcardrepresentsanysequenceof0ormorecharacters.The“_”wildcardrepresentsanysinglecharacter.Forexample,“LIKESchmitt%”willsearchforanynamesbeginningwith“Schmitt”.

Thecomparisonoperatorscanbeusedwithnumericorstringproperties,exceptfortheLIKEoperator,whichcanonlybeusedwithstringproperties.

CombineormodifyexpressionswiththestandardbooleanoperatorsAND,OR,

Page 44: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

andNOT.

Topicsinthissection

Examples

Pleasesendusyourcommentaboutthispage

Page 45: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

Examples

Theseexamplesassumethatthefeatureclassyouarequeryinghasanintegerpropertynamedyearandastringpropertynamedowner.Toselectallfeaturesnewerthan2001,createafilterlikethis:

MgFeatureQueryOptionsqueryOptions=newMgFeatureQueryOptions();

queryOptions.SetFilter("year>2001");

Toselectallfeaturesbuiltbetween2001and2004,createafilterlikethis:

queryOptions.SetFilter("year>=2001andyear<=2004");

ToselectallfeaturesownedbyDavisorDavies,createafilterlikethis:

queryOptions.SetFilter("ownerLIKE'Davi%s'");

Pleasesendusyourcommentaboutthispage

Page 46: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

SpatialFilters

Withspatialfilters,youcandocomparisonsusinggeometricproperties.Forexample,youcanselectallfeaturesthatareinsideanareaonthemap,orthatintersectanarea.

Therearetwowaysofusingspatialfilters:

Createaseparatespatialfiltertoapplytothefeaturesource,usingtheMgFeatureQueryOptions.SetSpatialFilter()method.

IncludespatialpropertiesinabasicfiltercreatedwiththeMgFeatureQueryOptions.SetFilter()method.

TheMgFeatureQueryOptions.SetSpatialFilter()methodrequiresanMgGeometryobjecttodefinethegeometryandaspatialoperationtocomparethefeaturepropertyandthegeometry.ThespatialoperationsaredefinedinclassMgFeatureSpatialOperations.

Toincludespatialpropertiesinabasicfilter,definethegeometryusingWKTformat.UsetheGEOMFROMTEXT()functioninthebasicfilter,alongwithoneofthefollowingspatialoperations:

CONTAINS

COVEREDBY

CROSSES

DISJOINT

EQUALS

INTERSECTS

OVERLAPS

TOUCHES

Page 47: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

WITHIN

INSIDE

Note Thespatialoperationsarenotcasesensitive,so“CONTAINS”and“contains”producethesameresult.

Forexample,thefollowingselectsfeaturesthatcrossanarea:

queryOptions.SetFilter(

"SHPGEOMcrossesGEOMFROMTEXT("+wktGeom+")");

Thesamefilteringsyntaxcanbeusedinalayerdefinition,tocreatealayercontainingonlythosefeaturesthatpassthefilter.SeeFilteringLayersByGeometryfordetails.

Note Notallspatialoperationscanbeusedonallfeatures.ItdependsonthecapabilitiesoftheFDOproviderthatsuppliesthedata.Thisrestrictionappliestoseparatespatialfiltersandspatialpropertiesthatareusedinabasicfilter.

Topicsinthissection

CreatingGeometryObjectsFromFeatures

Pleasesendusyourcommentaboutthispage

Page 48: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

CreatingGeometryObjectsFromFeatures

Youmaywanttouseanexistingfeatureaspartofaspatialquery.Toretrievethefeature’sgeometryandconvertitintoanappropriateformatforaquery,performthefollowingsteps:

Createaquerythatwillselectthefeature.

QuerythefeatureclasscontainingthefeatureusingAcMapLayer.SelectFeatures()orMgFeatureService.SelectFeatures().

ObtainthefeaturefromthequeryusingtheMgFeatureReader.ReadNext()method.

GetthegeometrydatafromthefeatureusingtheMgFeatureReader.GetGeometry()method.ThisdataisinAGFbinaryformat.

ConverttheAGFdatatoanMgGeometryobjectusingtheMgAgfReaderWriter.Read()method.

Forexample,thefollowingsequencecreatesanMgGeometryobjectrepresentingtheboundariesofzone1inthelayernamed“zones”.ItcreatesanMgGeometryobjectandtheWKTrepresentationofthatobject.

MgLayerCollectionlayers=currentMap.GetLayers();

MgLayerBaselayer=layers.GetItem("zones");

stringfsId=layer.GetFeatureSourceId();

stringclassName=layer.GetFeatureClassName();

MgFeatureQueryOptionsquery=

newMgFeatureQueryOptions();

query.SetFilter("ZONE_ID=1");

MgResourceIdentifierresId=

newMgResourceIdentifier(fsId);

MgFeatureReaderfeatureReader=

fs.SelectFeatures(resId,

Page 49: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

className,query);

if(featureReader.ReadNext())

{

stringgeometryName=layer.GetFeatureGeometryName();

MgByteReadergeometryData=

featureReader.GetGeometry(geometryName);

MgAgfReaderWriteragfReaderWriter=newMgAgfReaderWriter();

MgGeometrygeometry=agfReaderWriter.Read(geometryData);

MgWktReaderWriterwktReaderWriter=newMgWktReaderWriter();

stringwkt=wktReaderWriter.Write(geometry);

}

ThefollowingassumesthatanotherfeatureclasshasageometrypropertySHPGEOM.ItusestheWKTstringinaquerytofindfeaturesintheotherfeatureclassthatintersectthezone:

MgFeatureQueryOptionsqueryOpts=newMgFeatureQueryOptions();

queryOpts.SetFilter("SHPGEOMintersectsGEOMFROMTEXT("+

wkt+")");

Pleasesendusyourcommentaboutthispage

Page 50: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

UpdatingFeatures

AllupdatestofeaturesinafeaturesourceareperformedusinganMgFeatureCommandCollection.Thefeaturecommandcollectioncancontaincommandstoaddnewfeatures,deleteexistingfeatures,updateexistingfeatures,lockfeatures,orunlockfeatures.

Toaddanewfeature,createanMgInsertFeaturesobject.MgInsertFeatureshastwoconstructors.OnehasanMgPropertyCollectionparameterandisusedtoinsertasinglefeature.TheotherhasanMgBatchPropertyCollectionparameterandisusedtoinsertmultiplefeaturesinasinglecommand.

TheMgPropertyCollectioncontainsvaluesforthefeatureproperties,includingthefeaturegeometryproperty.CreateanemptyMgPropertyCollection,thenaddpropertiesusingMgPropertyCollection.Add().Thedifferentpropertytypes,suchasMgGeometryPropertyorMgInt32Property,areallderivedfromthebaseclassMgProperty.

Mostfeatureclasseswillrequireageometryproperty,whichisusedtodisplaythefeature.Tocreateageometryproperty,startwithanMgGeometryobject.

ConverttheMgGeometrytobinaryAGFformatsuitableforFDO.

MgByteReadergeometryStream;

MgAgfReaderWriteragfReaderWriter=newMgAgfReaderWriter;

geometryStream=agfReaderWriter.Write(geometry);

Createapropertycollectiontocontainthefeatureproperties.Addthegeometryproperty.Addanyotherrequiredproperties.Thepropertynamesarecasesensitiveandmustmatchthenamesdefinedinthefeatureclass.

MgPropertyCollectionproperties=newMgPropertyCollection();

MgGeometryPropertygeomProp;

geomProp=newMgGeometryProperty("SHPGEOM",geometryStream);

Page 51: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

properties.Add(geomProp);

Createafeaturecommandtoinsertthefeature,andaddittoafeaturecommandcollection.

MgFeatureCommandCollectioncommands=

newMgFeatureCommandCollection();

MgInsertFeaturesinsertCommand;

insertCommand=newMgInsertFeatures(className,properties);

commands.Add(insertCommand);

CallAcMapLayer.UpdateFeatures()toaddthenewfeature.

mapLayer.UpdateFeatures(commands);

Deletingandupdatingfeaturesissimilar.TheconstructorsforMgDeleteFeaturesandMgUpdateFeaturesrequiredifferentparameters,butthefeaturecommandscanbeaddedtothesameMgFeatureCommandCollection.

Topicsinthissection

EditSets

Pleasesendusyourcommentaboutthispage

Page 52: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

EditSets

Therearetwodifferentmodesforupdatestofeatures:

Editset

Directupdate

Note SomeFDOproviders,includingthefile-basedprovidersSDF,SHP,andraster,donotsupporteditsetmode.

UpdatesmadeusingeditsetmodearemadetotheworkingcopyinsidetheAutoCADMap3Dapplication,butarenotcommittedtothefeaturesource.Editsmadeusingdirectupdatearechangedinthefeaturesourceimmediately.

Therearetwomethodsforupdatingfeatures:

AcMapLayer.UpdateFeatures()

MgFeatureService.UpdateFeatures()

AcMapLayer.UpdateFeatures()worksdirectlywithfeaturesinthemaplayer.Thisisthepreferredmethodwhenworkingineditsetmode.

MgFeatureService.UpdateFeatures()updatesthefeaturesinthefeaturesource.Thismethodcanbeusedwhenthefeaturesourceisnotbeingdisplayedinalayer.Forexample,anAutoCADMap3DapplicationcouldcreateanSDFfilecontainingresultdatawithouteverhavingtodisplaythedata.

Tosettheupdatemodeforalayer,callAcMapLayer.SetEditSetMode().

Tocommitchangesmadeineditsetmode,callAcMapLayer.SaveFeatureChanges().Thisupdatesthefeaturesource.Todiscardthechanges,callAcMapLayer.DiscardFeatureChanges().

Pleasesendusyourcommentaboutthispage

Page 53: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

CreatingSDFfiles

Manygeospatialoperationsrequirecreatingnewlayers,addingfeaturestothelayers,andaddingthelayerstothemap.Thelayerscanbetemporaryorpermanent.InAutoCADMap3DthisishandledusingSDFfiles.

AnSDFfilecontainsasingleschemathatcandefinemultiplefeatureclasses.

TocreateanSDFfile,firstdefinetheschemaandanyfeatureclassesusedintheschema.Foreachfeatureclass,definealistofproperties.Inmostcases,thepropertiesshouldincludeanidentitypropertyandageometryproperty,aswellasanyotherproperties.

UsetheFDOAPItocreatetheschema.

ThefollowingcreatesasimpleschemawithanautogeneratedIDproperty,astringproperty,andageometryproperty.

//Createthefeatureclassdefinition

FeatureClassclassDefinition=

newFeatureClass("newClass","classdescription");

//Addanautogeneratedidentityproperty

DataPropertyDefinitionidProp=

newDataPropertyDefinition("id","propertydesc");

idProp.DataType=DataType.DataType_Int32;

idProp.IsAutoGenerated=true;

classDefinition.Properties.Add(idProp);

classDefinition.IdentityProperties.Add(idProp);

//Addanameproperty

DataPropertyDefinitionnameProp=

newDataPropertyDefinition("Name","propertydesc");

nameProp.DataType=DataType.DataType_String;

classDefinition.Properties.Add(nameProp);

//Addageometryproperty

Page 54: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

GeometricPropertyDefinitiongeomProp=

newGeometricPropertyDefinition("SHPGEOM","propertydesc");

geomProp.GeometryTypes=MgGeometryType.Polygon;

classDefinition.Properties.Add(geomProp);

classDefinition.GeometryProperty=geomProp;

//Createtheschemaandaddtheclassdefinition

FeatureSchemaschema=

newFeatureSchema("SHP_Schema","Schemadescription");

schema.Classes.Add(classDefinition);

Oncetheschemahasbeencreated,usetheFDOAPItocreatetheSDFfile,setthespatialcontext,andapplytheschema.Thefollowingismodifiedfromtheutilityclassesinthesampleapplications.

//Setconnectionproperties

IConnectionPropertyDictionaryconnProperties=

conn.ConnectionInfo.ConnectionProperties;

connProperties.SetProperty("File",sdfPath);

connProperties.SetProperty("ReadOnly",false.ToString());

//Createdatastore,ie.SDFfile

ICreateDataStorecreateDSCmd=

conn.CreateCommand(CommandType.CommandType_CreateDataStore)

asICreateDataStore;

createDSCmd.DataStoreProperties.SetProperty("File",sdfPath);

createDSCmd.Execute();

try

{

//Opentheconnection

ConnectionStateconnState=conn.Open();

intretryRound=0;

while(++retryRound<5//Try5times

&&(connState==ConnectionState.ConnectionState_Pending

||connState==ConnectionState.ConnectionState_Busy))

{

connState=conn.Open();

}

if(retryRound>=5)

{

thrownew

InvalidOperationException("Failedtoconnecttofile"

+sdfPath);

Page 55: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

}

//Createspatialcontext,includingcoordinate

system

AcMapMapcurrentMap=AcMapMap.GetCurrentMap();

stringmapSRS=currentMap.GetMapSRS();

ICreateSpatialContextcreateSCCmd=

conn.CreateCommand(CommandType.CommandType_CreateSpatialContext)

asICreateSpatialContext;

createSCCmd.CoordinateSystemWkt=mapSRS;

createSCCmd.Name="";

createSCCmd.CoordinateSystem=mapSRS;

createSCCmd.Extent=newbyte[]{0,0,0,0};

createSCCmd.Description="Description";

createSCCmd.XYTolerance=0.0;

createSCCmd.ZTolerance=0.0;

createSCCmd.Execute();

//Applyschema

if(schema.ElementState!=

SchemaElementState.SchemaElementState_Unchanged)

{

IApplySchemaapplySchemaCmd=

conn.CreateCommand(CommandType.CommandType_ApplySchema)

asIApplySchema;

applySchemaCmd.FeatureSchema=schema;

applySchemaCmd.Execute();

}

}

catch(System.Exceptione)

{

throwe;//Oraddexceptionhandling

}

finally

{

//Closeconnection

if(conn!=null)

{

conn.Close();

}

}

Pleasesendusyourcommentaboutthispage

Page 56: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

MapsandLayers

Topicsinthissection

OverviewBasicLayerPropertiesLayerGroupsLayerVisibilityManipulatingLayersLayerDefinition

Pleasesendusyourcommentaboutthispage

Page 57: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

Overview

Amapiscomposedoflayers,whereeachlayerrepresentsdatafromafeaturesource.

AutoCADMap3DandAutodeskMapGuidedifferinsomeofthewaystheyhandlemaplayers.BecauseMapGuideisaweb-basedmappingproduct,itmustcoordinatelayerdisplaybasedoninformationfromtheclientandtheserver.AutoCADMap3Dcanhandlealllayerdisplaydirectlyfromtheapplication.

Note TheGeospatialPlatformAPIdealsstrictlywithlayersfromFDOfeaturesources.IfamapinAutoCADMap3Dincludesotherlayers,theymustbehandledusingtheappropriatemethodsfromthe.NETAPI.

Alayer(AcMapLayerobject),hasaLayerDefinitionpropertythatpointstoalayerdefinitionintheresourcerepository.ThelayerdefinitioncontentisXMLthatconformstotheLayerDefinition.xsdLayerDefinition.xsdschema.Amongotherelements,itcontainsaResourceIdelementthatidentifiesthefeaturesourceforthelayer.

Pleasesendusyourcommentaboutthispage

Page 58: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

BasicLayerProperties

Amapcontainsoneormorelayers(AcMapLayerobjects)thatarerenderedtocreateacompositeimage.TheAcMapLayerclass,whichappliesonlytoAutoCADMap3D,isderivedfromMgLayerBase,whichispartofthecommonGeospatialPlatformAPIsharedbetweenAutoCADMap3DandMapGuide.

Eachlayerhaspropertiesthatdeterminehowitdisplaysinthemapandmaplegend.Someofthepropertiesare:

Layername:Auniqueidentifier

Visibility:whetherthelayershouldbedisplayedinthemap.Notethatactualvisibilityisdependentonmorethanjustthevisibilitysettingforalayer.SeeLayerVisibilityforfurtherdetails.

Selectable:Whetherfeaturesinthelayerareselectable.Thisonlyappliestolayerscontainingfeaturedata.Itdoesnotapplytolayerscontainingrasterdata.

AcMapMap.GetLayers()returnsanMgLayerCollectionobjectthatcontainsallthelayersinthemap.MgLayerCollection.GetItem()returnsanindividualMgLayerBaseobject,byeitherindexnumberinthecollectionorlayername.

Layersinthecollectionaresortedbydrawingorder,withthetoplayersatthebeginningofthecollection.

Pleasesendusyourcommentaboutthispage

Page 59: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

LayerGroups

Layerscanbeoptionallygroupedintolayergroups.LayersinthesamegrouparedisplayedtogetherintheDisplayManager.

Thevisibilityforalllayersinagroupcanbesetatthegrouplevel.Ifthegroupvisibilityisturnedoffthennoneofthelayersinthegroupwillbevisible,regardlessoftheirindividualvisibilitysettings.Ifthegroupvisibilityisturnedon,thenindividuallayerswithinthegroupcanbemadevisibleornotvisibleseparately.

Layergroupscanbenestedsoagroupcancontainothergroups.Thisprovidesafinerlevelofcontrolforhandlinglayervisibilityorforgroupinglayersintolegendgroups.

AcMapMap.GetLayerGroups()returnsanMgLayerGroupCollectionobjectthatcontainsallthetop-levellayergroupsinthemap.

Eachlayergroupinamapmusthaveauniquename,evenifitisnestedwithinanothergroup.

Pleasesendusyourcommentaboutthispage

Page 60: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

LayerVisibility

Whetheralayerisvisibleinagivenmapdependsonthreecriteria:

Thevisibilitysettingforthelayer

Thevisibilitysettingsforanygroupsthatcontainthelayer

Themapviewscaleandthelayerdefinitionforthatviewscale

Inorderforalayertobevisible,itslayervisibilitymustbeon,thevisibilityforanygroupcontainingthelayermustbeon,andthelayermusthaveastylesettingdefinedforthecurrentmapviewscale.

Topicsinthissection

Example:ActualVisibility

Pleasesendusyourcommentaboutthispage

Page 61: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

Example:ActualVisibility

Forexample,assumethatthereisalayernamedRoadsthatispartofthelayergroupTransportation.Thelayerhasviewstyledefinedforthescaleranges0–10000and10000–24000.

Thefollowingtableshowssomepossiblesettingsofthevariousvisibilityandviewscalesettings,andtheireffectontheactuallayervisibility.

LayerVisibility GroupVisibility ViewScale

ActualVisibility

On On 10000 On

On On 25000 Off

On Off 10000 Off

Off On 10000 Off

Pleasesendusyourcommentaboutthispage

Page 62: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

ManipulatingLayers

ModifyingbasiclayerpropertiesandchanginglayervisibilitysettingscanbedonedirectlybysettingpropertieslikeAcMapLayer.Name,AcMapLayer.Selectable,andAcMapLayer.Visible.Morecomplexmanipulationrequiresmodifyinglayerresourcesintheresourcerepository.

Topicsinthissection

ChangingVisibility

Pleasesendusyourcommentaboutthispage

Page 63: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

ChangingVisibility

Toquerytheactuallayervisibility,callAcMapLayer.IsVisible().Thereisnomethodtosetactualvisibilitybecauseitdependsonothervisibilitysettings.

Toquerythevisibilitysettingforalayer,callAcMapLayer.GetVisible().Tochangethevisibilitysettingforalayer,callAcMapLayer.SetVisible().

Toquerythevisibilitysettingforalayergroup,callAcMapLayerGroup.GetVisible().Tochangethevisibilitysettingforalayergroup,useAcMapLayerGroup.SetVisible().

Tochangethelayervisibilityforagivenviewscale,modifythelayerresourceandsaveitbacktotherepository.

Pleasesendusyourcommentaboutthispage

Page 64: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

LayerDefinition

ThefeaturesourceandstylingforalayeraresetusingaLayerDefinition,storedintheresourcerepository.ThelayerdefinitionconformstotheLayerDefinition.xsdLayerDefinition.xsdschema.Rasterlayersandvectorlayershavedifferentstylingrequirementsandcapabilities.

Forbothrasterandvectordata,asinglelayerdefinitioncancontainmultiplescaleranges,whichdefinethestylingforparticularviewscales.Forexample,avectorlayercouldhavethefollowingscaleranges:

0to10,000

10,000to500,000

500,000toinfinity

Featuresinthelayercouldbestyleddifferentlyorbehiddencompletelyforthedifferentscaleranges.

Foraavectorlayer,eachscalerangecancontainstylinginformationforthefollowing:

AreaTypeStyle,usedforpolygons

LineTypeStyle,usedforlinesandcurves

PointTypeStyle,usedforpoints

ThelayerdefinitioncanbeanyvalidXMLthatconformstotheschema.TohelpgeneratetheXML,theAutoCADMap3DsamplesuseclassesgeneratedfromLayerDefinition.xsdbyxsd.exe.

Forexample,tocreateavectorlayerdefinitionthatcontains2scaleranges,dothefollowing:

Createthetwoscaleranges.Foreach,specifytheminimumandmaximumscalefortherange.Definethenecessaryelements,likefill

Page 65: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

andstrokesettings.

Createthevectorlayerdefinition.Addthescaleranges.

Setthefeaturenametotheschema/featureclassinthefeaturesource.

Settheresourceidtopointtothefeaturesourcecontainingthelayerdata.

Setthegeometrytothegeometrypropertyofthefeatureclass.

Createalayerdefinitionthatcontainsthevectorlayerdefinition.

Storethelayerdefinitionintheresourcerepository.

Createanewlayerthatreferencesthelayerdefinition.Addthelayertothelayercollectionforthecurrentmap.

Theexamplecodethatfollowsusesthefollowingnamespacedeclarations:

usingSystem.IO(fortheStringWriterclass)

usingSystem.Text(fortheEncodingclass)

usingSystem.Xml.Serialization(forXMLserializationroutines)

usingOSGeo.MapGuide.Schema.LayerDefinition

(generatedbyxsd.exe.CodeforthisclassisavailablewiththeAutoCADMap3Dsamples.)

Thefollowingassumesthatthefeaturesourcecontainsonlypolygons.Featuresourcescontaininglineorpointdatawouldrequirestylingforthosefeaturetypesaswell.

//Createthefirstscalerange

VectorScaleRangeTyperange=newVectorScaleRangeType();

AreaRuleareaRule=newAreaRule();

AreaSymbolizationFillTypeareaSymFillType=

newAreaSymbolizationFillType();

FillTypefillType=newFillType();

fillType.FillPattern="Solid";

fillType.ForegroundColor="9900ffaa";

Page 66: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

fillType.BackgroundColor="FF000000";

StrokeTypestrokeType=newStrokeType();

strokeType.LineStyle="Solid";

strokeType.Thickness="0.0";

strokeType.Color="FF000000";

strokeType.Unit=LengthUnitType.Centimeters;

areaSymFillType.Fill=fillType;

areaSymFillType.Stroke=strokeType;

areaRule.Item=areaSymFillType;

areaRule.LegendLabel="";

object[]items=newobject[1];

items[0]=newAreaRule[]{areaRule};

range.Items=items;

range.MinScale=0.0;

range.MaxScale=10000000.0;

range.MinScaleSpecified=true;

range.MaxScaleSpecified=true;

//Secondscalerange

VectorScaleRangeTyperange2=newVectorScaleRangeType();

AreaRuleareaRule2=newAreaRule();

AreaSymbolizationFillTypeareaSymFillType2=

newAreaSymbolizationFillType();

FillTypefillType2=newFillType();

fillType2.FillPattern="Solid";

fillType2.ForegroundColor="ffffff00";

fillType2.BackgroundColor="FF000000";

StrokeTypestrokeType2=newStrokeType();

strokeType2.LineStyle="Solid";

strokeType2.Thickness="0.0";

strokeType2.Color="FF000000";

strokeType2.Unit=LengthUnitType.Centimeters;

areaSymFillType2.Fill=fillType2;

areaSymFillType2.Stroke=strokeType2;

areaRule2.Item=areaSymFillType2;

areaRule2.LegendLabel="";

object[]items2=newobject[1];

items2[0]=newAreaRule[]{areaRule2};

Page 67: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

range2.Items=items2;

range2.MinScale=10000000.0;

range2.MaxScale=Double.MaxValue;

range2.MinScaleSpecified=true;

range2.MaxScaleSpecified=true;

//Nowcreateavectorlayerdefinitionandadd

thescaleranges.

VectorLayerDefinitionTypevectorLayerDef=

newVectorLayerDefinitionType();

vectorLayerDef.VectorScaleRange=newVectorScaleRangeType[2];

vectorLayerDef.VectorScaleRange.SetValue(range,0);

vectorLayerDef.VectorScaleRange.SetValue(range2,1);

//Settheresourceidtopointtothefeature

sourcefor

//thelayer.Setthefeaturenametoafeature

classin

//thefeaturesource.Setthegeometryproperty

tothe

//defaultgeometrypropertyforthefeature

class.

vectorLayerDef.ResourceId="Library://Data/SAMPLE.FeatureSource";

vectorLayerDef.FeatureName="Schema1:FeatureClass1";

vectorLayerDef.Geometry="Geometry";

//Createalayerdefinitioncontainingthevector

layer

//definition.

LayerDefinitionlayerDef=newLayerDefinition();

layerDef.Item=vectorLayerDef;

layerDef.version="1.0.0";

//ConverttoanXMLstring.

using(StringWriterwriter=newStringWriter())

{

XmlSerializerxs=newXmlSerializer(typeof(LayerDefinition));

xs.Serialize(writer,layerDef);

//ConverttoUTF-8.

byte[]unicodeBytes=

Encoding.Unicode.GetBytes(writer.ToString());

byte[]utf8Bytes=

Encoding.Convert(Encoding.Unicode,Encoding.UTF8,

unicodeBytes);

Page 68: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

MgByteSourcesource=

newMgByteSource(utf8Bytes,utf8Bytes.Length);

//UpdatetheresourceinMap.

MgResourceServicers=

AcMapServiceFactory.GetService(MgServiceType.ResourceService)

asMgResourceService;

//Storethelayerdefinitionintherepository.

MgResourceIdentifiernewLayerDefId=

newMgResourceIdentifier(

"Library://myNewLayer.LayerDefinition");

rs.SetResource(newLayerDefId,source.GetReader(),null);

//Createanewlayerthatreferencesthelayer

definition.

//Addthistothelayersinthecurrentmap.

AcMapMapcurrentMap=AcMapMap.GetCurrentMap();

MgLayerCollectionlayers=currentMap.GetLayers();

AcMapLayerlayer;

layer=newAcMapLayer(newLayerDefId,rs);

layer.Name="testlayer";

layers.Add(layer);

}

ThiscreatesthefollowingXML:

<?xmlversion="1.0"encoding="utf-16"?>

<LayerDefinition

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:xsd="http://www.w3.org/2001/XMLSchema"

version="1.0.0">

<VectorLayerDefinition>

<ResourceId>Library://Data/SAMPLE.FeatureSource</ResourceId>

<FeatureName>Schema1:FeatureClass1</FeatureName>

<FeatureNameType>FeatureClass</FeatureNameType>

<Geometry>Geometry</Geometry>

<VectorScaleRange>

<MinScale>0</MinScale>

<MaxScale>10000000</MaxScale>

<AreaTypeStyle>

<AreaRule>

<LegendLabel/>

<AreaSymbolization2D>

<Fill>

Page 69: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

<FillPattern>Solid</FillPattern>

<ForegroundColor>9900ffaa</ForegroundColor>

<BackgroundColor>FF000000</BackgroundColor>

</Fill>

<Stroke>

<LineStyle>Solid</LineStyle>

<Thickness>0.0</Thickness>

<Color>FF000000</Color>

<Unit>Centimeters</Unit>

</Stroke>

</AreaSymbolization2D>

</AreaRule>

</AreaTypeStyle>

</VectorScaleRange>

<VectorScaleRange>

<MinScale>10000000</MinScale>

<MaxScale>1.7976931348623157E+308</MaxScale>

<AreaTypeStyle>

<AreaRule>

<LegendLabel/>

<AreaSymbolization2D>

<Fill>

<FillPattern>Solid</FillPattern>

<ForegroundColor>ffffff00</ForegroundColor>

<BackgroundColor>FF000000</BackgroundColor>

</Fill>

<Stroke>

<LineStyle>Solid</LineStyle>

<Thickness>0.0</Thickness>

<Color>FF000000</Color>

<Unit>Centimeters</Unit>

</Stroke>

</AreaSymbolization2D>

</AreaRule>

</AreaTypeStyle>

</VectorScaleRange>

</VectorLayerDefinition>

</LayerDefinition>

Topicsinthissection

LayersWithJoinedFeatureSourcesFilteringLayersByGeometryModifyingLayerStyle

Pleasesendusyourcommentaboutthispage

Page 70: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add
Page 71: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

LayersWithJoinedFeatureSources

Tocreatealayerdefinitionforalayerthatusesafeaturesourcecontainingajoin,createthelayerdefinitionasdescribedinLayerDefinition.Setthe<FeatureName>elementtothejoinnameasdefinedinthefeaturesource.Setthe<FeatureNameType>elementtoNamedExtension.Forexample,thefollowingportionofalayerdefinitionusesthejoinnamed“Parcels_Joins1”.

<?xmlversion="1.0"encoding="utf-16"?>

<LayerDefinition

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:xsd="http://www.w3.org/2001/XMLSchema"

version="1.0.0">

<VectorLayerDefinition>

<ResourceId>Library://Data/SAMPLE.FeatureSource</ResourceId>

<FeatureName>Parcels_Joins1</FeatureName>

<FeatureNameType>NamedExtension</FeatureNameType>

SeeJoinsfordetailsaboutthefeaturesourcedefinition.

Pleasesendusyourcommentaboutthispage

Page 72: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

FilteringLayersByGeometry

Thelayerdefinitionforavectorlayercanincludea<Filter>elementtoselectonlycertainfeatures.ThefilterisastringthatcontainsavalidFDOselectionexpression.SeeSelectingUsingtheAPIforadescriptionoffilters.

Forexample,assumethefollowing:

geomPolyisanMgPolygonrepresentingtheareaofinterest.

geometryisthedefaultgeometrypropertyforafeatureclass.

Thefollowingcreatesafiltertoselectonlythosefeaturesthatintersectthepolygon.

MgWktReaderWriterrw=newMgWktReaderWriter();

stringwktGeom=rw.Write(geomPoly);

stringfilter="geometryintersectsGeomFromText("+

wktGeom+")");

TomodifythesampleinLayerDefinitiontousethefilter,setthe<Filter>elementasfollows:

vectorLayerDef.Filter=filter;

Pleasesendusyourcommentaboutthispage

Page 73: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

ModifyingLayerStyle

Tomodifythestylingforalayer,retrievethelayerdefinitionfromtherepository,makechangestoit,storeitbacktotherepository,andrefreshthelayer.

Toretrievethelayerdefinition,getitsresourceidentifierfromthemaplayer.GettheresourcecontentanddeserializeitusinganXmlSerializerobject.

AcMapMapcurrentMap=AcMapMap.GetCurrentMap();

MgLayerCollectionlayers=currentMap.GetLayers();

MgResourceServicers=

AcMapServiceFactory.GetService(MgServiceType.ResourceService)

asMgResourceService;

//Getthelayerdefinition.ConvertittoanXMLstring

//storedinabytereader.

AcMapLayerlayer1=layers.GetItem(layerName)asAcMapLayer;

MgResourceIdentifierlayerDefId=layer1.GetLayerDefinition();

MgByteReaderlayerReader=rs.GetResourceContent(layerDefId);

//DeserializeittocreateaLayerDefinitionobject.

XmlSerializerlayerDefSerializer=new

XmlSerializer(typeof(LayerDefinition));

LayerDefinitionxmlLayerDef=

layerDefSerializer.Deserialize(new

StringReader(layerReader.ToString()))

asLayerDefinition;

UpdatingtheLayerDefinitionobjectissimilartocreatinganewone.Findthecorrectelementsandsettheirvalues.Forexample,thefollowingchangestheforegroundcolorforthearearuleinthefirstscalerange,thenitupdatesthelayerdefinitionintheresourcerepositoryandrefreshesthelayer.

//ShouldbeaVectorLayerDefinitionType

if(xmlLayerDef.ItemisVectorLayerDefinitionType)

{

Page 74: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

VectorLayerDefinitionTypexmlVectorLayerDef=

xmlLayerDef.ItemasVectorLayerDefinitionType;

//Checktherulesforthefirstscalerange.

//Onlyupdaterulesiftheyarethecorrecttype.

object[]items=xmlVectorLayerDef.VectorScaleRange[0].Items;

foreach(objectiteminitems)

{

Typetype=item.GetType();

if(type.Name==typeof(AreaRule[]).Name)

{

AreaRule[]areaRules=itemasAreaRule[];

//OK,gotthecorrectarearule.Settheforegroundcolor.

if(areaRules.Length>0)

{

areaRules[0].Item.Fill.ForegroundColor=newColor;

}

}

}

//NowconvertitbacktoanXMLstringandupdatethe

//resource.

using(StringWriterwriter=newStringWriter())

{

//Getthexmlstring

layerDefSerializer.Serialize(writer,xmlLayerDef);

//Createtheresource

byte[]unicodeBytes=

Encoding.Unicode.GetBytes(writer.ToString());

byte[]utf8Bytes=

Encoding.Convert(Encoding.Unicode,

Encoding.UTF8,unicodeBytes);

MgByteSourcesource=

newMgByteSource(utf8Bytes,utf8Bytes.Length);

//UpdatetheresourceinMap

rs.SetResource(layer1.LayerDefinition,

source.GetReader(),null);

layer1.ForceRefresh();

}

}

Page 75: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

Pleasesendusyourcommentaboutthispage

Page 76: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

Geometry

Topicsinthissection

OverviewGeometryObjectsComparingGeometryObjectsCoordinateSystemsMeasuringDistanceCreatingaBuffer

Pleasesendusyourcommentaboutthispage

Page 77: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

Overview

TheAutoCADMap3DGeospatialPlatformAPIincludesacompletesetofclassesforworkingwithgeometry.Thisincludesthefollowing:

Describingsimpleandcomplexgeometricobjects

Performingspatialcomparisonsbetweenobjects

Creatingnewobjectsbasedontheintersection,difference,orunionofexistingobjects

Convertingbetweendifferentcoordinatesystems

Creatingbuffersaroundobjects

Pleasesendusyourcommentaboutthispage

Page 78: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

GeometryObjects

MgGeometryisthebaseclassforallthegeometrytypes.Thesimplegeometrytypesare:

MgPoint—asinglepoint

MgLineString—aseriesofconnectedlinesegments

MgCurveString—aseriesofconnectedcurvesegments

MgPolygon—apolygonwithsidesformedfromlinesegments

MgCurvePolygon—apolygonwithsidesformedfromcurvesegments

Thecurvesegmentsarecirculararcs,definedbyastartpoint,anendpoint,andacontrolpoint.

Complextypesareformedbyaggregatingsimpletypes.Thecomplextypesare:

MgMultiPoint—agroupofpoints

MgMultiLineString—agroupoflinestrings

MgMultiCurveString—agroupofcurvestrings

MgMultiPolygon—agroupofpolygons

MgMultiCurvePolygon—agroupofcurvepolygons

MgMultiGeometry—agroupofsimplegeometryobjectsofanytype

Pleasesendusyourcommentaboutthispage

Page 79: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

ComparingGeometryObjects

TheMgGeometryclasscontainsmethodsforcomparingdifferentgeometryobjects.ThesearesimilartothespatialfiltersdescribedinSelectingUsingtheAPI.Methodstotestspatialrelationshipsinclude:

Contains()

Crosses()

Disjoint()

Equals()

Intersects()

Overlaps()

Touches()

Within()

Forexample,ifyouhaveanMgLineStringobjectlineandanMgPolygonobjectpolygon,youcantestifthelinecrossesthepolygonwithacallto

line.Crosses(polygon)

Methodstocreatenewgeometryobjectsfromthepointsetoftwoothergeometriesinclude:

Difference()

Intersection()

SymmetricDifference()

Union()

Page 80: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

CompletedetailsareintheGeometrymoduleoftheGeospatialPlatformAPIreference,underSpatialRelationships.

Pleasesendusyourcommentaboutthispage

Page 81: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

CoordinateSystems

Asinglemapwilloftencombinedatafromdifferentsources,andthedifferentsourcesmayusedifferentcoordinatesystems.Themaphasitsowncoordinatesystem,andanyfeaturesourcesusedinthemapmayhavedifferentcoordinatesystems.Itisimportantfordisplayandanalysisthatalllocationsaretransformedtothesamecoordinatesystem.

Note Acoordinatesystemcanalsobecalledaspatialreferencesystem(SRS)oracoordinatereferencesystem(CRS).ThisguideusestheabbreviationSRS.

AutoCADMap3Dsupportsthreedifferenttypesofcoordinatesystem:

ArbitraryX-Y

Geographic,orlatitude/longitude

Projected

AnMgCoordinateSystemobjectrepresentsacoordinatesystem.

Note YoucannottransformbetweenarbitraryX-Ycoordinatesandeithergeographicorprojectedcoordinates.

TocreateanMgCoordinateSystemobjectfromanAcMapMapobject,

GettheWKTrepresentationofthemapcoordinatesystem,usingAcMapMap.GetMapSRS().

CreateanMgCoordinateSystemobject,usingMgCoordinateSystemFactory.Create().

TocreateanMgCoordinateSystemobjectfromamaplayer,

Getthefeaturesourceforthelayer.

Gettheactivespatialcontextforthefeaturesource.

ConvertthespatialcontexttoaWKT.

Page 82: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

CreateanMgCoordinateSystemobjectfromtheWKT.

Totransformgeometryfromonecoordinatesystemtoanother,createanMgCoordinateSystemTransformobjectusingthetwocoordinatesystems.ApplythistransformtotheMgGeometryobject.

Forexample,ifyouhavegeometryrepresentingafeatureonalayerthatusesonecoordinatesystem,andyouwanttocompareittoafeatureonanotherlayerthatusesadifferentcoordinatesystem,performthefollowingsteps:

stringfeatureSource1=layer1.GetFeatureSourceId();

MgSpatialContextsReadercontexts1=

featureService.GetSpatialContexts(

featureSource1,true);

contexts1.ReadNext();

stringsrs1=contexts1.GetCoordinateSystemWkt();

stringfeatureSource2=layer2.GetFeatureSourceId();

MgSpatialContextsReadercontexts2=

featureService.GetSpatialContexts(

featureSource2,true);

contexts2.ReadNext();

stringsrs2=contexts2.GetCoordinateSystemWkt();

MgCoordinateSystemFactorycoordsysFactory=

newMgCoordinateSystemFactory();

MgCoordinateSystemTransformxform=

coordsysFactory.GetTransform(srs1,srs2);

MgGeometrygeometry1xform=geometry1.Transform(xform);

Pleasesendusyourcommentaboutthispage

Page 83: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

MeasuringDistance

Measuringdistanceingeographicorprojectedcoordinatesystemsrequiresgreatcirclecalculations.BothMgGeometry.Buffer()andMgGeometry.Distance()acceptameasurementparameterthatdefinesthegreatcircletobeused.Ifthemeasurementparameterisnull,thecalculationisdoneusingalinearalgorithm.

Createthemeasurementparameter,anMgCoordinateSystemMeasureobject,fromtheMgCoordinateSystemobject.

DistanceiscalculatedintheunitsoftheSRS.MgCoordinateSystemincludestwomethods,ConvertCoordinateSystemUnitsToMeters()andConvertMetersToCoordinateSystemUnits(),toconverttoandfromlineardistances.

Forexample,tocalculatethedistancebetweentwoMgGeometryobjectsaandb,usingthecoordinatesystemsrs,performthefollowingsteps:

MgCoordinateSystemMeasuremeasure=srs.GetMeasure();

doubledistInMapUnits=a.Distance(b,measure);

doubledistInMeters=srs.ConvertCoordinateSystemUnitsToMeters(

distInMapUnits);

AnotherwaytocalculatethedistanceistouseMgCoordinateSystemMeasure.GetDistance(),asinthefollowing:

distInMapUnits=measure.GetDistance(a,b);

Pleasesendusyourcommentaboutthispage

Page 84: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

CreatingaBuffer

Tocreateabufferaroundafeature,usetheMgGeometry.Buffer()method.ThisreturnsanMgGeometryobjectthatyoucanuseforfurtheranalysis.Forexample,youcoulddisplaythebufferbycreatingafeatureinatemporaryfeaturesourceandaddinganewlayertothemap.Youcouldalsousethebuffergeometryaspartofaspatialfilter.Forexample,youmightwanttofindallthefeatureswithinthebufferzonethatmatchcertaincriteria,oryoumightwanttofindallroadsthatcrossthebufferzone.

Tocreateabuffer,getthegeometryofthefeaturetobebuffered.IfthefeatureisbeingprocessedinanMgFeatureReaderaspartofaselection,thisrequiresgettingthegeometrydatafromthefeaturereaderandconvertingittoanMgGeometryobject.Forexample:

MgByteReadergeometryData=

featureReader.GetGeometry(geometryName);

MgGeometryfeatureGeometry=agfReaderWriter.Read(geometryData);

Ifthebufferistobecalculatedusingcoordinatesystemunits,createanMgCoordinateSystemMeasureobjectfromthecoordinatesystemforthemap.Forexample:

stringmapWktSrs=currentMap.GetMapSRS();

MgCoordinateSystemFactorycoordSysFactory=

newMgCoordinateSystemFactory();

MgCoordinateSystemsrs=coordSysFactory.Create(mapWktSrs);

MgCoordinateSystemMeasuresrsMeasure=srs.GetMeasure();

Usethecoordinatesystemmeasuretodeterminethebuffersizeinthecoordinatesystem,andcreatethebufferobjectfromthegeometrytobebuffered.

doublesrsDist=

srs.ConvertMetersToCoordinateSystemUnits(bufferDist);

MgGeometrybufferGeometry=

featureGeometry.Buffer(srsDist,srsMeasure);

Page 85: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

Todisplaythebufferinthemap,performthefollowingsteps:

Createafeaturesourceforthebuffer.Thismayrequirecreatinganewfileforthefeaturesource.SeeCreatingSDFfiles.

Createalayerthatreferencesthefeaturesource.Addittothemapandmakeitvisible.

Createanewfeatureusingthebuffergeometryandinsertitintothefeaturesource.

Forexample,thefollowingcodeassumesthatthelayerresLayerhasbeencreatedusingafeaturesourcewithageometrypropertyofGeometry.Itaddsanewfeatureusingthebuffergeometry.

MgPropertyCollectionproperties=newMgPropertyCollection();

properties.Add(newMgGeometryProperty("Geometry",

agfReaderWriter.Write(bufferGeometry)));

MgFeatureCommandCollectioncommands=

newMgFeatureCommandCollection();

commands.Add(newMgInsertFeatures(resFeatureClassName,

properties));

resLayer.UpdateFeatures(commands);

Tousethebufferaspartofaquery,createaspatialfilterusingthebuffergeometry,andusethisinacalltoAcMapLayer.SelectFeatures().Forexample,thefollowingcodeusesabasicfilterandaspatialfiltertoselectparcelsinsidethebufferareathatareoftype“MFG”.YoucanusetheMgFeatureReadertoperformtaskslikegeneratingareportoftheparcels,orcreatinganewlayerthatputspointmarkersoneachparcel.

MgFeatureQueryOptionsqueryOptions=newMgFeatureQueryOptions();

queryOptions.SetFilter("PARCELTYPE='MFG'");

queryOptions.SetSpatialFilter('SHPGEOM',bufferGeometry,

MgFeatureSpatialOperations.Inside);

MgResourceIdentifierfeatureResId=newMgResourceIdentifier(

"Library://Data/Parcels.FeatureSource");

MgFeatureReaderfeatureReader=

layer.SelectFeatures(queryOptions);

Page 86: AutoCAD Map 3D 2009 Geospatial Platform … Up Visual Studio To use the Geospatial Platform API, follow the instructions in the AutoCAD Map 3D ObjectARX .NET Developer’s Guide. Add

Pleasesendusyourcommentaboutthispage