Buy this Book
Print Book $49.95 Read it Now!
Print Book £35.50
Add to UK Cart
Reprint Licensing

Programming MapPoint in .NET
Programming MapPoint in .NET

By Chandu Thota
Price: $49.95 USD
£35.50 GBP

Cover | Table of Contents


Table of Contents

Chapter 1: Hello, MapPoint!
So, you want to develop location-based applications using .NET! Microsoft MapPoint technologies offer a wide variety of applications, services, and tools to enable you to develop powerful location-based applications using .NET technologies.
In this introductory chapter, I will go through different location-based application categories and architectures and explain which MapPoint product or technology is appropriate to use in certain scenarios; specifically, I will discuss the fundamental differences between the following three products and technologies from MapPoint:
  • MapPoint 2004
  • MapPoint Web Service
  • MapPoint Location Server
Fundamentally, location-based applications are applications that either know how to process location-based information or make use of their location for other processing. To that end, location-based applications can be categorized into two major categories: location-enabled applications and location-aware (or real-time) applications.
Location-enabled applications understand location and know how to process it. For example, a conventional store locator is a location-enabled application—simply specify a location and provide a distance within which you want to find stores. Another example is a simple maps-and-directions application that can calculate driving directions using starting and ending addresses and display them on a map. These applications know how to interpret and process the location information.
Location-aware applications are similar to location-enabled applications except that they are aware of their own location, so they can use it for processing information. For example, a simple maps-and-directions application connected to a GPS device can provide you with up-to-date driving directions based on your current location, or it can even recalculate the driving directions if you leave your planned route! Another example is a store-locator application that knows where you are and automatically recommends nearby stores based on your current location. Location-aware applications are usually known as
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Location-Based Application Categories
Fundamentally, location-based applications are applications that either know how to process location-based information or make use of their location for other processing. To that end, location-based applications can be categorized into two major categories: location-enabled applications and location-aware (or real-time) applications.
Location-enabled applications understand location and know how to process it. For example, a conventional store locator is a location-enabled application—simply specify a location and provide a distance within which you want to find stores. Another example is a simple maps-and-directions application that can calculate driving directions using starting and ending addresses and display them on a map. These applications know how to interpret and process the location information.
Location-aware applications are similar to location-enabled applications except that they are aware of their own location, so they can use it for processing information. For example, a simple maps-and-directions application connected to a GPS device can provide you with up-to-date driving directions based on your current location, or it can even recalculate the driving directions if you leave your planned route! Another example is a store-locator application that knows where you are and automatically recommends nearby stores based on your current location. Location-aware applications are usually known as real-time location applications .
The intelligence of location awareness comes from the real-time location information obtained either by using an external hardware device, such as GPS, or by other means, such as mobile phone operator networks.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Location Application Architectures
Beyond the application categories, you need to be aware of application architectures when building location-based applications. Location-based applications can be built using two different architectures:
  • Disconnected location-based applications
  • Connected location-based applications
Let's look at each of these categories in detail.
Disconnected location-based applications contain location information and related processing framework locally on the hosted computer hard disk, which means that network connectivity is not required for the application's functionality. A typical disconnected location-based application architecture is shown in Figure 1-1.
The main advantage of this architecture is that the location data resides locally, so the applications can provide a faster and richer user experience; however, having data locally may also be viewed as a limitation for other reasons, such as the size of the application (since location data can easily grow to a few Gigabytes) and the data becoming out-of-date due to lack of frequent updates. The advantages include:
  • Continuous availability of the application and data with no dependency on network connectivity
  • Rich user interface
  • Ideal architechture for thick client scenarios, where computing power and memory are available to handle complex processing on the client device
Figure 1-1: Disconnected location-based application architecture
However, there are also disadvantages:
  • Larger application footprint
  • Local location data that becomes out-of-date over time
  • Different applications for different platforms (Windows versus Mobile)
  • Not ideal architecture for thin client (such as web) scenarios
