Getting Started in VB
Getting Started in VB
Copyright 2001 ESRI All Rights Reserved. Printed in the United States of America. The information contained in this document is the exclusive property of ESRI. This work is protected under United States copyright law and the copyright laws of the given countries of origin and applicable international laws, treaties, and/or conventions. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying or recording, or by any information storage or retrieval system, except as expressly permitted in writing by ESRI. All requests should be sent to Attention: Contracts Manager, ESRI, 380 New York Street, Redlands, CA 92373-8100, USA. The information contained in this document is subject to change without notice. U. S. GOVERNMENT RESTRICTED/LIMITED RIGHTS Any software, documentation, and/or data delivered hereunder is subject to the terms of the License Agreement. In no event shall the U.S. Government acquire greater than RESTRICTED/LIMITED RIGHTS. At a minimum, use, duplication, or disclosure by the U.S. Government is subject to restrictions as set forth in FAR 52.227-14 Alternates I, II, and III (JUN 1987); FAR 52.227-19 (JUN 1987) and/or FAR 12.211/12.212 (Commercial Technical Data/Computer Software); and DFARS 252.227-7015 (NOV 1995) (Technical Data) and/or DFARS 227.7202 (Computer Software), as applicable. Contractor/Manufacturer is ESRI, 380 New York Street, Redlands, CA 92373-8100, USA. SAMPLE DATA LICENSE AND DISCLAIMER The sample data included in this package is the exclusive property and copyright of ESRI, and the respective data publishers. The sample data is protected under United States copyright law and other international copyright treaties and conventions. The sample data is provided under license from each of the respective data publishers for the Licensees own internal use. Licensee shall not sell, rent, lease, sublicense, lend, assign, time-share, or transfer, in whole or in part, or provide unlicensed third parties access to the sample data or portions of the data, documentation or metadata, any updates, or Licensees rights under this Agreement. The sample data herein has been obtained from sources believed to be reliable, but their accuracy and completeness, and the opinions based thereon, are not guaranteed. ESRI is not inviting reliance on the sample data, and you should always verify actual data and information. The sample data contained in this package is subject to change without notice. THE SAMPLE DATA IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ESRI shall not be liable for indirect, special, incidental, or consequential damages related to Licensees use of the sample data, even if ESRI is advised of the possibility of such damage. ESRI and the ESRI globe logo are trademarks of ESRI, registered in the United States and certain other countries; registration is pending in the European Community. ArcObjects, ArcSDE, ArcInfo, ArcMap, and ArcGIS are trademarks of ESRI. Other companies and products mentioned herein are trademarks or registered trademarks of their respective trademark owners.
Contents
Introduction Loading the Map control Using the Map control Adding pan and zoom controls Adding a toolbar Creating a find tool Handling resize Displaying map layers based on scale Adding a spatial query tool Event tracking Adding layers programmatically Working with RasterLayer objects Using ESRI tools and commands Congratulations
5 6 8 10 12 15 17 18 19 20 23 24 25 28
Getting Started
IN THIS BOOK Loading the Map control into Visual Basic Adding simple display tools Creating basic spatial query tools Displaying map layers Tracking events Adding an image layer Working with ESRI commands and tools
Introduction
In this introductory document you will use the ESRI Map control and Microsoft Visual Basic to build an application that uses maps. Along the way you will learn how to
Display a map with multiple layers. Control panning and zooming. Create a Toolbar control. Display map layers based on scale. Perform spatial and logical queries. Draw simple graphics on the map. Display features with thematic renderers. Dynamically display real-time event tracking. Programmatically add data to a map. Add Identify and Query commands from the sample AfCommandsVB library.
Note: If you accepted the defaults when installing ArcObjects, the geographic data this tutorial refers to can be found in C:\Arcexe81\ArcObjects Developer Kit\Samples\Data\Usa. The bitmaps you can use are in the C:\Arcexe81\Bin\Icons folder.
Getting help The Map control is an ActiveX control that is provided by ESRI as part of the ArcObjects development toolkit. To find out about the available methods, properties, and events that are provided with the Map control, click the Object Browser button in the Visual Basic toolbar (or hit F2). Pull down the Project/Library box and choose esriControlsCtl.
Tip: You can also add controls by selecting Components from the Project menu or by pressing Ctrl+T.
Find ESRI ArcObjects Controls 8.1 in the list of available controls and check the box beside it. Click OK to close the dialog. Notice that a new tool appears in the Visual Basic Toolbox. This new tool is the ArcObjects Controls Version 8.1 Map control.
The esriControls objects and constants are listed in the Classes bottom left-hand list. Click on the Map control object in the list, and its properties and methods are listed in the Members list to the right. Likewise, click on a method in the right-hand list to see the
Tip: The simplest way to get help is to select the Map control and press F1.
method signature. The details will appear in the space at the bottom of the Object Browser. The ArcObjects online help system is also integrated with the Visual Basic Object Browser.
1. Click MapControl in the Classes/Modules list. 2. Click VisibleRegion in the Methods/Properties list. 3. Click the help (question mark) button.
Adding the ESRI Object Library To fully access all available ArcObjects components in your Visual Basic project, you will need to add a Reference to the ESRI Object Library to your project. To do this, pull
down the Project menu and select References. Find and check ESRI Object Library in the list of available references. Again, from within the Object Browser, you can see all the available objects and components in ArcObjects by selecting esriCore from the Project/Library box.
The help system provides help for every object, property, method, event, and constant in ArcObjects. In addition to the Object Browser, the help system is accessible from the Visual Basic code window. Simply type in the name of an object, property, method, event, or constant and press F1.
Select the data to display on the map You can specify the data that is displayed on the map by setting properties in the MapControls Property Page.
1. Right-click the mouse on the map to display the context menu. 2. Choose Properties to display the Property Pages. 3. Click the Add button and locate the folder containing the states sample data. 4. Click the states.shp file and then click Add. 5. Add the file ushigh.shp in the same manner. 6. Use the Up and Down arrows to ensure that the ushigh layer is at the top of the list.
You can also specify how the data is displayed on the Map by using this Property Page.
You can double-click on the colors to display the Color dialog box.
4. Click OK to close the Property Page.
Click on the Symbology tab. Click the Symbol button. Select a red color and click OK to dismiss the Layer Properties dialog.
3. Now define a renderer for the States layer:
Select States from the list of layers. Click on the Symbology tab. In the Symbology tab select Categories and then click on Unique values. Make SUB_REGION the Value field and click on the Add All Values button.
TrackRectangle is a method that applies to the Map control. It tracks the movement of the mouse while the user keeps the mouse button pressed, rubber-banding a rectangle at the same time. When the user releases the mouse button, the TrackRectangle method returns an IEnvelope object that the application then assigns to the Extent property of the map, causing the map to be redrawn with a new map extent.
3. Release the mouse button and notice that the map is redrawn at the location you specified. 4. Click the Stop button in Visual Basic to return to design mode.
Add panning
1. Double-click the map to display the Visual Basic code window again. 2. Change the code for the OnMouseDown event.
10
Private
Sub
MapControl1_OnMouseDown(
ByVal button As Long, _ ByVal shift As Long, _ ByVal x As Long, _ ByVal y As Long, _ ByVal mapX As Double, _ ByVal mapY As Double) If Button = vbLeftButton Then MapControl1.Extent = _ MapControl1.TrackRectangle ElseIf Button = vbRightButton Then MapControl1.Pan End If End Sub
5. Resize the Map control so that it is not obscured by the button. 6. Double-click the Full Extent button to display the code window. 7. Add code for the Click event.
Private Sub Command1_Click() MapControl1.Extent = MapControl1.FullExtent End Sub
If the Button parameter is equal to vbLeftButton when the OnMouseDown event occurs, then the zooming code from the previous step will be executed. Otherwise, the code will call another Map control method, Pan. If the user clicks the left mouse button, the Button parameter will be vbLeftButton. If the user clicks the right mouse button, the value of Button will be vbRightButton. Add a FullExtent button Your application now supports panning and zooming but, once the user has zoomed into the map, there is no way to get back to the full extent again. In this section you will add a button to the form that zooms the map to the full extent.
1. Double-click the CommandButton button in the Toolbox to add a button to the form. 2. Move the button to the upper right of the form. 3. Press F4 to display the Properties window. 4. Click in the Caption box and type Full Extent to change the buttons caption.
8. Finally, when you are in Design mode, use the Visual Basic Properties box to change two properties of the Map control set ShowScrollBars to False and choose a color for MapControls BackColor property.
The FullExtent property of the Map returns a reference to an IEnvelope that defines the bounding box of all the layers in the Map. Test your change
1. Click the Run button in the Visual Basic toolbar. 2. Click the map with the left mouse button and drag out a rectangle. 3. Release the mouse button to redraw the map.
11
4. Click the map with the right mouse button and drag to pan the map. 5. Release the mouse button to redraw the map. 6. Click the Full Extent button to redraw the map at the full extent.
The ImageList control may obscure the map; however, this is not a problem because the ImageList control will not be visible when your application is running.
Adding a toolbar
Visual Basic includes a Toolbar control that can be used in conjunction with an ImageList control to display a collection of buttons at the top of a form. We shall use the Visual Basic Toolbar for this starter application. The current applications pan and zoom functionality is somewhat hidden from the user. In this section, you will create a toolbar with Pan and Zoom buttons. Adding a toolbar
1. Delete the Full Extent button from the form. 2. Bring up the Components dialog by pressing Ctrl+T. Select Microsoft Windows Common Controls. You will notice new tools are added to your toolbox. 3. Double-click the Toolbar button in the toolbox to add a Toolbar control to the form. 4. Double-click the ImageList button in the toolbox to add an ImageList control to the form. 5. Resize the map so that it is not obscured by the toolbar.
12
4. Click Insert Picture and locate the folder that contains the sample bitmaps. This should be the Icons directory within the ArcGIS Bin folder. 5. Click the zoom_in_tool_1.bmp file and then click Open. 6. Add a descriptive Key, for example, Zoom. This will correspond with Keys that will be used when adding buttons to the Toolbar control. 7. Add the files pan_1.bmp, globe_3.bmp, select_by_polygon.bmp, flag.bmp, information.bmp, and selection_1.bmp in the same manner. The Keys should be FullExtent, SelectByPolygon, TrackEvent, Identify, and Query, respectively.
2. Click Properties to display the Property Pages. 3. In the ImageList box, click the arrow and then click ImageList1. This associates the toolbar with the ImageList control.
Adding buttons to the Toolbar control In this section you will add seven buttons to the toolbar.
1. In the Toolbar Control Properties dialog, click the Buttons tab, then click Insert Button. 2. Set the buttons style to ButtonGroup, its Image to Zoom, its Key to Zoom, and its Value to Pressed. Add suitable Tool Tips. 3. Add a second button and set its Style to ButtonGroup, its Image to 2, and its Key to Pan. 4. Add five more buttons and associate them with the remaining images in the ImageList, setting their Style to ButtonGroup (add Separators if you wish). The Keys should be FullExtent, SelectByPolygon, TrackEvent, Identify, and Query, respectively. 5. Click OK to dismiss the Property Pages.
Set the MaskColor of the ImageList Setting the MaskColor property of an ImageList control specifies a color that will act as a mask for any images contained by the control. The mask color will not be drawn, resulting in an image with a transparent background.
1. Click the Color tab. 2. In the Properties list, click MaskColor. 3. Click Magenta in the Color Palette list and then click OK to dismiss the Property Pages.
Associate the ImageList with the toolbar You can associate the Toolbar control with an ImageList control to provide the graphic images for the buttons.
1. Right-click the Toolbar control to display the context menu.
13
Private Sub Toolbar1_ButtonClick(ByVal Button _ As MSComCtlLib.Button) With MapControl1 Select Case Button.Key Case "Zoom" .MousePointer = esriPointerZoomIn Case "Pan" .MousePointer = esriPointerPan Case "FullExtent" .MousePointer = esriPointerDefault .Extent = MapControl1.FullExtent End Select End With End Sub
Selecting the first button in the toolbar sets the mouse to be a zoom tool; selecting the second button lets you use the mouse to pan. The Toolbar ButtonClick Event Handler In this section you will implement the handler for the ButtonClick event that is generated whenever a click occurs on a button in the toolbar. We will add code to change the MapControls MousePointer depending on what tool has been selected, providing useful feedback to the user. We shall also reimplement the Full Extent button that you deleted. Within the event handler we will be using a Case statement with switches, depending on the Key value of the button that you defined earlier.
1. Double-click the toolbar to display the code window. 2. Add the following code to Toolbar1s ButtonClick event.
14
4. Click somewhere on the map and then drag to pan. 5. Click on the Full Extent button (the globe) in your applications toolbar.
4. Double-click the TextBox button in the toolbox to add a TextBox to the form and position it next to the label. 5. Clear the Text property of the TextBox using the Properties window. 6. Resize the map so that it is not obscured by the new controls.
Attach code to the TextBox You will use the text the user types into the TextBox to perform a logical query.
1. Double-click the TextBox to show the code window. 2. Add code to Text1s KeyPress procedure by selecting KeyPress from the right-hand dropdown list:
Private Sub Text1_KeyPress(KeyAscii As Integer) If KeyAscii = vbKeyReturn Then ' Find the States layer Dim i As Integer Dim pFeatLyr As IFeatureLayer For i = 0 To MapControl1.LayerCount - 1 Set pFeatLyr = MapControl1.Layer(i) If pFeatLyr.Name = "states" Then ' Found it and exit loop Exit For End If Next i ' Create a string to use in the query Dim queryStr As String queryStr = "STATE_NAME = '" & Text1.Text & "'" ' Create the query filter Dim pQueryFltr As IQueryFilter Set pQueryFltr = New QueryFilter pQueryFltr.WhereClause = queryStr
15
' Perform the selection Dim pFeatSeln As IFeatureSelection ' QI for IFeatureSelection from the ' IFeatureLayer _ False Set pFeatSeln = pFeatLyr pFeatSeln.SelectFeatures pQueryFltr, ' Get the selection set Dim pSelSet As ISelectionSet Set pSelSet = pFeatSeln.SelectionSet ' Get the cursor from the selection set Dim pFeatCursor As IFeatureCursor pSelSet.Search Nothing, True, pFeatCursor ' Assume only one feature Dim pFeature As IFeature Set pFeature = pFeatCursor.NextFeature If Not pFeature Is Nothing Then ' Get the extent of the selected feature Dim pExtent As IEnvelope Set pExtent = pFeature.Shape.Envelope ' And set the Map control's extent MapControl1.Extent = pFeature.Shape.Envelope End If End If End Sub esriSelectionResultNew,
The code locates the States layer and defines a simple SQL query expression using the value of the Text property of the TextBox. The States layers IFeatureSelection uses this query to search for the specified value. You can obtain an IFeatureCursor that contains all features from the IFeatureSelection. Here we assume the cursor contains only one feature, from which we will derive the geometry and its extent envelope. We will use this envelope to reset the MapControls Extent.
GETTING STARTED WITH THE MAP CONTROL USING VISUAL BASIC
16
Handling resize
When you run your application and resize the form, you will notice that the map is not automatically resized. Respond to the Resize event
1. Double-click the form to display the code window. 2. Add code to the forms Resize procedure by selecting Resize from the right-hand dropdown list:
Private Sub Form_Resize() If (ScaleWidth <> 0) Then ' y coord for Text and Label Dim yFind As Integer ' a constant spacing Dim space As Integer space = Text1.Top - (MapControl1.Top _ + MapControl1.Height) yFind = ScaleHeight - Text1.Height - space ' x coord for Text and Label Dim xFind As Integer xFind = ScaleWidth - Text1.Width Dim mapTop As Integer mapTop = Toolbar1.Top + Toolbar1.Height Dim mapHeight As Integer mapHeight = yFind - space - mapTop If (mapHeight > 0) Then ' move all the controls Text1.Move xFind, yFind Label1.Move xFind - _ Label1.Width - 20, yFind MapControl1.Move 0, mapTop, _
3. Double-click the form to show the code window. 4. Add code to the forms Load procedure.
Private Sub Form_Load() Form_Resize End Sub
When the user resizes the form, the code resizes the controls using the Move method. Notice that when you run your application it redraws the map twice initially. This is due to the fact that controls on the form are initially displayed using the size and position specified during design time. To fix this problem, you will resize the controls when the form is initialized. You have already written the code to resize the controls, so you just need to call the procedure.
17
Click on the Symbology tab. Select Categories, Unique Values. Make STATE_NAME the Value Field and click on Add All Values button.
6. Click OK to dismiss the Layer Properties dialog. 7. Click OK to dismiss the Property Page.
If you run your application now, you will notice that it displays every county in the United States. At the full extent there is no need to display that much detail. You can use the MinimumScale and MaximumScale properties on the ILayer interface to selectively make the Counties and States layers visible or invisible, depending on the current scale of the map.
Because this code executes in the application startup phase, the scale breaks are set up once. If the code were added in response to the OnBeforeDraw event, the layers would be made visible or invisible just before each drawing operation. This may unnecessarily invalidate any drawing caches, which in turn will make the redraw inefficient. Think carefully about what code you place in the OnBeforeDraw event.
18
3. Click the FullExtent button and the Counties are no longer visible.
With MapControl1 .Map.ClearSelection .Refresh esriViewGeoSelection .Map.SelectByShape pSearchShape, Nothing, False ' And refresh the map .Refresh esriViewGeoSelection End With End Sub
19
Event tracking
Some applications must display geographic entities on top of the map, especially if those entities have a tendency to move. For example, a vehicle tracking system would want to display vehicles on the map at the appropriate locations and update those locations over time without redrawing all the underlying layers of the map each time a vehicle changes location. In this section, you will add event tracking layer elements to your application to facilitate this requirement. We have already added the required toolbar button (the Flag at toolbar button number five), and now we shall implement the tool. Implement the Event tool
1. Add a private member variable to the General section of the Forms code window. This will be an ElementCollection that will be used to hold your events.
Private m_pElementCollection As IElementCollection
Optionally, from the Property Pages, display the Layer Properties dialog to modify the default Selection Symbol for each layer. Set it to a yellow solid fill.
4. Modify the MapControl1s OnMouseDown procedure to call AddGeoEvent, passing in the mapX and mapY coordinates. These are already in Map units.
ElseIf .Item("TrackEvent").Value = tbrPressed Then AddGeoEvent mapX, mapY
20
Implement the AddGeoEvent procedure The AddGeoEvent procedure adds a new element where the mouse click occurred. Add the following code to the General section of the Forms code window.
Private Sub AddGeoEvent(mapX As Double, mapY As Double) ' Make the point Dim pPoint As IPoint Set pPoint = New Point pPoint.PutCoords mapX, mapY ' Make the element Dim pElement As IElement Set pElement = New MarkerElement pElement.Geometry = pPoint ' Add the element to the collection m_pElementCollection.Add pElement ' And finally redraw the map MapControl1.Refresh esriViewForeground End Sub
Add a timer to your form To trigger the movement of the events, a Timer control will be used. The Visual Basic function Rnd is used to generate a random number to move the events in a random manner.
1. Double-click the Timer button in the toolbox to add a timer to the form. The Timer control will not be visible when your application is running. 2. Double-click the timer to display the code window. 3. Add code to the timer procedure.
Private Sub Timer1_Timer() Dim maxDist As Double Dim nEventCount As Integer Dim pt As IPoint maxDist = MapControl1.Extent.Width / 20 nEventCount = m_pElementCollection.Count Dim newX As Double Dim newY As Double Dim i As Integer ' If the collection is not empty Dim pGeometry As IPoint If (nEventCount > 0) Then
Drawing the events After the layers draw, we iterate through the collection of events to draw each, in turn, using the MapControls DrawShape method. Add this code to the OnAfterDraw Event procedure.
Private Sub MapControl1_OnAfterDraw(ByVal display As esriCore.IDisplay, ByVal phase As esriCore.esriViewDrawPhase) If (phase = esriViewForeground) Then Dim pElement As IElement Dim i As Integer For i = 0 To m_pElementCollection.Count - 1 m_pElementCollection.QueryItem i, pElement MapControl1.DrawShape pElement.Geometry
21
Dim pElement As IElement ' Iterate the collection For i = 0 To nEventCount - 1 m_pElementColn.QueryItem i, pElement Set pGeometry = pElement.Geometry ' Generate a new random position newX = pGeometry.x - (maxDist * (Rnd - 0.5)) newY = pGeometry.y - (maxDist * (Rnd - 0.5)) ' And update the element pGeometry.PutCoords newX, newY pElement.Geometry = pGeometry Next i MapControl1.Refresh End If End Sub esriViewForeground
Modify Form_Resize Modify the Form_Resize method to move the CheckBox when the form is resized. Just before the Text1 and Label1 controls are moved, insert the code for moving the Check1 control.
' Move all the controls Check1.Move 0, yFind Text1.Move xFind, yFind
Add a CheckBox to your form To turn the timer on or off, you will add a CheckBox control to your application.
1. Double-click the CheckBox button in the toolbox to add a CheckBox to the form. 2. Move the CheckBox to the lower left corner of the form. 3. Open the Properties window and set the Caption to Data Collection. 4. Double-click the CheckBox control to open the code window. 5. Add code to Check1s Click procedure.
Private Sub Check1_Click() Timer1.Interval = Check1.Value * 500 End Sub
22
The example code that follows loads three layers using two of the above methods. Ensure that you change the paths to the data to match your installation. Remove the existing layers
1. Right-click the mouse on the map to display the context menu. 2. Choose Properties to display the Property Pages. 3. Click on the ushigh layer, then click Delete to remove the layer. 4. Remove counties and states in the same manner, then click OK.
23
"C:\Data\USA",
"USHigh"
Select an image layer to display on the map You can specify an image to display as a RasterLayer by setting properties in the MapControls Property Pages.
1. Right-click the mouse on the map to display the context menu. 2. Choose Properties to display the Property Pages. 3. Click the Add button and then select Raster datasets from the Show of type combo box. 4. Navigate to a data folder that contains raster datasets. If you have the ESRI Data & Maps CD, you can use the sample image wsiearth.tif. 5. Click on the raster dataset file, then click Add. 6. If you still have other datasets listed in your Property Pages, use the arrow buttons to ensure that the raster data is at the bottom of the list.
2. To ensure that the MapControls MousePointer correctly reflects the startup status of the Toolbar, insert the following line after the call to InitializeMap:
MapControl1.MousePointer = esriPointerZoomIn
24
Adding a RasterLayer programmatically Previously, you added feature layers programmatically; now you will add a RasterLayer programmatically. Remove the existing layers
1. Right-click the mouse on the map to display the context menu and click on Properties to display the Property Pages. 2. Select wsiearth.tif (or the raster dataset you selected), then click Delete.
We have already added an Identify button on the toolbar. Now we need to make three modifications. Firstly, we define a Private member variable to hold our Command. The second change is in the Form_Load event where we instantiate the private member variable, and the final change involves handling the clicking of the toolbar.
GETTING STARTED WITH THE MAP CONTROL USING VISUAL BASIC 25
1. Firstly, add a private member variable to your project by adding the following code to the Forms code window General section.
Private m_pCommand As ICommand
2. Immediately after the call to InitializeMap, insert the following lines to create an Identify tool and pass it a reference to the Map control.
Set m_pCommand = New AfCommandsVB.Identify ' Pass the Map control as the hook m_pCommand.OnCreate MapControl1.Object
3. Modify the Toolbar1_ButtonClick procedure to associate the Map control with the Identify command using the CurrentTool property.
Private Sub Toolbar1_ButtonClick(ByVal Button As MSComCtlLib.Button) Set MapControl1.CurrentTool = Nothing With MapControl1 Select Case Button.Key Case "Zoom" .MousePointer = esriPointerZoomIn Case "Pan" .MousePointer = esriPointerPan Case "FullExtent" .MousePointer = esriPointerDefault .Extent = MapControl1.FullExtent Case "SelectByPolygon" .MousePointer = esriPointerCrosshair Case "TrackEvent" .MousePointer = esriPointerHotLink Case "Identify" .MousePointer = esriPointerDefault Set MapControl1.CurrentTool = m_pCommand End Select End Sub
For the Map control to be able to set the CurrentTool, the target tool must support the ITool interface, which the supplied Identify tool does. Internally, once the Map control has been associated with the CurrentTool, it forwards all MouseDown events directly to the CurrentTool first and fires the OnMouseDown event as before. If another operation has been selected from the Toolbar, for example, the Pan, we need to reset the CurrentTool to Nothing to indicate that no tool should be used. We do this at the beginning of the procedure. Test your changes
1. Click the Run button in the Visual Basic toolbar. 2. Select the Identify tool from the Toolbar. Notice that the MousePointer has changed. Click on an individual feature or drag a rectangle and an attribute dialog box will pop up. 3. To stop running your application and return to design mode, click the Stop button in the Visual Basic toolbar.
26
Adding a Query tool The AF Commands library also comes with a very useful Query tool. This tool enables you to query a specified layer using a spatial and/or attribute query. The results can be Added, Kept, or Discarded to or from the Maps SelectionSet. To correctly use the Query tool (and all other tools that only implement the ICommand interface), we need to create our tool and load it into a global variable. If we create the command using the OnCreate method and then fire its OnClick method entirely within one procedure, it will quickly go out of scope, and an error will be raised. Storing the command in a global variable solves the problem. Alternatively, you can use a Collection to manage your tools instead of a global variable.
1. Firstly, add a private member variable to your project by adding the following code to the Forms code window General section:
Private m_pQuery as ICommand
pFeatSeln To =
layers
Work QI
only for
with the
(TypeOf
pLayer =
IFeatureLayer)
Then
pFeatSeln If
pFeatSeln.SelectionColor
2. Next, modify the Form_Load procedure and add the following lines to create a new Query command and pass it a reference to the Map control.
' Use the AfCommandsVB Query tool Set m_pQuery = New AfCommandsVB.Query m_pQuery.OnCreate MapControl1.Object
Only feature layers have a SelectionColor. To check what type of layer we have, we use the TypeOf keyword. After we have worked out if the current map layer is an IFeatureLayer, we QI directly to the IFeatureSelection interface and set its SelectionColor property.
27
Congratulations
You have built a simple application using the Map control. Although these exercises demonstrated many of the capabilities of the Map control, there is still much more to discover in ArcObjects. To learn more, read the book Exploring ArcObjects, consult the ArcObjects Developers online reference, or use the ArcObjects Component Help online for the most up-to-date information.
3. Now try the Spatial Constraint. First, zoom into the Map so that the counties are drawn. In the Query dialog, click on the counties layer in the Class tab, then click on the Spatial Constraint tab. For the Spatial Extent, click on the icon for digitizing an area and then click on the map to draw a polygon. Select the Intersects Spatial Operator and finally click on the Apply button. 4. To stop running your application and return to design mode, click the Stop button in the Visual Basic toolbar.
28