Section 2.3. Programming the MapPoint ActiveX Control


2.3. Programming the MapPoint ActiveX Control

The programming models of the MapPoint 2004 APIs and MapPoint 2004 ActiveX Control are exactly the same, except that you use the AxMappointControl class instead of creating an ApplicationClass object to access the active map instance.

2.3.1. Adding MapPoint 2004 ActiveX Control

The first step towards developing with MapPoint 2004 ActiveX control starts with configuring your development environment. You need to add the ActiveX Control to your Visual Studio .NET toolbox to enable the "Drag-and-Drop" development tool. Create a new tab by selecting the Add Tab option from the toolbox context menu as shown in Figure 2-11.

Figure 2-11. Add Tab context menu


Name the newly created tab MapPoint ActiveX Control and click on it to add the MapPoint 2004 ActiveX Control reference by selecting Add/Remove Items from the context menu, as shown in Figure 2-12.

Figure 2-12. Add/Remove Items context menu


When the Customize Toolbox dialog is displayed, select the COM Components tab and Microsoft MapPoint Control 11.0 as shown in Figure 2-13.

Note that if you have MapPoint 2004 APIs already added to your project, you need to remove that reference before you add ActiveX Control; adding ActiveX Control automatically adds the MapPoint 2004 API reference to your project.

That's it! Now you are ready to develop applications using the MapPoint 2004 object model.

2.3.2. Initializing the MapPoint 2004 ActiveX Control

When you drag-and-drop the MapPoint control onto your Windows form, the reference to the MapPoint interoperable assembly is automatically added to your project, along with the control. The drag-and-drop operation also creates and adds an instance of MapPoint control to your code file:

     private AxMapPoint.AxMappointControl axMappointControl1;

Figure 2-13. The Customize Toolbox dialog


Before you use AxMappointControl, you need to initialize the control by creating new map coverage by calling the NewMap method on the AxMappointControl class. This method takes the map region of type GeoMapRegion enumeration as an argument. There are two valid region values for the map region in MapPoint 2004: GeoMapRegion.geoMapNorthAmerica for North American maps and GeoMapRegion.geoMapEurope for European maps. The following code shows how to initialize the control to show the North American map:

     axMappointControl1.NewMap(MapPoint.GeoMapRegion.geoMapNorthAmerica);

If you are programming with MapPoint 2004 European Edition, you have to initialize the control with GeoMapRegion.geoMapEurope.


You can also open an existing map file using the OpenMap method to initialize the control. The OpenMap method takes an existing map file path as an argument:

     axMappointControl1.OpenMap("C:\MyMap.ptm");

After initializing the map control, you can access the map object via the ActiveMap property:

     MapPoint.Map map = axMappointControl1.ActiveMap;

Using this map object, you can perform all the location-based operations, such as finding places, addresses, and nearby places, as we did earlier in this chapter.

2.3.3. Controlling Toolbars and Panes

The MapPoint 2004 ActiveX map control provides the same set of toolbars as the MapPoint 2004 application. These toolbars are not visible by default, but you can make them appear or disappear programmatically using the MapPoint 2004 ActiveX control's Toolbars property, which is a collection of four toolbars:


Standard toolbar

Contains common operations, such as opening a new map and printing a map along with main MapPoint features, such as finding nearby places, routing, etc.


Navigation toolbar

Contains a find textbox to find input places and other menu items, such as zoom in, zoom out, and map style.


Drawing toolbar

Contains standard drawing tools to draw shapes, such as lines, rectangles, and circles.


Location and Scale toolbar

Shows the current maps's location and scale.

These toolbars are shown in Figure 2-14.

To access a particular toolbar, use either the index or the name of the toolbar; for example, the following code shows how to show make the Location and Scale toolbar visible using the index:

      //Define toolbar indexes     object TOOLBAR_STANDARD = 1;     object TOOLBAR_NAVIGATION = 2;     object TOOLBAR_DRAWING = 3;     object TOOLBAR_LOCATIONSCALE = 4;     //using index     axMappointControl1.Toolbars.get_Item(ref TOOLBAR_DRAWING).Visible                                                          = true;     axMappointControl1.Toolbars.get_Item(ref TOOLBAR_LOCATIONSCALE).Visible                                                          = true;     axMappointControl1.Toolbars.get_Item(ref TOOLBAR_NAVIGATION).Visible                                                          = true;     axMappointControl1.Toolbars.get_Item(ref TOOLBAR_STANDARD).Visible                                                          = true;