The decision to develop a disconnected location-based application should be based entirely on factors such as connectivity and functional richness of the application, which we will discuss in more detail later in this chapter.
Connected location-based applications contain location information and related processing framework on remotely located servers instead of the local hard disk, which means that a network connection is essential for the application to run. Typical connected-location based application architecture is shown in Figure 1-2.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Developing Location-Enabled Applications
Location-enabled applications know how to interpret and process location information. The kinds of applications that fall into this category include:
Generic maps and directions
Provide basic planning-related functionalities, such as displaying a desired location on a map and calculating driving directions from one point to another point. For example, both MapPoint 2004 and Streets & Trips 2004 provide this functionality right out of the box.
Location-based data visualization (or thematic mapping )
Helps you to visualize the data using geographic extent. For example, using MapPoint 2004, you can view information such as population statistics in any given city in the United States, or color-code the map based on population density.
Store Finders, ATM Finders, and similar applications
Find points of interest around a desired location. For example, you can find a nearby coffee shop when you are traveling in a new town or find local bloggers in the area in which you live.
To build this category of applications using MapPoint technologies, you have two choices: disconnected applications using MapPoint 2004, and connected applications using MapPoint Web Service.
MapPoint 2004 is a powerful desktop mapping application that provides a rich set of APIs for both managed and unmanaged application development. MapPoint 2004 is well-suited for disconnected location-enabled application architecture, which means that the location-enabled application and required location data reside locally on the host computer's hard disk, and no network connectivity is required for the application's functionality.
Along with normal location-based APIs, such as Find, Route, and Render, MapPoint 2004 also offers a rich set of functions (also APIs) for thematic mapping, territory management, and spatial data import from a variety of source formats such as Excel, Access, Txt, and so on.
The APIs provided by MapPoint 2004 are COM- (Component Object Model) based APIs; however, thanks to .NET Framework runtime callable wrappers , you can program with the COM APIs using .NET's managed code. MapPoint 2004 also provides an ActiveX control that enables MapPoint 2004 application integration into your applications so that you can reuse most of the MapPoint 2004's application user interface.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Developing Location-Aware Applications
Location-aware applications (or real-time location applications ) apply your current location when processing information to provide smart choices. The kinds of applications that fall into this category are:
  • Real-time navigation software
  • Fleet tracking applications
  • Friend and family finder applications
To build this category of applications using MapPoint technologies, you have two choices (yes, again!): disconnected and connected applications .
MapPoint 2004 provides necessary APIs and location data to build location-enabled applications; however, you can also build disconnected location-aware applications using MapPoint 2004 by interfacing a location-aware hardware such as Global Positioning Satellite (or simply GPS) devices. Even though MapPoint 2004 does not provide ready-to-use APIs for GPS interfacing, it is relatively easy to use real-time information from a GPS device in the MapPoint application environment.
Figure 1-7 shows how your location-aware applications build on MapPoint 2004 and a GPS device.
This architectural layer is not very different from Figure 1-3, except that this application uses a GPS device for real-time information.
For further details on how to interface MapPoint 2004 with a GPS device, see Chapter 4.
The most common scenarios for this architecture include real-time navigation applications, real-time location based information logging applications.
Figure 1-7: Location-aware application using MapPoint 2004 with a GPS device
MapPoint Location Server is an enterprise-hosted server that enables real-time location scenarios using a locatable device, such as a mobile phone or a pager. MapPoint Location Server does not require any location-related hardware, such as GPS devices; instead, it locates a provisioned (registered) user's mobile device by communicating with a mobile operator. In a typical scenario, a user requests his position using a mobile device equipped with a client that communicates with MapPoint Location Server. When MapPoint Location Server receives the request from the client, it identifies the mobile operator for the user and sends a location request to the mobile operator, which responds by sending back the real-time location of the user, expressed as latitude and longitude coordinates. MapPoint Location Server then requests a map or other location information from MapPoint Web Service to process the user's real-time location.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
How It All Fits Together
By now, you might be confused about which product to use for each type of application. To clarify your choices, Figure 1-9 summarizes your options.
Figure 1-9: MapPoint Platform development choices
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Where Are We?
Microsoft MapPoint technologies provide a wide variety of applications, services, and tools to develop location-enabled applications and location-aware applications for both connected and disconnected scenarios. To recap:
  • To develop disconnected location-enabled applications , use MapPoint 2004.
  • To develop connected location-enabled applications, use MapPoint Web Service.
  • To develop disconnected location-aware applications , use MapPoint 2004 with GPS.
  • To develop connected location-aware applications , use MapPoint Location Server .
If you are wondering how to digest so much information about all these products in one introductory chapter, don't worry; I will discuss MapPoint 2004, MapPoint Web Service, and MapPoint Location Server in detail in the upcoming chapters.
Let's get started!
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Programming with MapPoint 2004
MapPoint 2004 provides a rich set of APIs and an ActiveX Control that lets you build powerful location-based business applications. Originally, the MapPoint APIs and ActiveX Control were designed for use with COM technologies, but thanks to .NET interoperability with COM, you can use those COM APIs to build applications using .NET programming languages such as C# and VB.NET.
Keep in mind that it is sometimes tricky to make the COM interfaces work with your .NET code, but I will discuss the tips, tricks, and workarounds in detail.
This chapter explores using the MapPoint 2004 APIs and MapPoint 2004 ActiveX Control to accomplish basic location-oriented tasks, such as finding places, addresses, and points of interest, routing between places, and other lightweight business-oriented tasks, such as optimizing a route. To follow the examples in this chapter, you'll need Microsoft MapPoint 2004 North America/Europe Edition installed on the development computer, and the Microsoft .NET Framework, Version 1.1 or later.
The MapPoint 2004 APIs and MapPoint 2004 ActiveX Control are designed for building disconnected Windows applications. Since all map data is installed locally on your hard drive, you can build Windows applications that don't need any network connectivity. However, if you need to build a connected web-based mapping application to keep your application footprint to a minimum size, consider instead the MapPoint Web Service, which is discussed later in this book in detail. Building a web-based application using the MapPoint 2004 APIs (or ActiveX Control) not only results in a poorly-performing web application but also violates the MapPoint license model! So, MapPoint 2004 can be used only for building Windows applications.
For a more detailed discussion on which platform to choose for your application development, refer to Chapter 1.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The MapPoint 2004 Object Model
The MapPoint 2004 APIs and MapPoint 2004 ActiveX Control are designed for building disconnected Windows applications. Since all map data is installed locally on your hard drive, you can build Windows applications that don't need any network connectivity. However, if you need to build a connected web-based mapping application to keep your application footprint to a minimum size, consider instead the MapPoint Web Service, which is discussed later in this book in detail. Building a web-based application using the MapPoint 2004 APIs (or ActiveX Control) not only results in a poorly-performing web application but also violates the MapPoint license model! So, MapPoint 2004 can be used only for building Windows applications.
For a more detailed discussion on which platform to choose for your application development, refer to Chapter 1.
You can develop three kinds of applications using MapPoint 2004:
Location data-processing applications
Use MapPoint 2004 automation internally but don't create maps.
Location visual applications (with map display)
Display location and thematic maps embedded into applications using MapPoint2004.
MapPoint 2004 Add-Ins
Extend the capabilities of MapPoint 2004.
Location data-processing applications are typically used in the business intelligence part of an enterprise application. For example, a goods-delivery company must optimize the stops in a delivery route to save on fuel costs and drivers' time. These applications are developed using the MapPoint 2004 APIs .
The visual application category applies when you want to display a map to represent business data thematically. For example, a map displaying sales across the country based on zip code gives an immediate understanding of whether location plays a crucial role in sales. For applications that embed maps, it is ideal to use the MapPoint 2004 ActiveX Control; however, you can also use MapPoint APIs to display maps without using the ActiveX Control, as discussed in Chapter 3.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Programming with MapPoint 2004 API
The MapPoint 2004 APIs were originally designed for use with the COM programming model. In order to build applications using the Microsoft .NET Framework, you need the interoperable assemblies for the MapPoint COM library. Let's look at how to add the MapPoint 2004 APIs as references for use in your project.
If you are using Visual Studio .NET Version 2003 or later, it is easy to add a reference to the MapPoint 2004 APIs using the Add Reference option from the project context menu, as shown in Figure 2-2.
Figure 2-2: Project Add Reference menu
If you are using MapPoint ActiveX Control, you don't need to add this reference manually, since Visual Studio .NET adds it automatically when you drag-and-drop the control on your Windows Form.
When you see the Add Reference dialog window, select the COM tab and select the Microsoft MapPoint 11.0 Object Library (North America) to add the MapPoint 2004 type library as a reference to your project, as shown in Figure 2-3.
Figure 2-3: Adding the MapPoint 2004 library as a reference
If you are using the MapPoint 2004 European Edition, select the Microsoft MapPoint 11.0 Object Library (Europe) to add the reference. Also, note that if you have both MapPoint North America and MapPoint Europe installed on the same computer, you can develop an interop assembly for either product for use with both applications.
In this process, Visual Studio .NET automatically creates an interoperable assembly and adds it as a reference to your project. By default, the namespace of the newly created assembly is set to MapPoint.
If you do not have Visual Studio .NET, or if you chose to do the hard work of creating the interoperable assembly yourself, you can use the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
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.
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.
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
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Cleaning Up After You're Done
The MapPoint 2004 object model was originally designed and implemented using COM technologies, so even if you use the COM Interoperable assemblies to write your code, the MapPoint 2004 Application instance will not be collected by the .NET runtime garbage collector. Before quitting your application, you must manually quit the MapPoint 2004 Application by calling the Quit method on the MapPoint.Application object:
    //Define MapPoint Application instance
    MapPoint.Application app = null;
    //Obtain app references either via MapPoint.ApplicationClass or
    //MapPoint.AxMapPointControl.ActiveMap.Application
    . . .

    //Clean up the MapPoint Application before you exit
    if(app != null)
    {
        app.Quit( );
        app = null;
    }