You get the same effect using the following code, which uses the toolbar's name:

     object name = "Location and Scale";     axMappointControl1.Toolbars.get_Item(ref name).Visible = true;

The Standard toolbar allows users to toggle different panes, such as route pane, find nearby pane, and so forth. However, if you want to control these panes in your application, don't make the entire Standard Toolbar visible in your applicationyou can control the pane visibility programmatically using the PaneState property of the ActiveX control. The PaneState property is of MapPoint.GeoPaneState type, which is an enumeration. The GeoPaneState enumeration has five values that show no panes, the Legend pane, the Find Nearby Places pane, the Route Planner pane, and the Territory Manager pane, as shown in Table 2-3.

Figure 2-14. MapPoint 2004 MapControl toolbars


Table 2-3. GeoPaneState enumeration values

GeoPaneState value

Description

geoPaneLegend

Legend pane is displayed.

geoPaneNearbyPlaces

Find Nearby Places pane is displayed.

geoPaneNone

No panes are displayed with the map.

geoPaneRoutePlanner

Route Planner pane is displayed.

geoPaneTerritory

Territory Manager pane is displayed.


For example, to let users find nearby places in your application, you can give them access to that functionality:

     //Make the route planning pane visible     axMappointControl1.PaneState = MapPoint.GeoPaneState.geoPaneRoutePlanner;

Finally, if you want to control the Route Planner pane that displays the detailed driving directions visibility, use the ItineraryVisible property of the ActiveX Control:

     //Hide itinerary pane     axMappointControl1.ItineraryVisible = false;

This property is also available from the ApplicationClass instance.

Now that we have a map control ready to use, let's start off with some basic actions, such as displaying a location on a map and zooming in and out of maps.

2.3.4. Displaying a Location on a Map

In our sample earlier this chapter, we have implemented the find methods to find places, addresses, and nearby locations. In all these cases, a MapPoint.Location instance represents the locations found. To display a location on the map, call the Location object's GoTo method:

     //Define a location instance     MapPoint.Location currentLocation = null;     //Get the current location from FindResults method     MapPoint.FindResults findResults =                      map.FindResults("your place input");     currentLocation = findResults.get_Item(ref index);     //Go to the current location on the map     currentLocation.GoTo( );

Calling this method zooms in to the location with the best possible view on the map and centers the map on that location. To highlight the location on a map, use the Location.Select method:

     //Highlight the location on the map     currentLocation.Select( );

After this implementation, our application looks similar to Figure 2-15.

If there is only one location, you can center the map on it using the Location.GoTo method, but you have to use the Map.Union method to center the map to display multiple locations on it. This method takes an array of locations and returns the center of the map as a Location object for all given locations:

     //Define an ArrayList to hold location objects     ArrayList locList = new ArrayList( );     //Add locations to the array list     for(int i=0;i<findResult.Count;i++)     {

Figure 2-15. Location display and highlight


        Object index = i+1;        MapPoint.Location location =                 findResult.get_Item(ref index)                 as MapPoint.Location;       locList.Add(location)     }     //Center the map to show all locations     MapPoint.Location center = axMappointControl1.ActiveMap.Union(locList.ToArray( ));     //Now zoom map to the center     center.GoTo( );

How do you pinpoint the selected location? Is it possible to annotate that location, or better, to highlight it? Pushpins make this process easy.

2.3.5. Working with Pushpins

Pushpins are visual marks on a map that contain either an annotation or data. Each pushpin on a map is associated with a location. A pushpin in MapPoint 2004 is represented by the Pushpin class. The Name property of a Pushpin object can be used to annotate the pushpin. You can also add notes to the pushpin using the Pushpin.Notes property.

A pushpin is represented pictorially by a symbol. MapPoint 2004 provides a number of symbols to be used with pushpins. These symbols are indexed, and their number should be used to indicate the symbol of a given pushpin; for example, the default symbol is the black pushpin, represented by 0. The valid range for the standard symbols is 0-255. You can also add customized pushpins, but the identity must be in the range of 256-32,766.

For a full list of available symbols, see the online documentation at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/mappoint2004/BIZOMPSymbol.asp.