The Quit method discards the current map and unloads all other items, such as add-ins, before exiting the application. However, calling this method asks the user whether she wants to save the map before discarding it. If you don't want users to have this choice, you can set the Saved property to True on the application's active Map object:
    app.ActiveMap.Saved = true;
Setting this value means that the user will not be prompted to make a decision whether to save or discard the current map.
If you fail to implement the cleanup, your application may have memory leaks.
So far, we have covered major APIs offered by MapPoint 2004 for finding places, addresses, and nearby interests, along with some basic map operations, such as placing pushpins, zooming, and panning. A discussion of MapPoint 2004 programming is not complete if we don't mention latitude and longitude , so before we move on to routing and driving directions, let's look at finding addresses for latitude and longitude in MapPoint 2004.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Dealing with Latitude and Longitude
You know how to find a location using a place name or an address, but do you know how to find a location using latitude and longitude? Using the Map class's GetLocation method, you can easily find a location that corresponds to a given latitude and longitude measurement. This is also called geocoding in cartography terminology. This method takes latitude and longitude as System.Double values and returns a Location instance that represents the input latitude and longitude. This method also takes the altitude as an argument, but it is mainly used at the time when the location is displayed on a map, so you can freely pass one mile for the time being. The following code shows how to find a location using latitude and longitude:
    //Get the reference to the active map instance
    MapPoint.Map map = app.ActiveMap;
    //Call the GetLocation method 
 
 to find location
    //using the latitude and longitude
    MapPoint.Location location =
            m.GetLocation(41.33896, -122.43433, 1);
At this point, don't bother to get the street address for the location returned by the GetLocation method because this method doesn't return the address all the time. Don't be disappointed, as there is still a way to find the nearest address using the current location. The idea is to basically do a hit-detection around the found location to see if there are any addresses available. Before we get into the details of how to find out a location's address, let's look at the hit-detection in MapPoint 2004 in detail.
What is hit-detection in MapPoint 2004, and how do you programmatically implement it? The Map object in MapPoint has the method, ObjectsFromPoint, which allows you to perform a hit-detection around any given point (x and y coordinates) on the screen. You can already get a point from any given location, so what does this method return? As the method name suggests, it returns an array of objects wrapped in a FindResults instance. The type of objects returned by this method depends on the current map altitude. For example, if you call this method at lower altitudes, it returns locations with street addresses; if you go to higher altitudes and call this method, it returns larger geographic areas, such as Zip Code, county, and time zone of the point. The following snippet shows how to call the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Routing in MapPoint 2004
MapPoint 2004 provides a simple but powerful API to calculate routes between locations. A route in MapPoint 2004 is represented as a MapPoint.Route object. You can access a Route object via the ActiveRoute property of a Map object (the Map object can be obtained either via the MapPoint.ApplicationClass object or MapPoint.axMapPointControl object using the ActiveMap property):
    MapPoint.Route route = axMappointControl1.ActiveMap.ActiveRoute;
After obtaining a valid route object, you can perform actions such as calculating, optimizing, and personalizing routes; let's see each one of these features in detail.
In MapPoint 2004 terms, a route is essentially a collection of locations connected in some way—via street, ferry, or highway. These locations in a route are known as waypoints and are represented using the MapPoint.Waypoint class. A valid route always contains two or more waypoints. Waypoints in a route are represented in the Route.Waypoints collection, so you use the Waypoints collection to add new waypoints:
    //Get ahold of route object
    MapPoint.Route route = axMappointControl1.ActiveMap.ActiveRoute;
    //Add the location to the ActiveRoute
    route.Waypoints.Add(loc, loc.Name);
You can access the waypoints using the same collection and the corresponding index value:
    //Obtain a waypoint from a given route
    object index = 1;
    MapPoint.Waypoint waypoint = route.Waypoints.get_Item(ref index);
You can use the MapPoint.Waypoint object in many ways to specify a new route or modify an existing route. To change the location represented by a Waypoint object, use the Waypoint.Anchor property. This property is of type object because it can be either a Location or a Pushpin. If you are assigning a new location to a waypoint, you can do it like this:
    //Obtain a waypoint from a given route
    object index = 1;
    MapPoint.Waypoint waypoint = route.Waypoints.get_Item(ref index);
    //Assign a new location
    waypoint.Anchor = newlocation;
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Where Are We?
In this chapter, we have discussed how to use MapPoint 2004 APIs to develop applications with basic functionalities, such as finding places, addresses, and latitude/longitude; displaying locations on a map; zooming into a location; and panning maps. When you develop your applications using MapPoint 2004 ActiveX Control, try to reuse the UI that comes with it—toolbars, panes, dialogs, etc. We have also discussed using the MapPoint 2004 routing API to optimize, calculate, and personalize routes. It is important to keep in mind that you are working with a set of COM objects with a managed wrapper around them, so be sure to call the Quit method on the MapPoint.Application object when you are done with your tasks.
While it seems to be a lot of information, these concepts are really the core of MapPoint 2004 programming, and we will be using them more in the next chapter when we discuss dealing with business data and MapPoint 2004 data APIs.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Working with Data in MapPoint 2004
MapPoint 2004 can process, analyze, and display business data based on location, and it can then create demographic maps, thematic maps, territories, time zone maps, and shapes on maps. MapPoint 2004 ships with extensive built-in demographic data and a set of APIs to import, analyze, and display your business data from variety of sources.
This chapter has three major sections that correspond to the common tasks of working with:
  • MapPoint demographic data
  • Your own data
  • Shapes on maps