The location represented by a pushpin can be accessed via the Pushpin.Location property. Let's look at some code to implement this; to add a pushpin to a predetermined location, call Map.AddPushpin method:

     //Get map center location     MapPoint.Location location = axMappointControl1.ActiveMap.Location;     //Add a pushpin at this location     MapPoint.Pushpin pushpin = axMappointControl1.ActiveMap.AddPushpin(                                                          location, "Center");     //Assign a symbol     pushpin.Symbol = 64;     //Select and highlight the location     pushpin.Select( );     pushpin.Highlight = true;     //Write annotation     pushpin.Note = "This is my favorite place!";

This code adds a pushpin to the center of the map. However, the pushpin on the map does not display any information. To display the information associated with the pushpin, such as name, notes, etc., use the Pushpin.BalloonState property. Setting this property displays the pushpin tool tip information. The Pushpin.BalloonState property is of MapPoint.GeoBalloonState type, which is an enumeration. The valid values for this property are:


GeoBalloonState.geoDisplayNone

Does not display any information.


GeoBalloonState.geoDisplayName

Displays only the name of the pushpin.


GeoBalloonState.geoDisplayBalloon

Displays all information including name, notes, etc.

The following code shows how to display the full details of a given pushpin:

     //Show tooltip (Balloon State)     pushpin.BalloonState = MapPoint.GeoBalloonState.geoDisplayBalloon;

You can remove a given pushpin by calling the Pushpin.Delete method. The Pushpin class exposes some other methods, such as Copy and Cut, to copy the pushpin to the clipboard.

Now that we know how to display a location on map, select a location, and add a pushpin to it, let's look at how to interact with the MapPoint 2004 ActiveX Control maps.

2.3.6. Interacting with Maps

The MapPoint 2004 ActiveX Control provides you with a fully interactive map on which to perform actions such as panning , zooming, and tracking mouse clicks. All of this functionality is accessible to both the programmer and the user.

2.3.6.1. Panning maps

To pan a map, use the Map.Pan method. This method takes two arguments:


PanDirection

Indicates the direction of the pan operation; this property is of MapPoint.GeoPanCmd type, which is an enumeration. This enumeration contains values that represent directional values such as east, west, north, south, and northeast.


PanFactor

Indicates the amount of pan. Even though there are no limits to the pan factor, keep in mind that this value is dependent on the altitude of your map. To give you an idea of what this means, at 1 mile (lower altitudes), a pan factor of 1 pans the map by 0.2 miles, but the same pan factor at 50 miles (a higher altitude) pans the map by 10 miles.

The following code shows how to call the Pan method:

     axMappointControl1.ActiveMap.Pan(MapPoint.GeoPanCmd.geoWest, 1);

Given this information, you could write a smart Pan method that pans by a certain distance at all altitudes. You would need the altitude to pan the distance ratio to calculate the correct pan value at a given altitude and distance. This ratio is approximately 4.88568304395 for altitudes up to 6,000 miles, above which the factor becomes non-linear. If you want your application to pan the map only by 1 mile irrespective of map's current altitude, you can calculate the pan factor as follows:

     //Specify desired pan distance     //For example, set to 1 mile in this case     double desiredDist = 1;     //Standard Altitude/Distance ratio     const double ALT2DISTRATIO = 4.88568304395;     //Calcuate the pan factor     double panFactor = desiredDist * ALT2DISTRATIO /                                      axMappointControl1.ActiveMap.Altitude;     //Now pan the map to west     axMappointControl1.ActiveMap.Pan(MapPoint.GeoPanCmd.geoWest, panFactor);

This code always pans the map the specified distance. This is very useful if you want to pan your map by a certain distance to show specific locations on the map. Finally, keep in mind that when panning at very low altitudes (say, one or two miles) where street level data is not possible, the MapPoint 2004 ActiveX Control shows a dialog asking to zoom out to higher altitudes before panning.

2.3.6.2. Zooming Maps

MapPoint 2004 ActiveX Control provides two methods to perform zoom operations on maps:


ZoomIn

Zooms the map view closer by reducing the map altitude.


ZoomOut

Zooms the map view farther by increasing the map altitude.

These two methods zoom in or out in steps. There are many levels of zoom effect that you can achieve using them. The levels are defined based on the map altitude. Each time you call zoom methods, the map's altitude is modified accordingly and rerendered to show the map at that altitude. The following code shows how to call a ZoomIn method:

     axMappointControl1.ActiveMap.ZoomIn( );