I will assume that you are familiar with the basic MapPoint 2004 programming model (if not, refer to Chapter 2 of this book). The sample data and code used in this chapter is available in the book's companion material in the Chapter03 directory.
In MapPoint 2004, both business data and demographic data are represented using the DataSet class. An active Map object exposes the DataSets collection, which you use to access a valid DataSet object. How does a DataSets collection get its data wrapped as a DataSet object? The DataSets collection is different from traditional .NET collections—it not only exposes a collection of DataSet objects, but it also offers methods to import external data and to access MapPoint 2004 demographic data.
A DataSet object is similar to a data table with rows and columns and regular querying capabilities. However, a DataSet object allows you to query the records or data rows based on location information. Each query results in a Recordset object containing the records that satisfy the location-based query. The DataSet object can also be used to display data on maps. In essence, if you are using any data features (such as data maps, territories, etc.) in MapPoint 2004 APIs, the DataSet class is the root for all these tasks; Figure 3-1 shows the relationships between an active Map object, a DataSets collection, a DataSet object, and a Recordset object.
Figure 3-1: MapPoint 2004 data-related API object model
It is important to note that the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Understanding the MapPoint 2004 Data API
In MapPoint 2004, both business data and demographic data are represented using the DataSet class. An active Map object exposes the DataSets collection, which you use to access a valid DataSet object. How does a DataSets collection get its data wrapped as a DataSet object? The DataSets collection is different from traditional .NET collections—it not only exposes a collection of DataSet objects, but it also offers methods to import external data and to access MapPoint 2004 demographic data.
A DataSet object is similar to a data table with rows and columns and regular querying capabilities. However, a DataSet object allows you to query the records or data rows based on location information. Each query results in a Recordset object containing the records that satisfy the location-based query. The DataSet object can also be used to display data on maps. In essence, if you are using any data features (such as data maps, territories, etc.) in MapPoint 2004 APIs, the DataSet class is the root for all these tasks; Figure 3-1 shows the relationships between an active Map object, a DataSets collection, a DataSet object, and a Recordset object.
Figure 3-1: MapPoint 2004 data-related API object model
It is important to note that the DataSet and RecordSet objects shown in the MapPoint object model are different from the Dataset and RecordSet classes defined in the System.Data namespace in the .NET Framework.
Tables 3-1 and 3-2 show some of the key methods exposed on the DataSet and RecordSet objects.
Table 3-1: Key Methods in the DataSet object
Method Name
Description
DisplayDataMap
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Understanding Data Maps
Imagine this: if you had a table of data that contained population count and area in square miles per state, and a map of the United States with states color-coded with corresponding population densities, on which one would it be easier to spot the state with the highest population density? Visualizing statistical data on maps makes grasping the key statistics more intuitive, especially if they are based on location.
MapPoint 2004 supports data visualization on maps through its data APIs. You can display data maps using either native MapPoint demographic data or an external data source such as a text file, Excel spreadsheet, or even a SQL Server database. In MapPoint 2004, a data map is represented with a DataMap class. A DataMap object can only be created using a DataSet object by calling the DisplayDataMap method. The resulting map displays data on the current active map of the MapPoint ActiveX Control or the ApplicationClass object and returns a DataMap instance. The DataMap object exposes a set of read-only properties that define the data map's behavior. The only property for which you can set a value is the LegendTitle property, used in the legend pane.
Before we get into coding details of data maps, there are a couple of details that you need to know: what data map styles (also known as data map types) are, and how to use the DataSet.DisplayDataMap method.
MapPoint 2004 supports three broad categories of data map styles:
  • Location data map
  • Single item data map
  • Multiple items data map
Each category is appropriate for a different set of uses.

Section 3.2.1.1: Location data map

This data map style should be used when you want to display only locations and have no data associated with them. For example, if you want to display your company's retail store locations in the United States, use a location data map. In this data map style, there are two display options to represent locations on maps:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Working with MapPoint Demographic Data
MapPoint 2004 ships with a lot of demographic data (also known as statistical data) that includes 136 categories for the United States and Canada and 43 categories for other countries worldwide. This demographic data includes statistics, such as population by location, average age by location, average household income by location, and so on. It is very useful when integrated with your own business data. For example, you may want to see total sales by state in the United Sates and then compare them with total population by state; this gives you an idea of your sales relative to population in each state.
Our first task is to see which kind of demographic data is available on a per country basis programmatically. An active Map object exposes a DataSets collection. You can access the demographic data by calling the GetDemographics method on the DataSets collection:
    //Get the demographics dataset by calling the
    //GetDemographics method 

    MapPoint.DataSet dataset
     = map.DataSets.GetDemographics(MapPoint.GeoCountry.geoCountryUnitedStates);
The GetDemographics method takes the country as an input argument and returns a DataSet object containing demographic data for the specified country.
You can obtain a demographic DataSet for other countries using MapPoint.GeoCountry enumeration. For example, to get demographics for the United Kingdom, call GetDemographics with the MapPoint.GeoCountry.geoCountryUnitedKingdom value.
To get all demographic data categories supported by this DataSet, loop through its field collection:
    //Get dataset details
    if(dataset != null)
     {
       //Get all field names
       for(int i=1;i<=dataset.Fields.Count;i++)
        {
          object index = i;
          //Add the field name in a listbox
          listBox1.Items.Add(dataset.Fields.get_Item(ref index).Name);
        }
     }
This code generates a listbox, shown in Figure 3-10, filled with all demographic categories that are available in MapPoint 2004 North American edition.
Figure 3-10:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Working with Your Business Data
Using the MapPoint 2004 APIs, you can import external data (i.e. your business data) and use it to create data maps. MapPoint APIs support variety of data sources for importing data. The data sources supported by MapPoint include, but are not limited to:
  • Text (.TXT, .CSV, .TAB)
  • Microsoft Excel spreadsheets
  • Microsoft Access database
  • Any relational database, such as SQL Server or Oracle Server
You can also import Outlook contacts. In this section, I will show how to import data from these data sources and display data maps using the imported data. Then I will show how to integrate your business data with demographic data. You will be able to display data maps rich with both business information and statistical data.
Importing external data is generally simple using the MapPoint 2004 APIs. You use the DataSets.ImportData method to import external data. This method returns reference to a valid DataSet object upon successfully importing data . The returned DataSet object is also added to the current active map's DataSets collection so that you can use the dataset later; however, once the map is closed, the imported dataset is lost.

Section 3.4.1.1: Understanding the DataSets.ImportData method

Like the DisplayDataMap method, the ImportData method is also exposed on the DataSets collection, mainly due to the fact that the imported data will be stored as a data set in MapPoint and made available from the DataSets collection for later use. The signature for the ImportData method is as follows:
    DataSets.ImportData(DataSourceMoniker, ArrayOfFields, Country, Delimiter, ImportFlags)
Let's discuss each argument in detail.
To import external data into a MapPoint 2004 DataSet, indicate the data source specifics, such as the path to the data source for a text file or an Outlook contacts file moniker, and pass this as the DataSourceMoniker argument. Even though this argument is an
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Querying a MapPoint DataSet
A MapPoint DataSet object gives you the ability to query the dataset to access the records. These queries can be pure data access queries (using the DataSet.QueryAllRecords method) or geometry- and location-based queries (using the DataSet.QueryCircle, DataSet.QueryPolygon, and so on). In any case, a successful query returns a RecordSet object that you can loop through the records and access the fields and the values contained in that record. With this introduction, let's now look at different ways to query a dataset.
You can query a DataSet using specific location queries for which the DataSet object provides methods, such as QueryCircle, QueryPolygon, and QueryShape. I will discuss the QueryCircle and QueryPolygon methods in this section and the QueryShape method shortly after introducing the shape concepts in the next section.
The QueryCircle method allows you to limit your query based on geographic distance. An example of this type of query is, "Find all orders that are being shipped to locations more than 100 miles away from my warehouse." In this query, you would use the QueryCircle method, specify the center of the circle as your warehouse, and set the radius of the circle to 100 miles.
Now, let's get back to our supply-chain optimization problem: imagine that you have a warehouse in Redmond, WA, and you have a database of all orders shipped on the West Coast. You can query the shipment records to find out which orders travel for more than 100 miles from your warehouse in Redmond by following these steps:
  1. Import all orders from SQL Server into a dataset:
        //Create a new dataset
        MapPoint.DataSet dataset = map.DataSets.AddPushpinSet("NorthWind Orders");
    
        //Import orders records from your SQL Server
        try
           {
              //Open the connection
              connection.Open( );
              //Get a sql reader from the query
              System.Data.SqlClient.SqlDataReader sqlReader =
                        command.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
              if(sqlReader != null)
               {
                  while(sqlReader.Read( ))
                   {
                      //Get the name of the customer
                      string customername  = sqlReader["ContactName"] as String;
                      //Get the company name
                      string companyname  = sqlReader["CompanyName"] as String;
                      //Get the address string
                      string address = sqlReader["Address"] + ", " + sqlReader["City"] + ",
                                     " + sqlReader["Region"] + ", " +
                                      sqlReader["PostalCode"] + " " + sqlReader["Country"];
    
                     //Find location
                     MapPoint.Location location = null;
                     try
                       {
                          //Find the address
                          MapPoint.FindResults findrs = map.FindResults(address);
                          //If no results found, skip to next record
                          if(findrs == null || findrs.Count <= 0)
                              throw new Exception(address);
                          //Get the location
                          location = findrs.get_Item(ref index) as MapPoint.Location;
                          //Create a pushpin
                          if(location != null)
                           {
                             MapPoint.Pushpin pushpin =
                                  map.AddPushpin(location, companyname);
                             //Assign the contact name
                             pushpin.Note = "Contact : " + customername;
                             //Move to the pushpin dataset
                             pushpin.MoveTo(dataset);
                           }
                       }
                  catch
                       {
                          //Do some logging
                       }
                }
    
                //Close the reader; this will automatically close the connection
                //due to the command behavior setting during the
                //ExecuteReader method
                sqlReader.Close( );
              }
            }
        catch
            {
              //Do clean up
            }
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Working with Shapes
A shape in MapPoint 2004 context is an entity that can be drawn on top of a map, queried for location information, or altered in appearance. MapPoint 2004 APIs allow you to draw, query, and alter the shapes on any given map. These shapes include circles, polygons, polylines, text boxes, drivetime zones, and so on. Remember that the circles, pies, series columns, and all other shapes drawn using the DisplayDataMap do not belong to shape category, since there is no way for you to either query or alter the circle shape appearance. Now, let's see how to work with shapes in MapPoint 2004.
MapPoint 2004 APIs expose all shapes on any given map as a Shapes collection (similar to the DataSets collection). Using this Shapes collection, you can add a new shape or retrieve an existing shape. To add a new shape, the Shapes collection offers Add XXXX methods (where XXXX can be a line, text box, polyline, and so on). Table 3-8 provides a list of these methods and their descriptions:
Table 3-8: Shape-drawing methods exposed on the Shapes collection
Methodname
Notes
AddDrivetimeZone
Adds a freeform closed shape representing the driving distance from a point on the map within a specified amount of time
AddLine
Adds a new line to the map between two points
AddPolyline
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Working with Territories
MapPoint 2004 provides APIs to generate and display territories based on external data (such as a text file or Access database). As with importing any other location data, the DataSets object is used to import territories. The DataSets object provides the ImportTerritories method to import territories from any source supported by the ImportData method.
The following code shows how to create a territory map using the 2004 U.S. presidential election results:
    //Using the MapPoint Sample Territory data from txt file
    string filePath = @"C:\MapPointData\2004Elections.xls";
    //Define fields
    object missing = System.Reflection.Missing.Value;
    //Import data and create a dataset
    MapPoint.DataSet dataset =
        map.DataSets.ImportTerritories(filePath, missing,
        MapPoint.GeoCountry.geoCountryUnitedStates,
        MapPoint.GeoDelimiter.geoDelimiterDefault,
        MapPoint.GeoImportFlags.geoImportExcelSheet);

    //Zoom to the territory map
    dataset.ZoomTo( );