What if you want to zoom in to a particular level from your current view? For example, if you want to zoom to street level directly without calling the ZoomIn method multiple times, you can do that by modifying the map altitude yourself:

     //Zoom directly into Street Level by setting 3 mile altitude     axMappointControl1.ActiveMap.Altitude = 3;

When the MapPoint 2004 ActiveX control loads a new map, by default it will be set at a 5,592-mile altitude. Streets start showing up at a 10-mile altitude. For detailed street maps, a 3-mile altitude is ideal.


2.3.6.3. Tracking mouse clicks

Along with all of its MapPoint-related functionality, the MapPoint 2004 ActiveX Control also provides events and methods to capture your interaction with maps using a mouse. Mouse interaction, in the context of maps, usually includes selecting a point on a map, selecting a pushpin location on a map, and so forth. If you want to process a user's interaction with maps in MapPoint 2004 ActiveX Control, you need to know when and where a mouse is clicked to obtain the location corresponding to a mouse click. Let's look at some of these methods in detail.

2.3.6.4. Point to location

This map object exposes the XYToLocation method to obtain a location at a given point on the map view on the screen. This method returns the location corresponding to the selected x and y coordinates. In order to use this method, you need to trap the mouse click and capture the x and y coordinates, which can be done using the Map object's BeforeClick event. This event occurs when a user clicks on the map before MapPoint 2004 ActiveX Control actually processes the mouse click. You would have to wire up this event in the InitializeComponent method of your application:

     axMappointControl1.BeforeClick +=                 new AxMapPoint._IMappointCtrlEvents_BeforeClickEventHandler(                                              axMappointControl1_BeforeClick);