The previous code yields the territory map shown in Figure 3-18.
Figure 3-18: U.S. presidential election results as a territory map
Territories are one of the most interesting features of MapPoint 2004; however, they are also a feature that has serious limitations in terms of what you can do with the MapPoint 2004 APIs. For example, if you want to query a location to determine which territory it belongs to, there is no API that can be used for this purpose. However, there is a workaround to achive this.
While there is no territory query API available in MapPoint 2004, you can determine a location's territory using a combination of other APIs, specifically Map.ObjectsFromPoint and Dataset.QueryCircle methods, in MapPoint 2004.
Say, for example, you are given the location "Redmond, WA," and now you have to determine whose sales territory it belongs to. In order to do that, you must import the territories into a dataset using the Datasets.ImportData
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Where Are We?
In this chapter, you have learned how to work with native demographic data and your business data to generate data maps in different map styles. You have also seen how to import data into MapPoint from variety of data source such as text, Excel, Access, SQL, and so on. We also have examined working with shapes, drivetime zones, and territories.
Working with the DataSets and Shapes collections can be among the most interesting tasks of the MapPoint APIs. These two objects provide the core of the location-based business intelligence processing power within MapPoint 2004.
In the next chapter, I will shift the focus slightly from the core MapPoint 2004 to focus on performance, interfacing with other applications by writing Add-Ins, and making MapPoint 2004 work with GPS devices.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Advanced MapPoint 2004 Programming
In the previous chapters, you learned how to use MapPoint 2004 APIs to perform simple location-oriented tasks, business data display, and management tasks. Now it's time to learn how to integrate and extend MapPoint 2004 APIs, as well as how to improve the performance and memory usag