Once you have wired up the event, the axMapPointControl1_BeforeClick method should be implemented so that you capture the mouse click coordinates:

     private void axMappointControl1_BeforeClick(object sender,                                AxMapPoint._IMappointCtrlEvents_BeforeClickEvent e)     {         int XCoord = e.x;         int YCoord = e.y;         MapPoint.Location location =                    axMappointControl1.ActiveMap.XYToLocation(XCoord, YCoord);         if(location != null)         {             //Do some processing with location             . . .         }     }

This event captures only single clicks from the mouse. To capture double-clicks from your mouse, you have to wire up the BeforeDblClick event, which occurs when a user double-clicks on the map but before the MapPoint 2004 ActiveX Control actually processes the double click.

2.3.6.5. Location to point

The Map object also provides a way to convert a location on the map to a point on the screen. Using Map object's LocationToX and LocationToY methods, you can obtain x and y coordinates for any given location by making separate calls for each coordinate:

     //Get the center of the map     MapPoint.Location location = axMappointControl1.ActiveMap.Location;     //Get x and y coordinates     int x = axMappointControl1.ActiveMap.LocationToX(location);     int y = axMappointControl1.ActiveMap.LocationToY(location);     //Display the center coordinates     MessageBox.Show(String.Format("Map is centered at ({0}, {1})",                                            x.ToString( ), y.ToString( )));

The LocationToX and LocationToY methods assume that a particular location is on the current map screen limits; if the location is not present in the ActiveX Control map screen limits, these methods fail by returning invalid values (such as a maximum value of int32). To avoid errors in a case like this, it's always a good idea to use the Location.GoTo( ) method before getting the coordinates.

2.3.6.6. Processing location selections

Sometimes you have to follow the locations or pushpins that users are selecting on a given map; for example, you have displayed 10 pushpins on a map, and when a user selects a pushpin, you want to show the information by using the BalloonState property. In this case, you need the Map object's SelectionChange event. Wiring up this event is no different from any other event that we have seen previously; you have to add the following code in the initialization method:

     this.axMappointControl1.SelectionChange +=                new AxMapPoint._IMappointCtrlEvents_SelectionChangeEventHandler(                                              axMappointControl1_SelectionChange);

The SelectionChangeEvent exposes two objects: one for a current or new selection and one for an old or previous selection. So, in the event handler method, you have to capture these two objects to do the processing, as follows:

     private void axMappointControl1_SelectionChange(object sender,                          AxMapPoint._IMappointCtrlEvents_SelectionChangeEvent e)     {         //Get the previous selection         MapPoint.Pushpin pPrev = e.pOldSelection as MapPoint.Pushpin;         //Get the current selection         MapPoint.Pushpin pCurr = e.pNewSelection as MapPoint.Pushpin;         if(pPrev != null)         {             //Turn off the tool tip             pPrev.BalloonState = MapPoint.GeoBalloonState.geoDisplayNone;             //Turn off the highlight             pPrev.Highlight = false;         }         if(pCurr != null)         {             //Display the information             pCurr.BalloonState = MapPoint.GeoBalloonState.geoDisplayBalloon;             //Highlight the pushpin             pCurr.Highlight = true;         }     }

Since the SelectionChangeEvent captures both previous and new selections as objects, it is possible that these selections are locations if you select a location instead of a pushpin. This event is also applicable for other objects such as shapes, directions, and waypoints. In that case, you need to typecast the object as a Location:

     //Get the previous selection     MapPoint.Location lPrev = e.pOldSelection as MapPoint.Location;     //Get the current selection     MapPoint.Location lCurr = e.pNewSelection as MapPoint. Location;

2.3.6.7. Disabling map interaction

Now, let's look at how to disable the map for user interaction; this may sound strange, after all the user interaction-related discussions. In some application scenarios, you have to make the map read-only so that users cannot change the information on the map. There is no straightforward way to do this other than disabling all events by overriding them.

You must take the following steps:

  1. Turn-off the edge panning by setting AllowEdgePan to false:

         axMappointControl1.ActiveMap.AllowEdgePan = false;

  2. Capture any mouse down event and display a message saying that this is a read-only map.

         //Wire up the mouse down event     private void axMappointControl1_MouseDownEvent(object sender,                         AxMapPoint._IMappointCtrlEvents_MouseDownEvent e)     . . .     //Implement the event handler method by displaying a message     private void axMappointControl1_MouseDownEvent(object sender,                         AxMapPoint._IMappointCtrlEvents_MouseDownEvent e)     {         return;     }

  3. Support pan and zoom via mouse wheel and arrow keys by overriding the AfterViewChange event by restoring the original center of the map and altitude.

         //Obtain the original center location     originalCenterLocation = axMappointControl1.ActiveMap.Location;     //Obtain the original altitude     originalAltitude = axMappointControl1.ActiveMap.Altitude;     . . .     //Wire up the AfterViewChange event      this.axMappointControl1.AfterViewChange +=            new System.EventHandler(this.axMappointControl1_AfterViewChange);     . . .     //Implement AfterViewChange event handler method     private void axMappointControl1_AfterViewChange(object sender, EventArgs e)     {              if(originalCenterLocation != null)           {              //Re-assign the center point              axMappointControl1.ActiveMap.Location = originalCenterLocation;             }           //Re-assign the altitude           axMappointControl1.ActiveMap.Altitude = originalAltitude;     }

As you can see, the AfterViewChange event handler restores both map center and altitude; this method takes care of both pan clicks and zoom (via the mouse wheel scroll), but keep in mind that performance may be affected by the mouse wheel scroll events. Finally, if you want to disable mouse clicks, set the cancel property of the BeforeClick and BeforeDblClick events to true.

2.3.7. Saving a Map

There are several ways to save a map from your application. You can save the map as a standard .ptm map that can only be opened using MapPoint 2004 application, or you can save it as a web page (.htm) map that can be opened by any browser.

Saving the map as a .ptm is very straightforward; you can use the SaveMapAs method on the MapPoint 2004 ActiveX Control:

     axMappointControl1.SaveMapAs(@"C:\test.ptm");

To save the map as a web page, use the SavedWebPages property of the Map object. This property is a collection of web pages, and you call the Add method as follows to save a new map as a web page:

     string path = @"C:\test.htm";                 axMappointControl1.ActiveMap.SavedWebPages.Add(                        path, axMappointControl1.ActiveMap.Location, "My Map",                        true, true, true, axMappointControl1.ActiveMap.Width,                        axMappointControl1.ActiveMap.Height, true, true, true, true);

Using the SavedWebPages collection also enables you to manage the saved pages from the MapPoint 2004 application UI using the File Manage Saved Web Pages menu option.




Programming MapPoint in  .NET
Programming MapPoint in .NET
ISBN: 0596009062
EAN: 2147483647
Year: 2005
Pages: 136
Authors: Chandu Thota

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net