MapInfo 2004 MapXtreme Developer Guide
Below you will find brief information for MapXtreme 2004. This guide will help you to understand the core concepts and architecture. It includes details about accessing data, find locations, using themes and legends, working with web-specific classes, planning a web application, using the desktop tools, customizing controls and dialogs, stylizing your maps, and much more.
Advertisement
Advertisement
Developer Guide
Information in this document is subject to change without notice and does not represent a commitment on the part of the vendor or its representatives. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, without the written permission of MapInfo
Corporation, One Global View, Troy, New York 12180-8399.
© 2004 MapInfo Corporation. All rights reserved. MapInfo, the MapInfo logo and MapXtreme 2004 are trademarks of MapInfo Corporation and/or its affiliates.
MapInfo Corporate Headquarters:
Voice: (518) 285-6000
Fax: (518) 285-6070
Sales Info Hotline: (800) 327-8627
Government Sales Hotline: (800) 619-2333
Technical Support Hotline: (518) 285-7283
Technical Support Fax: (518) 285-6080
Contact information for MapInfo Corporation is located at:
http://www.mapinfo.com/contact_us.cfm
.
WARNING: This software uses patented LZW technology for .GIF image compression and/or decompression. (Unisys United States patent No. 4,558,302 and corresponding patents in Canada, France, Germany, Italy, Japan and the United Kingdom). GIF images compressed or decompressed for transmission via the Internet or via any other on–line communication capability may not be sold or licensed for revenue, or used by an Internet Service Provider or in paid advertisements unless the user first enters into a written license agreement with Unisys. For information concerning licensing, please contact: Unisys Corporation Welch Licensing Department
C1SW19 Township Line & Union Meeting Roads P.O. Box 500 Blue Bell PA 19424 Fax: 215-986-3090
Adobe Acrobat ® is a registered trademark of Adobe Systems Incorporated in the United States.
ECW by ER mapper © 1998–2001.
LEAD Technologies, Inc. © 1996.
Products named herein may be trademarks of their respective manufacturers and are hereby recognized. Trademarked names are used editorially, to the benefit of the trademark owner, with no intent to infringe on the trademark.
April 2004
Table of Contents
Windows 2000 Post-Service Pack 4 (SP4) COM+ 1.0 rollup package 27 . . . . . . . . . . . . . . 24
Developer Guide Table of Contents
Chapter 4: Understanding the MapXtreme 2004 Architecture . . . . . . . . . . . . . . . . . . 43
Comparing the New Object Model to the Previous Object Models. . . . . . . . . . . . . . . . . . . 45
Chapter 5: Working with Core MapXtreme 2004 Classes . . . . . . . . . . . . . . . . . . . . . . 49
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
4
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Table of Contents
Chapter 6: Adding Mapping Capability to your Applications . . . . . . . . . . . . . . . . . . . 54
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
5
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Table of Contents
Multi Dimension Geometry Support (Greater than two Dimensions) . . . . . . . . . . . . . . . . . 106
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
6
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Table of Contents
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
7
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Table of Contents
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
8
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Table of Contents
Chapter 15: Dialogs and Controls for Desktop Applications . . . . . . . . . . . . . . . . . . 180
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
9
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Table of Contents
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
10
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Table of Contents
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
11
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Table of Contents
Appendix C: Understanding the New MapInfo Workspace . . . . . . . . . . . . . . . . . . . . 296
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
12
MapXtreme2004_DevGuide_A4.pdf
Introduction to
MapXtreme 2004
1
Welcome Developers to MapInfo Corporation’s entry into the world of .NET programming. In support of
Microsoft’s .NET framework for Windows, we have re-architected our MapX and MapXtreme code base, to reflect a single object model for developing or extending mapping applications for the desktop, traditional client/server environments or the Web.
Our first release in this venture is MapInfo MapXtreme 2004, an application development tool for organizations who recognize that data visualization and mapping can help you make better business decisions and manage assets and operations more effectively. MapXtreme 2004 is for organizations that need to incorporate location analysis or definition into desktop, client/server and web-based products. MapXtreme 2004 can be used as a powerful analysis toolkit to make critical business decisions such as optimal locations for sales offices, how to transport products most efficiently, and how to manage and protect assets. Developers can use MapXtreme 2004 to shorten their development time and improve performance, reliability, and security.
In this chapter:
!
!
!
!
Developer Guide
Welcome to MapXtreme 2004
Chapter 1: Introduction to MapXtreme 2004
MapXtreme 2004 is a Windows development toolkit designed to allow developers to create more powerful location-enhanced desktop and client/server applications. Use these tools and namespaces to create your own applications or enhance existing applications to include location-based information and analysis. The MapXtreme 2004 development toolkit gives developers maximum control and flexibility in deploying solutions whether those solutions target the desktop, an enterprise, or the Web. Further, you can reuse the code you write for one platform to enhance or create solutions for the other, which will save you time and effort both now and in the future.
The MapXtreme 2004 toolkit allows you to develop mapping solutions for all of these environments on the ubiquitous Windows platform. Our goal is to give developers the tools to build the most powerful map-based solutions possible in the shortest amount of time possible.
The following components and features are included in MapXtreme 2004:
•
Product framework: MapXtreme 2004 Object Model, which is compatible with the
.NET framework. See
Overview of the MapXtreme 2004 Architecture in Chapter 4 on page 44
•
Development Environment Tools: MapXtreme 2004 provides controls, dialogs, and templates that developers can use in Visual Studio.NET to develop Windows applications (using Windows Forms) and web applications (using ASP.NET).
Developers can extend these components to provide more advanced functionality available through the object model. See
Web Controls in Chapter 12 on page 150
Overview of the MapInfo.Windows.Controls Namespace in Chapter 15 on page 181
•
Full Mapping and Analytical capabilities: All the features and operations provided in the previous releases of MapXtreme and MapX are available, including map creation, display, data access from a wide variety of sources, thematic mapping, raster and grid handling, object processing and presentation.
•
Scalable Infrastructure: MapXtreme 2004 provides object pooling and caching capabilities that developers use to fine tune web applications based on performance requirements. See
Chapter 5: Working with Core MapXtreme 2004 Classes
•
Runtime Deployment: MapXtreme 2004 uses Windows Installer technology (merge modules) that developers can use to install or redistribute runtime components used in deployed applications. See
Deploying Your Application in Chapter 2 on page 32
•
Extensive Documentation: MapXtreme 2004 includes a help system that describes the MapInfo .NET object model, on which MapXtreme 2004 is based. The help is organized by namespace and is integrated in the VisualStudio.NET development environment.
•
Sample Applications and Data: MapXtreme 2004 provides samples that demonstrate
MapXtreme 2004 functionality and sample data for you to use.
Overview of Key Features
MapXtreme 2004 is packed with features and conveniences to help you build your Windows
Forms or ASP.NET Web applications efficiently. Regardless if you are making the map the cornerstone of your application or are adding some basic mapping functionality to support your existing application, the framework and tools you use are the same.
Here are some highlights of what you can do with MapXtreme 2004. If you are new to MapInfo
Corporation’s mapping products, be sure to also see
for additional help on the basics.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
14
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 1: Introduction to MapXtreme 2004
For developers upgrading to MapXtreme 2004, see the sections that follow this list for what’s
new and changed in the product. See also
Migrating to MapXtreme 2004 on page 18
mapping of old features to new ones.
•
Tables, Layers, Features: MapXtreme 2004 maps are made up of geographic features like point locations, boundaries and street networks. The feature information is stored in tables and display in the map in layers.
•
Data access: MapXtreme 2004 supports data from a wide variety of sources, including spatial and non-spatial RDBMS, MS Access, dBase and ASCII, as well as its own native type the MapInfo Table (.TAB).
•
Selections and Searches: This is a common and useful operation when working with mapping data. It allows you to find, using attributes or spatial queries, just the data that matches your criteria.
•
Thematic mapping: One of the most widely used ways of analyzing your data is to show the visual relationship and underlying data through theme maps. MapXtreme
2004 supports the creation and use of six themes: ranged, individual value, graduated symbol, dot density, and pie and bar charts.
•
Labeling: What’s a map without labels? MapXtreme 2004 provides a sophisticated labeling capability that not only allows you to label features with names or other information (column data or expressions), you can create ranged and individual value themes on the labels themselves to impart your message without relying on text alone.
•
Geographic processing and analysis: This refers to making new features from existing ones, such as combining postal code boundaries to create sales territories. It also refers to using the geographic component of the feature (its location coordinates) to learn more about its relationship to other features. For example, create a buffer around a point that measures five miles in radius to find out what other points fall within the buffer zone.
•
Map Styling: Labeling is one form of map styling that you can control on your map in nearly infinite ways. Style also refers to the color, patterns, fonts, line styles and symbols of map features that is used in many areas of MapXtreme 2004, including features, adornments (map titles), dialog boxes and text. This allows you to create maps that are visually pleasing and make your location data easily understood.
•
Projections and Coordinate Systems: These are ways of representing locations on a two-dimensional map. Knowing the coordinate system of your data allows MapXtreme
2004 to line up features properly for accurate display and measurement. MapXtreme
2004 supports a wide variety of projections and coordinate systems and provides information for creating your own.
•
Tools and Convenience Features: MapXtreme 2004 provides a host of tools that can be added to your application or you can customize them for additional functionality. For streamlined Windows Forms and Web development, MapXtreme 2004 provides controls for tools and dialogs that are integrated into VisualStudio.NET. Code and UI samples show how features work or can be included directly in your application. Two data management utilities are included for managing tables that you will use in your application (Geodictionary Manager) and manage workspaces for ease of use and portability (Workspace Manager).
•
Performance and Persistence: MapXtreme 2004 is designed to maximize the performance of your application by offering pooled sessions and multi-threading so that processes are carried out as efficiently as possible within the available system resources. Persistence is maintained both within the session and between sessions by saving information in a new XML-based workspace format.
•
Geocoding and Routing: Geocoding is the process of adding a location to data in the form of coordinates so that it may be displayed on a map. Routing is the ability to find a route by shortest travel time or distance between points. MapXtreme 2004 provides clients for geocoding and routing so your application is ready to take advantage of
MapInfo’s servers for these processes (server-side processing is not included in
MapXtreme 2004.)
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
15
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
What’s New
Chapter 1: Introduction to MapXtreme 2004
New Object Model
With the new architecture underlying MapXtreme 2004 we now have a single model on which our mapping products will be based going forward. By basing it on Microsoft’s .NET framework, we can take advantage of many of its features, such as ADO.NET.
Table Data Model
New for MapXtreme 2004 is the focus on the table as the basic unit of data access. Previous releases of MapX and MapXtreme used a layer-centric model in which you added a layer to a map or bound data to layers already in the map. In MapXtreme 2004 to get data into your application you open a table. This change brings MapXtreme 2004 in line with MapInfo
Professional and keeps to the single object model for all MapInfo mapping products.
Data Access
MapXtreme 2004 now separates the concept of data from map. All data operations are carried out via the
MapInfo.Data namespace
. Operations include adding and removing tables, and inserting, updating and deleting records from a variety of data sources.
.NET Dataset Provider support: allows any ADO.NET dataset provider to be treated as an
Table in MapInfo.Data. This will allow you to use external non-mappable data.
MISQL: MapXtreme 2004 provides a new SQL specification for use in extracting data from tables.
New View Table Format
MapXtreme 2004 introduces a new View table version (800) that supports the new MI SQL syntax, table descriptions and metadata.Views are tables whose definition is based on a Select statement. Prior to MapXtreme 2004, the select statement in a view table was based on
MapBasic syntax. Support remains for parsing and processing MapBasic SQL for these tables.
New views, however, should be created with the new select syntax. For more information on MI
Appendix A: MapInfo SQL Reference
Raster and Grid Table Structures
Raster and Grids now have new table structures (obj, MI_Style, MI_Raster, MI_Grid) and new datatypes RasterImageInfo and GridImageInfo. This allows you to query any column in a raster or grid image.
Style Object Model
Style is now its own object; it is no longer stored in an object. Each table containing a geometry column will also contain a Style column (alias MI_Style) containing a new datatype Style. For style overrides, the Feature class provides FeatureStyleModifier and
FeatureOverrideStyleModifiers.
The style object model also makes available several collection classes (style repositories) to hold styles for the style dialog controls.
Style enhancements include shipping new larger custom bitmap symbols and additional fill patterns and line styles. For your own custom styles, you can create larger, non-square bitmaps with up to 24-bit color depth.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
16
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 1: Introduction to MapXtreme 2004
Workspace
MapXtreme 2004 introduces a new workspace format and utility for easy handling of tables and maps. The MapInfo Workspace (.MWS) is XML-based for ultimate portability and easy use.
The Workspace Manager is a GUI tool for creating and managing workspaces containing table settings, named connections, multiple map views and more. Workspace Manager replaces the
MapX Geoset Manager.
Adornments
The Adornments class holds items that would have been considered annotations in previous releases of MapXtreme. Adornments include map titles, scalebars, legends and user-drawn objects.
WFS and WMS
MapXtreme 2004 provides built-in OGC Compliant Web Services (server and client) for Web
Features Services (WFS) and Web Mapping Services (WMS). Use a WFS to retrieve read-only data encoded in Geography Markup Language (GML) for map display and analysis. Use a
WMS to retrieve a raster image for use as a display layer in your map. This specification supports transparent pixel definition for image format, which means you can use WMS images as overlays and not solely as the bottom layer of your map.
Thread Safety
MapXtreme 2004 is thread safe and can run in a multithread environment as long as no instances of objects are shared across threads.
Clients for Geocoding and Routing
Use the included clients in your application when you wish to connect to MapInfo routing and geocoding servers. These clients require the use of MapInfo Corporation’s geocode server or geocoding service (not included in MapXtreme 2004.
Feature Processing
Feature processing now includes the ability to use Convex Hull buffers and new GroupBy and
Aggregation functions (FeatureProcessor class). The erase function in previous MapX/
MapXtreme releases is now called Difference and is handled via the FeatureGeometry class.
New Tool and Dialogs
A variety of tools and controls have been provided in MapXtreme 2004. New tool functionality includes SelectRegion. For Windows Forms application development, decrease your design time by using pre-built drag-and-drop dialog and tool controls. For web applications, we offer a flexible tools architecture that you can tie in with your own tools.
New Sample Applications
Many of the new features have samples that can be run in VisualStudio.NET for learning how to program in the new object model. You will find them in the Samples folder after installation.
What’s Changed
Themes
Themes are no longer layers that are attached to a base layer. Themes are of two types:
Modifier themes (Ranged, Individual Value, Dot Density) and Object themes (Graduated symbols, multivariable themes (pie and bar)).
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
17
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 1: Introduction to MapXtreme 2004
Animation
To facilitate the creation of animation layers, use the GroupLayer with no backing store so that the layer is always redrawn.
Label Enhancements
Labels now exist in their own layer and can be re-ordered independently of the feature layer on which they are based.
Geosets
Geoset Manager from MapX has been replaced by the Workspace Manager, a utility that allows you to build and save XML-based workspaces. Geosets continue to be supported, however, you cannot create any new geosets in MapXtreme 2004. Workspaces, however, improve upon geosets in that they can store more information about the map including remote table and thematic display information.
Geodictionary Manager
This tool for registering tables for databinding has been updated to support XML-based geodictionary files. The command line behavior is no longer supported.
Drilldown Tables
Drilldown tables are not supported in this release of MapXtreme 2004.
Migrating to MapXtreme 2004
The following is a table of MapX and MapXtreme features and functionality from the previous releases of MapX and MapXtreme and the equivalent for this release of MapXtreme 2004. As with any new architecture of a product, note that the equivalent may not be exact. Use the
MapXtreme 2004 topics in the right column of this list to find further details elsewhere in this
Developer Guide and in the online help and object model. A full list of the MapX object model and the equivalent functionality in MapXtreme 2004 is covered in
Appendix A: Migrating to
MapXtreme 2004
MapX5.0 /MapXtreme3.0
Map object
MapXBroker
Layer-centric model
MapXtreme 2004
Map class: holds collection of Layers
MapControl: way to view a map on a form.
Session class: starting point for all MapXtreme 2004-based applications.
Related topics: MICommand, Catalog, Pooling.
Table-centric model
Related topics: Table metadata (TableInfo class), Feature class,
Column class (MI_Geometry, MI_Style, MI_Key), MapInfo
ADO.NET data provider
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
18
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 1: Introduction to MapXtreme 2004
MapX5.0 /MapXtreme3.0
Datasets, data binding
Geosets. Geoset Manager
Annotations
Thematic mapping Same thematic map types. Themes are no longer layers.
Related topics: ModifierThemes (graduated symbol, pie and bar themes), ObjectThemes (ranged, individual value, dot density themes.
MapInfo.Mapping.Thematic namespace
Feature layer and Feature Collections
FeatureGeometry: all geometries are now objects. Includes point, multipoint, curve, multicurve, polygon, multipolygon, ring. Geometries include rectangle, rounded rectangle, ellipse, legacy arcs, legacy text.
Related topics: CoordSysFactory (registered coordinate systems), object processing (see FeatureProcessor, below)
FeatureFactory
Tools
FeatureProcessor class: object processing Buffer, Combine,
Intersection, ConvexHull
Related topic: Difference (formerly Erase) in FeatureGeometry class
New tool: SelectRegion. Can assign to mouse buttons and configure mouse wheel for zooming.
Raster and Grid Images
MapXtreme 2004
Add a temporary column to an Table using the Table.AddColumns() method.
Related topic: Geodictionary Manager
Workspaces (.MWS): new XML format. Geosets are still readable.
Related topics: Workspace Manager
Adornments: a Legend, a Title, a Scalebar, or some other similar user-defined object in a single map.
Label objects and Label collections
Selection object
Spatial Server connectivity
New table structure, RasterImageInfo, GridImageInfo
Related topics: controllable styles: brightness, contrast, color/ grayscale, translucency, one-color transparency.
MapInfo.Raster namespace
LabelLayer: allows the separate ordering of labels and layers.
LabelSource: information from the data source that is used for labeling.
Selection class: a multi-feature collection of lists of features that are tied to a table.
MI ADO.NET data providers, new MI SQL language.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
19
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
MapX5.0 /MapXtreme3.0
Style Object
Chapter 1: Introduction to MapXtreme 2004
MapXtreme 2004
Style class: new object model. Style are now objects, not properties of other objects; information is stored in column MI_Style.
Related topics: FeatureStyleModifiers, FeatureOverrideStyleModifiers in the Mapping namespace.
Learning to Use MapXtreme 2004
After you install MapXtreme 2004, your next priority will be learning how to use the MapInfo components. In this section we list the wide variety of support mechanisms we have created to get you up and running quickly and with minimal disruption in your development timetable.
Support Resources
MapInfo is committed to supporting new MapInfo developers as well as our long time customers as we move into the new .NET environment. We provide a wide variety of tools to help you make the transition or get up and running quickly in the Visual Studio.Net environment with the following resources.
Documents and Help Systems
This document, the MapXtreme 2004 Developer Guide, provides an overview of the
MapXtreme 2004 development environment and namespaces. The Visual Studio .NETintegrated Help System provides the more specific API-level information you need to use these tools to develop integrated Windows desktop and web-based applications with MapInfo’s powerful mapping components. If you have comments regarding the documentation, you can send them to
.
Note:
The above-mentioned email address should not be used for questions specific to the software or clarification about subjects contained in the documentation. Please send those questions to Technical Support (see below).
If you are new to using or developing with MapInfo mapping products, be sure to see
.
Technical Support
MapInfo Corporation offers unparalleled technical support for users of MapInfo software products. Our Technical Support department provides technical assistance to registered users of MapInfo software – so you don't need to be an expert in all aspects of our products in order to get results. See the MapInfo Web site for information on the tech support offerings.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
20
MapXtreme2004_DevGuide_A4.pdf
Getting Started
2
This chapter provides all the information you need to install, configure, and deploy your first MapXtreme
2004 application.
In this chapter:
!
!
!
!
!
!
Building ASP.NET Web Applications Without A Template . . . . . . . . . . . . . . . . . . . . . 32
!
Developer Guide
Installation
Chapter 2: Getting Started
The following sections describe MapXtreme 2004 system requirements and the installation procedure.
System Requirements
MapInfo has tested and supports MapXtreme 2004 on the following operating systems.
Operating Systems
Development Framework Support
• Windows 2000 Professional SP 4
• Windows 2000 Server SP 4
• Windows 2000 Advanced Server SP 4
• Windows XP Professional SP 1
• Windows 2003 Server Standard Edition
• Windows 2003 Web Edition
• Windows 2003 Server Enterprise Edition
• Microsoft .NET Framework 1.1
• Visual Studio .NET 2003
• Visual C#
• VB.NET
Additional software requirement include:
•
MDAC 2.7 or later (MDAC 2.8 is located on the MapXtreme 2004 product CD.
•
IIS 5.0 or IIS 6.0
Minimum system requirements
Memory Windows Server 2003: 160 megabytes (MB) RAM
Windows Server 2003 Web: 160 MB RAM
Windows XP: 160 MB RAM
Windows 2000: 96 MB RAM
Windows 2000 Server: 192 MB RAM
Windows 2000 Advanced Server:192 MB RAM
600-MHz Pentium III-class processor recommended
Supported Databases include:
•
SQL Server 2000
•
MS Access
•
Informix IDS 9.3
•
Oracle 9ir2
•
Oracle 9ir1
•
Oracle 8.1.7
•
Oracle 9ir2 Locator
•
SpatialWare 4.6 for SQL Server 2000
•
SpatialWare 4.8.1 for SQL Server 2000
•
SpatialWare 4.5.1 for Informix IDS 9.3
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
22
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Types of Installations
Chapter 2: Getting Started
MapXtreme 2004 provides two installation types: one for Development (SDK) and one for
Deployment (Runtime). Each is selectable from the product CD Browser. This section explains the licensing requirements for each installation type.
Development (SDK) Installations
For SDK installations, if you are using a software-copy protected version (SCP) of MapXtreme
2004, you will be required to obtain a license from MapInfo Corporation to continue using the product after the 60-day trial period.
For non-copy protected versions (NCP), the installation provides you with a non-expiring development license.
Deployment (Runtime) Installations
For Desktop Runtime installations, you must obtain a runtime license from MapInfo
Corporation for each desktop application installation. Place the license file in the same folder as the application executable to avoid potential collisions with other applications.
For Web Runtime installations, you must obtain a runtime license from MapInfo Corporation for each web installation you perform. Place the license in the path \Common
Files\MapInfo\MapXtreme\6.0.
To obtain a runtime license contact your local MapInfo reseller or your local MapInfo Customer
Support representative. To find your local MapInfo office, visit
www.mapinfo.com
and click on
Contact Us.
Before You Install
The following are things to know about prior to installing MapXtreme 2004.
Administrator Privileges
In order to install MapXtreme 2004, it requires that you are either an Administrator on the machine or the current user is a member of the group Administrator.
Install Visual Studio .NET 2003 First
It is recommended that before you install MapXtreme 2004 that you should have Visual Studio
.NET 2003 installed. If you do not have Visual Studio .NET 2003 or the Microsoft .NET
Framework installed, the installer will prompt you to install the Microsoft .NET Framework, and will then install it prior to installing MapXtreme 2004.
Note:
If you do not have Visual Studio .NET 2003 installed, some of the sample templates will not be installed.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
23
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 2: Getting Started
Windows 2000 Post-Service Pack 4 (SP4) COM+ 1.0 rollup package 27
If you are running Windows 2000 and intend to use MapXtreme 2004 in a Web-based application, you must obtain the Microsoft Windows 2000 Post-Service Pack 4 (SP4) COM+
1.0 rollup package 27. For more information, see the Microsoft Knowledge Base Article -
822618 at
http://support.microsoft.com/?id=822618
.
Additional Installation Features
The MapXtreme 2004 CD provides online installation instructions to follow. You can also access the instructions via the Help button on the install dialogs during the installation procedure.
MapXtreme 2004 provides free sample data for a variety of world locations. To install the data, choose Install Sample Data from the CD Browser. You can control how much of the data you wish to install by choosing the Custom option. The Complete option (default) will install about
300 MB of world data sets. For a listing of available data sets, see
The MapXtreme 2004 CD Browser also provides a link to the PDF version of this Developer
Guide. Choose from US Letter or A4 format.
Installing MapXtreme 2004 in Your Environment
To install MapXtreme 2004:
1.
Place the MapXtreme 2004 CD in the CD drive.
2.
At the CD Browser main page, click Install. The Install Description page displays.
3.
Choose either Development Install to install the SDK or Deployment Install to install the runtime version.
Note:
The Deployment installation requires a runtime license. Contact your reseller for more information.
4.
Choose Install SDK or Install Runtime. At the Welcome dialog box, click Next to proceed. For deployment installations skip to
Note:
You may also review the installation instructions and install sample data from this page.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
24
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 2: Getting Started
5.
At the Installer Welcome dialog box, read the information in the panel and click N
EXT
to proceed.
6.
Choose to accept the License Agreement. Click N
EXT
. The Customer Information dialog box displays.
7.
At the Customer Information dialog box, enter your user name and company name in the appropriate fields. Click N
EXT
. The Setup Type dialog box displays.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
25
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 2: Getting Started
8.
At the Setup Type dialog box, select C
OMPLETE
or C
USTOM
. Choose C
USTOM
if you want to choose the features to be installed or to install to a location other than the default (C:\Program Files\MapInfo\MapXtreme\6.0). Click N
EXT
. If you chose
C
OMPLETE
9.
If you chose Custom in the previous step, select the components that you want to install, or click the C
HANGE
button to specify a new installation path. Click N
EXT
.
10. At the Ready to Install the Program dialog box, click I
NSTALL
.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
26
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
11. The Installing MapXtreme 2004 dialog box launches.
Chapter 2: Getting Started
12. At the InstallShield Wizard Completed dialog box, click F
INISH
to leave the software installer.
Creating Applications in Visual Studio .NET
With MapXtreme 2004, it's easy to add a map to your application. MapInfo provides you Visual
Basic.NET and Visual C# project templates that allow you to create a simple mapping application without writing any code.
Map Applications
The following procedure outlines the steps to make a simple map application.
Note:
This example is specific to Visual Basic.NET. To create a Visual C# Map application substitute Visual C# for Visual Basic in the following steps.
1.
From the F
ILE
menu, point to N
EW
then click P
ROJECTS
. The New Project dialog box displays.
2.
In the Project Types frame of the New Project dialog box, under the M
AP
X
TREME
P
ROJECTS
folder, click VB P
ROJECTS
.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
27
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 2: Getting Started
3.
In the Templates frame of the New Project dialog box select M
AP
A
PPLICATION
.
4.
Choose an appropriate name and location and click OK. MapXtreme 2004 creates the application and MapForm1.vb [Design] displays.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
28
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 2: Getting Started
5.
On the V
IEW
menu, click C
ODE
to examine the code that was written to create the application.
6.
On the D
EBUG
menu, click S
TART
to run the application.
7.
Click the O
PEN
T
ABLE
icon and load your data. The default location for sample data is
C:\Program Files\MapInfo\MapXtreme\6.0\Samples\Data.
8.
Use the controls in the toolbar to manipulate the map as you would with any other
MapInfo mapping application.
ASP.NET Web Applications
The following procedure outlines the steps to make a simple ASP.NET Web Application. For a more detailed discussion on the myriad considerations when planning a web application, see
Chapter 13: Planning a Web Application
Note:
This example is specific to Visual Basic.NET. To create a Visual C# ASP.NET map application substitute Visual C# for Visual Basic in the following steps.
1.
From the F
ILE
menu, point to N
EW
then click P
ROJECTS
. The New Project dialog box displays.
2.
In the Project Types frame of the New Project dialog box, under the M
AP
X
TREME
P
ROJECTS
folder, click VB P
ROJECTS
.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
29
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 2: Getting Started
3.
In the Templates frame of the New Project dialog box select ASP.NET M
AP
A
PPLICATION
.
4.
Choose an appropriate location and click OK. MapXtreme 2004 creates the application and WebForm1.aspx displays.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
30
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 2: Getting Started
5.
Click HTML, at the bottom of WebForm1.aspx to view the HTML for the application.
6.
On the D
EBUG
menu, click S
TART
to run the application.
7.
Use the controls in the toolbar to manipulate the map as you would with any other
MapInfo mapping application.
MapXtreme 2004 Controls
Once you have created a basic application using one of our templates, enhancements are possible using a variety of MapXtreme 2004 controls provided in the Toolbox. For Simple Map applications, MapXtreme 2004 Windows Controls are available. Any of the controls found in the
MapXtreme 2004 Windows Controls tab of the Toolbox, can be added to your form.
For MapXtreme ASP.NET Web applications, MapXtreme 2004 Web Controls are available. Any of the controls found in the MapXtreme Web Controls tab of the Toolbox, can be added to your form. See
for more information.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
31
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 2: Getting Started
Building ASP.NET Web Applications Without A Template
You may also build your ASP.NET map application without using the MapXtreme 2004 templates. For example, to create a Visual Basic Web application:
1.
Choose File > New > Project from the Visual Studio .NET menu. The New Project dialog displays.
2.
At the New Project dialog under the Visual Basic projects folder, choose ASP.NET Web application.
3.
From the MapXtreme Web Controls group in the Toolbox, choose a control and drag it onto the form. This will add three MapXtreme 2004 assemblies as references in your project: MapInfo.CoreEngine, MapInfo.CoreTypes, and MapInfo.Web.
This will also update the Web.config file to add the assembly information as well as elements for httpModules.
Deploying Your Application
There are essentially two strategies for installing the MapXtreme 2004 components on the server machine where you wish to host your application: either 1) use the included runtime installer or, 2) create your own installer and add the appropriate merge modules (MSM).
The MapXtreme 2004 SDK ships with MXTRunNCP.exe. The SCP version of the SDK version ships with MXTRunSCP.exe.
Deploying With the Runtime Installer
Use the runtime installer (MXTRunNCP.exe or MXTRunSCP.exe) as part of your custom installation process. This will install the MapXtreme 2004 assemblies and create the needed registry entries. It will also include the required .NET Framework v1.1. Runtime assemblies and files are included for both Web and Desktop applications. Additionally, you will need to install your runtime license file which you get from your reseller in the path Common
Files\MapInfo\MapXtreme\6.0.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
32
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 2: Getting Started
For Web-based application, using the runtime installer is the better strategy, as it also creates a necessary virtual directory.
All of the runtime components are installed in their default locations. There are no userconfigurable options.
One advantage of using the runtime installer is that you can apply patches from MapInfo without rebuilding your installer.
One disadvantage of using the runtime installer executable is that, depending on your application, unnecessary files may be installed.
Additionally, if you expect to install more than one MapXtreme-enabled application, you will need to maintain your own reference counts. By using the MSMs directly with your own installer, references are maintained automatically.
Steps for Deploying an Application Using the Runtime Installer
1.
From the MapXtreme 2004 CD, choose Install. The Install options page displays.
2.
Choose Deployment Installation and choose Install Runtime Environment. The install wizard opens.
3.
Follow the prompts to proceed with the installation.
Note:
You must have ADMINISTRATOR permissions on the computer in order to run the installer. You also need IIS permissions to install to the Web server.
4.
Deploy your Windows or Web application as you wish (e.g., create a deployment project in Visual Studio and add your application.)
5.
Install your runtime license file in the path C:\Program Files\Common
Files\MapInfo\MapXtreme\6.0.
If you wish to run the runtime installer from a command line, follow these instructions. The executable is located in the \Install\InstallRuntime folder on the CD and in the folder \Program
Files\MapInfo\MapXtreme\6.0\Redistributables.
•
To run the runtime installer with minimal UI, execute the runtime installer like this:
MXTRunNCP.exe /v"/qb"
•
To run the runtime installer silently, execute the runtime installer like this:
MXTRunNCP.exe /v"/qn"
If you are using a software copy protected version of MapXtreme 2004, the runtime executable is called MXTRunSCP.exe.
Deploying With Your Own Installer
Create your own installer using Windows Installer technology (MSI) and include the
MapXtreme merge modules.
A merge module (MSM file) is a single package that contains all files, resources, registry entries, and setup logic necessary to install a component. Merge modules cannot be installed alone; they must be assimilated into an MSI file.
Use this strategy if you want to fine-tune exactly which components are installed, or if you want to create your own MSI-based installer.
One disadvantage of using the MSMs is that you will have to create your own patch or updated installer if MapInfo provides updates to this product.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
33
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 2: Getting Started
An advantage of using the MSMs is that you control which components get installed and reference accounts are maintained automatically. Assemblies of a particular version will be copied into the Global Assembly Cache (GAC) only once, and reference counts will be maintained for each application using those assemblies. If one application is subsequently removed, the reference count (which then decreases by 1) will preserve the assemblies in the
GAC. When the last application using those assemblies is removed, then the assemblies themselves will be removed.
Several developer tools are available to help you create an MSI installer. InstallShield
Developer (InstallShield Corporation), Visual Studio .NET (Microsoft), and Wise for Windows
Installer (Wise Solutions) are some examples. See
http://msdn.microsoft.com/library/en-us/ msi/setup/windows_installer_start_page.asp
for more information on the Windows Installer.
The following are the merge modules for MapXtreme 2004. Include them as necessary in your installer MSI.
•
MapInfoCoreEngine.MSM: required for all MapXtreme applications built using the NCP version of MapXtreme 2004
•
MapInfoCoreEngineIntl.MSM: required for all MapXtreme applications built using the
SCP version of MapXtreme 2004
•
MapInfoMXTConfig.MSM: required for all MapXtreme applications
•
MapInfoDesktop.MSM: required for all Desktop applications
•
MapInfoWeb.MSM: required for all Web applications
•
MIFonts.MSM: required if your application or data uses the TrueType™ MapInfo symbol fonts.
•
MapInfoServices.MSM: required if your application uses the geocoding or routing clients.
•
MapInfoWFS.MSM: required if your application uses a Web Feature Service for data transformation.
•
MapInfoWMS.MSM: required if your application uses a Web Map Service for retrieving digital images.
Steps to Deploying an Application With Your Own Installer
Here are the tasks you must do to get MapXtreme 2004 to install with your installer:
1.
Include the MSMs you need.
By default, Visual Studio .NET and InstallShield looks in \Program Files\Common
Files\Merge Modules for merge modules to include. This allows you to build installers immediately, without having to re-configure your development environment.
2.
Include your runtime license file.
3.
Create a virtual directory that points to the folder C:\Program Files\Common
Files\MapInfo\MapXtreme\6.0\WebResources.
Deploying Applications that Access Data
Any Visual Basic or Visual C# application that includes data access has a dependency on
Microsoft Data Access Components (MDAC) version 2.7 or later. MDAC must be installed on a target computer prior to installing your application or the application will fail. MDAC 2.8 is located on the MapXtreme 2004 product CD.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
34
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 2: Getting Started
Application Data Files
Application data files are nonexecutable files used by an application. MapXtreme 2004 installs and uses the following set of application data files. For information about customizing these file locations, see
Location of Application Data Files in Appendix B on page 294
File Type
Abbreviation file
Pen file
Projection file
Vector symbol file
Custom symbol directory
Nadcon files jgd2000 files
Filename
MAPINFOW.ABB
MAPINFOW.PEN
MapInfoCoordinateSystemSet.xml
MapInfow.fnt
CustSymb
*.las, *.los
jgd2000.*
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
35
MapXtreme2004_DevGuide_A4.pdf
Mapping Concepts
3
Before you create a mapping application, it’s helpful to understand basic mapping concepts and how these concepts are implemented in MapXtreme 2004. This chapter discusses the common concepts you will come across as you learn MapXtreme 2004.
At the end of this Developer Guide, we have provided a Glossary of mapping and programming terms that you will also find useful.
In this chapter:
!
!
!
Developer Guide
Mapping and MapXtreme 2004
Chapter 3: Mapping Concepts
The central element to a mapping application is the map. This chapter presents a short overview of the most important mapping terms that you will likely encounter while building your application with MapXtreme 2004. The introductions also point you to the appropriate namespace in the MapXtreme 2004 object model so that you can quickly get the technical information you need. The topics include:
•
•
•
•
•
•
•
•
•
Coordinate Systems and Projections
Maps
A map displays the spatial relationship among map features, such as town boundaries, customer locations, or power lines. The map visually orients you to where those features are and what they represent. In addition to features, elements on the map can include labels, titles, legends, and themes. Themes are created based on some action taken involving the features and information on the map.
In MapXtreme 2004, the map is contained in a MapControl. These classes are included in the
Mapping namespace. The MapControl is the container that holds the map and some tools for viewing (pan, zoom in, zoom out, center). You can create maps from tables using the
MapFactory. See
Introduction to the Mapping Namespace in Chapter 6 on page 55
Tables
Tables contain the data you wish to display on the map. Tables hold rows and columns of information that describe the features, including their geometry, style, and attributes.
MapXtreme 2004 supports tables from a wide variety of sources including, native tables
(MapInfo .TAB), relational database management systems (RDBMS), dBase, MS Access,
ASCII, and ESRI ShapeFiles. Speciality tables include raster, grid, seamless, views, WMS, and
ADO.NET. The type of table is available through the TableInfo class. Tables are opened and
closed via the Catalog in the Data namespace. See
Layers
Maps are made up of layers. Layers contain map features, such as postal code boundaries, schools, or streets networks. It is important to understand the order of the layers. The bottommost layer is drawn first and the topmost layer drawn last. Layers containing features that would obscure other features (such as boundaries over points), should be placed below other layers, in this case the boundary layer.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
37
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 3: Mapping Concepts
Layers in MapXtreme 2004 can represent more than features. Layers can be raster or grid images, seamless maps (joined maps), contain labels or user-drawn features, or contain an object theme, such as a pie theme. Layers can be grouped for easier positioning and to facilitate animation of their features. The main interface is IMapLayer. For more information see
Chapter 6: Introduction to the Mapping Namespace
Features
Features are described by their geometry, style, data source, key and attributes. Typically a feature is a row in a table. Supported geometries include closed objects that cover a given area
(Polygons, MultiPolygons, Rings, Rectangle, RoundedRectangles, and Ellipses); point objects that represent single locations of data (Points, MultiPoints); and line objects that cover a given distance (Curves, MultiCurves and LegacyArcs).
One of the main uses of computerized maps is to gather information about the features. In
MapXtreme 2004 features are returned in FeatureCollections by any of several methods, either created from scratch using a schema, selected using selection tools or methods or by searching the Catalog for those that meet a specific set of criteria.
Feature classes are located in the MapInfo.Data namespace.
Labels and Legends
Maps without elements to describe what is displayed are not very useful. Maps need text such as labels and legends. Labels have been mentioned above as belonging to a type of layer called a LabelLayer. This allows you to control every aspect of a label’s visibility, position, style, and content. MapXtreme 2004 classes for working with labels include LabelSource,
LabelProperties, and LabelModifiers. See
Chapter 6: Introduction to the Mapping
Other text elements can also be used in a map to help deliver its message properly. Legends are cartographic elements that describe the features in a coded manner. For example, the legend may describe the boundaries as school districts, the lines as a power line network, or points as corporate office locations. Legends also contain a title to describe collectively what the map represents.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
38
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 3: Mapping Concepts
In MapXtreme 2004, legends are part of the Adornments class, along with map titles and scalebars. Adornments reside in the MapInfo.Mapping namespace.
Themes
Computer maps are not only useful for visibly showing spatial relationships among the map features, but you can analyze the underlying data that is associated with the features to learn more about what you see. A common analytical technique is to create a theme based on a feature layer in which the data is ranked in specific ways. For example, a ranged theme shows color blocks where each color represents features on the map that meet the same criteria. A graduated symbol theme is useful for showing distributions of populations for example, with the largest symbol representing the largest population.
Themes can also be created for labels. For example, use a ranged label theme to show the relative population size among cities. The largest labels represent the cities with the largest populations.
The MapInfo.Mapping.Thematics namespace contains classes that implement themes as style overrides on Feature layers and as Object themes. Modifier themes change the style, while object themes add a new layer. All themes implement the ITheme interface.
Tools
Most mapping applications provide an assortment of toolbar buttons (tools) to aid with common drawing tasks (such as drawing a line on the map) and navigation tasks (such as zooming in).
MapXtreme 2004 provides a number of common mapping tools, plus you can also create your own custom tools. They fall into these categories:
•
View tools
•
Select tools
•
Add Feature tools
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
39
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
•
Custom tools
The View Tools are ZoomIn, ZoomOut, Center, and Pan.
Chapter 3: Mapping Concepts
The Select Tools are Point, Polygon, Rectangle, Radius, and Region. The SelectPoint Tool can allow users to Move, Resize, and Rotate objects. The Select node mode allows users to move/ add/remove individual points to and from objects. Dynamic Selection shows what objects can be in the selection as the mouse is being moved when using the SelectRect, SelectRadius, and the SelectPolygon tools.
The Add Feature Tools are Point, Line, Polyline, Polygon, Circle, Ellipse, and Rectangle. There are Style and Insertion Layer properties for each Add Tool.
Custom Tool base classes Point, Line, Polyline, Polygon, Circle, Ellipse, and Rectangle are provided to create custom tools. Derive custom tools from Custom Tool base classes, or even from stock tools.
See
Chapter 14: Using the Desktop Tools
for more detail about using these tools in your
application.
Workspaces
While not strictly a mapping concept, workspaces are included here because they will make working with all the mapping elements easier. MapXtreme 2004 supports an XML-based workspace format that uses the .MWS extension. In it are all the settings for your maps. The
format for the workspace is explained in
Appendix C: Understanding the New MapInfo
. MapXtreme 2004 provides a utility called Workspace Manager to help you
construct workspaces and save them for later use. See
Chapter 18: Using the Workspace
Coordinate Systems and Projections
Coordinate systems and projections are two important mapping concepts about which you should have a basic understanding. Projection refers to how a map is displayed on a flat surface such as a paper map or computer screen, while a coordinate system describes how map features are spatially arranged. Both are important considerations when developing applications, especially those where spatial precision and accuracy are important.
A projection is a method of reducing the distortion that occurs when objects from a spherical surface are displayed on a flat surface. There are two main trade-offs to be considered: the preservation of equal area, and the preservation of the true shape of a feature. There are many different types of projections, each designed to reduce the amount of distortion for a given area. Some projections preserve shape; others preserve accuracy of area, distance, or direction.
A coordinate system is a set of parameters that tells you how to interpret the locational coordinates for objects. One of those parameters is projection. Coordinates can be of two types: Spherical or Cartesian. Spherical relates to locations on the curved surface of the Earth, while Cartesian describes flat surface locations in two dimensions. Both are represented by x and y coordinates. The difference comes when calculating distance or area of features that represent real Earth locations such as streets or rivers (Spherical), or relative locations, such as a map of brain anatomy or a chess board (Cartesian).
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
40
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 3: Mapping Concepts
Knowing which coordinate system your map uses is an important consideration when developing applications. Analytical operations involving distance and area calculations, such as buffering, routing, and querying use the coordinate system and projection to yield the correct results.
Coordinate system and projection classes are part of the Geometry namespace. For more information see
Chapter 7: Introduction to the MapInfo.Geometry Namespace
Geocoding with MapXtreme 2004
The maps discussed above all use data that provide additional information beyond what you can see on the map. For example, a table of store locations not only includes geographic coordinates to place the stores in the correct map location, it may contain data about the locations, such as store hours, customer service phone numbers and manager name. This gives the application the power to analyze and yield information that would otherwise be lost in rows and columns of tables.
Typically a table of custom data is included on a map along with reference layers, such as streets, town boundaries and water features that represent the true environment of the area.
These references layers are usually purchased ready to display on a map. MapInfo
Corporation sells a wide variety of reference data for locations around the world.
But the custom data, like your store locations, may not be ready to display on a map. The table must contain geographic coordinates so the mapping engine knows where to draw the objects.
The process of assigning coordinates to data is called geocoding. Any table of data that contains locational information, such as address or postal code, can be geocoded. The process involves matching the custom table against an already geocoded table covering the same location. If an address match is made, the coordinates from the geocoded table are assigned to the custom data. Then the custom data is ready to be viewed on a map.
Geocoding is a typical early step in the process of creating a map. As a developer of mapping applications, you will need to consider the type of data you wish to display on the map and its need to be geocoded.
The MapXtreme 2004 framework provides classes for using a geocoding client that can access
MapInfo Corporation’s server geocoding products. For more information about geocoding see
Chapter 19: Geocoding and Routing
and the MapInfo.Geocoding namespace in the online
Help (accessible via VisualStudio.NET).
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
41
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Routing with MapXtreme 2004
Chapter 3: Mapping Concepts
Another component is available to developers of MapXtreme 2004 is routing. Driving direction applications and those involved in planning routes for deliveries or laying cable, for example, utilize routing. Typically the goal is to locate the route by shortest distance or shortest travel time.
Like the provision for geocoding, MapXtreme 2004 allows developers to use a pre-built routing client in their application that interacts with MapInfo Corporation’s routing server products. See
Chapter 19: Geocoding and Routing
and the MapInfo.Routing namespace in the MapXtreme
2004 online Help.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
42
MapXtreme2004_DevGuide_A4.pdf
Understanding the
MapXtreme 2004
Architecture
4
The basis for the MapXtreme 2004 product is the new object model and the infrastructure we have designed. This chapter focuses on the way the MapXtreme 2004 architecture is designed so you can make informed choices for your development needs. Understanding the architecture of the product will help you create applications that efficiently use the new features and capabilities of the object model.
In this chapter:
!
!
Comparing the New Object Model to the Previous Object Models . . . . . . . . . . . . . . 45
!
Developer Guide Chapter 4: Understanding the MapXtreme 2004 Architecture
Overview of the MapXtreme 2004 Architecture
MapXtreme 2004 is built on top of Microsoft’s .NET architecture and utilizes the functionality that their infrastructure includes. This new MapInfo initiative was undertaken to present to you the power of developing, and the adaptability of the .NET platform for applications. We have also worked hard to combine the power and ease of our Windows products (primarily MapInfo
Professional and MapX/MapXtreme) into one comprehensive object model. The object model is the basis for MapInfo’s partners and customers, as well as MapInfo itself, for developing
Windows-based products for the foreseeable future.
With similar code, you can develop an application that can be deployed on either a desktop or the Web. If you develop an application for a desktop a small amount of changes allow you to deploy the same application in a web environment.
The object model is made up of a number of namespaces. Each namespace encompasses a set of related classes. Some of the more commonly used namespaces are:
•
MapInfo.Engine
•
MapInfo.Mapping
•
MapInfo.Data
•
MapInfo.Geometry
•
MapInfo.Styles
•
Mapinfo.Tools
•
MapInfo.Geocoding
•
MapInfo.Routing
•
MapInfo.Windows.Controls
•
MapInfo.Web.Controls
The following figure illustrates the MapInfo MapXtreme 2004 architecture. The
MapInfoCoreEngine.dll and MapInfo.CoreTypes.dll contain most of the core mapping and data access functionality. On top of the Core Engine are the MapInfo.Windows and MapInfo.Web namespaces that contain controls, tools, and other functionality specific to each deployment environment. Any application that gets developed from the MapXtreme 2004 object model is built atop of the MapInfo.Windows or MapInfo.Web namespace.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
44
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 4: Understanding the MapXtreme 2004 Architecture
MapInfo MapXtreme 2004 Architecture
Comparing the New Object Model to the Previous Object Models
If you have used MapX and MapXtreme before, you will find similarities and differences in the way they work from MapXtreme 2004. This section describes some of the major differences between MapXtreme 2004 and previous versions of our APIs.
Specific Object Model Implementation Differences
The Map object from MapX is now represented by 3 or 4 classes. The Map contains the layers, area of interest (view), Adornments, Legends, regardless of how it is being viewed. The
MapControl holds the Map object and acts as a control for the Map and tools which interact with the Map. There is a MapControl for both Windows Forms (desktop) applications and
ASP.NET (web) applications. The MapExport class can be used to export a Map to a file or stream. The Session holds the collection of Maps, Selections, and Tables. Cartographic scale is now fully supported. Label layers can be used to better control the position of labels. Group
Layers allow for treating many layers as one in the layer hierarchy.
The MapX Datasets concept has been replaced by a more flexible set of options in the
MapInfo.Data namespace. MapXtreme 2004 uses ADO.NET for data access. ADO.NET allows a wide variety of data formats to be accessed with very similar code, facilitating easy transition between data sources. We have added a wider variety of cursors for forward and backward access through a database table.
MapXtreme 2004 uses a table-centric data model. In previous versions of our API, maps were made up of layers, but there was no specific table class. In the new MapXtreme 2004 object model, a table is the central object used for accessing data. The Session.Catalog is used to open and enumerate tables. Layers can reference tables, but all table specific methods were moved from Layer to table. Also, Searching is done on tables and not layers.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
45
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 4: Understanding the MapXtreme 2004 Architecture
Thematics that modify styles, such as ranged themes and individual value themes, no longer use their own layer. In the previous models such a theme occupied a separate layer and worked independently of other layers of a map. Object themes still retain their own layer and can now be displayed in any way you choose, independent of the original map objects on which the theme was based.
Geometry has been changed to be a hierarchical model with much deeper access to properties of the objects. Styles are also represented in a hierarchy.
A larger quantity of map tools have been added for you to use. Their extensibility and functionality has been enhanced to make it much easier to develop customized tools. There are also tools for use in web applications that are also extensible.
For web applications, the MapXBroker and MapXServer are no longer needed. Instead
MapXtreme 2004 uses standard COM+ to pool the Session object.
Application state is managed via serialization and the ASP.NET state server. See
for more details about state management and serialization.
Namespaces
The MapXtreme 2004 Object Model is made up of many namespaces. A .NET namespace is an object hierarchy that differentiates specific classes, methods, and properties from others with the same name. By utilizing namespaces, developers can avoid collisions between names of objects and their methods and properties. The list below contains several of the namespaces implemented in the current version of the MapXtreme 2004 Object Model. A broad overview of each namespace is included in the following sections. Each description contains a reference to the part of this manual that contains detailed information about it and its use.
MapInfo.Data Namespace
The MapInfo.Data namespace contains the classes and interfaces that implement the MapInfo
Data Provider. The new object model has several different classes to access data. Depending on the format your data is stored there are specific classes to use to access it. We are now implementing ADO.NET access to any data that is contained in formats not covered by any other class. For more detail on the Data namespace, see
Chapter 9: Accessing Data from a DBMS
MapInfo.Data.Find Namespace
The MapInfo.Data.Find namespace contains the classes used for searching for data. The namespace facilitates the search for an object by specifying a mappable table and column (it must be indexed) on which to perform the search. For more detail on the Data.Find namespace, see
MapInfo.Engine Namespace
The MapInfo.Engine namespace contains all classes directly related to the core functionality that drives all applications based on MapXtreme 2004. This includes the core Session class which is the starting point for all MapXtreme 2004 applications. For more detail on the Engine namespace, see
Chapter 5: Working with Core MapXtreme 2004 Classes
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
46
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 4: Understanding the MapXtreme 2004 Architecture
MapInfo.Geometry Namespace
The MapInfo.Geometry namespace is an extensible hierarchy based on OGC (Open GIS
Consortium) standards, coordinate system interoperability, and object processing. The
MapInfo.Geometry namespace contains classes, interfaces, and enumerations for creating and editing Geometry objects. For more detail on the Geometry namespace, see
MapInfo.Mapping Namespace
The MapInfo.Mapping namespace contains classes, interfaces, and enumerations for creating, displaying, and exporting maps, layers, modifiers, and labels. For more detail on the Mapping namespace, see
Chapter 6: Adding Mapping Capability to your Applications
MapInfo.Mapping.Legends Namespace
The MapInfo.Mapping.Legends namespace contains classes, interfaces, and enumerations for creating and displaying of Cartographic and Thematic Legends. For more detail on the
Mapping.Legends namespace, see
Chapter 6: Adding Mapping Capability to your
Chapter 11: Using Themes and Legends
MapInfo.Mapping.Thematics Namespace
The MapInfo.Mapping.Thematics namespace contains classes that implement themes as styles of layers and as layers themselves. Themes can be applied to Modifier themes to change the style, while object themes add a new layer. All themes implement the ITheme interface. For more detail on the Mapping.Thematics namespace, see
MapInfo.Persistence Namespace
The MapInfo.Persistence namespace contains classes that support the reading and writing of
XML-based workspaces to enable the saving and retrieval of mapping workspaces.
MapInfo.Raster Namespace
The MapInfo.Raster namespace exposes the full functionality of MapInfo’s C/C++ Raster and
Grid APIs. Raster images can be opened for querying using MapInfo.Raster.RasterRead. Grid images can be opened for querying using MapInfo.Raster.GridRead. Hillshading can be added to existing grids using MapInfo.Raster.HillshadeWrite. Related classes include
MapInfo.Raster.RasterInfo, MapInfo.Raster.GridInfo, MapInfo.Styles.RasterStyle, and
MapInfo.Styles.GridStyle. For more detail on the Raster namespace, see
Working with Rasters and Grids
.
MapInfo.Styles Namespace
The MapInfo.Styles namespace highlights the new Styles object model. The Styles class is the base class of all styles. For more detail on the Styles namespace, see
Chapter 16: Stylizing your Maps
.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
47
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 4: Understanding the MapXtreme 2004 Architecture
MapInfo.Tools Namespace
The MapInfo.Tools namespace contains classes for creating and implementing many types of tools to use in your map. For more detail on the Tools namespace, see
MapInfo.Geocoding Namespace
The MapInfo.Geocoding namespace contains the classes, interfaces and enumerations that define the MapXtreme 2004 client for geocoding. Geocoding using either the MapInfo geocoding server or the MapInfo Location Utility service is supported. The availability and the
URL of a running geocoding server or Location Utility service is required to perform geocoding.
The interface of both clients is similar as they both use the same classes for geocode requests, constraints, responses, result codes, and input and candidate addresses.
MapInfo.Routing Namespace
The MapInfo.Routing namespace contains classes, interfaces, and enumerations which comprise the .NET client to Routing. The client supports both point-to-point and multi-point routing optimized for shortest time or shortest distance. Routing using either the MapInfo routing server or another routing service is supported. The ability to avoid certain points is also available. Routing results can include step by step directions and/or a route geometry which can be displayed on a map.
MapInfo.Web Namespace
The MapInfo.Web namespace provides support for using Visual Studio .NET templates for a
MapXtreme ASP.NET application.There are MapControl design-time enhancements available from this namespace. For more detail on the Web namespaces, see
Chapter 12: Working with the Web-Specific Classes
.
MapInfo.Windows.Dialogs Namespace
This namespace contains classes that implement various dialog boxes and dialog box components to be used in Windows applications. For more detail about the Windows.Dialogs namespace, see
Chapter 15: Dialogs and Controls for Desktop Applications
.
MapInfo.Windows.Controls Namespace
This namespace contains classes that implement various windows controls and their requisite components for use with developing forms in Windows applications. For more detail on the
Windows.Controls namespace, see
Chapter 15: Dialogs and Controls for Desktop
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
48
MapXtreme2004_DevGuide_A4.pdf
Working with Core
MapXtreme 2004
Classes
5
The MapInfo.Engine namespace contains the interfaces and classes that relate directly to the core functionality that drives all applications based on MapXtreme 2004. This includes the core ISession interface which is the starting point for all MapXtreme 2004 applications. Features in this namespace include a Feature object, Styles Repositories, and Table opening SearchPaths and Named
Connections. Other types in the namespace are supporting classes, delegates, structures, and enumerations for Selections, Collections and Resources.
In this chapter:
!
!
!
!
Developer Guide
ISession Interface
Chapter 5: Working with Core MapXtreme 2004 Classes
The ISession interface is the starting point for all MapXtreme 2004-based applications. It manages the initialization of resources needed for a MapXtreme 2004 application. As illustrated in the diagram, the ISession interface also provides access to other important objects such as Data.Catalog, Mapping.MapFactory, Geometry.CoordSysFactory,
Engine.Selections, and others.
The Session class provides access to the ISession object. To access the session, call the
Session.Current() method. Each thread in your process has an ISession object available.
There can be only one session per thread and the session cannot be shared by multiple threads.
Session Management on the Desktop
To access the session object on a desktop application all you need to do is call Current(). Do not call Dispose(). The Dispose() method is automatically called during the application shutdown or when the AppDomain using MapXtreme 2004 is unloaded.
Session Management on ASP.NET
The WebSessionActivator class manages the lifetime of the session object for each Web client request. This class is an IHttpModule and has to be registered in your Web.config file (see
Web.config File in Chapter 13 on page 170
for more information) in order for your application
to work properly. If you are using MapXtreme 2004 Web controls, this class is automatically registered at design-time.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
50
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Selection Class
Chapter 5: Working with Core MapXtreme 2004 Classes
A Selection is a collection of IResultSetFeatureCollection objects that holds lists of features.
These features are a subset of rows in a table. They could be property boundaries, street networks, cell tower locations, or natural features such as rivers, to name a few. They are typically drawn with special highlighting when they display in a Map. There can only be one
IResultSetFeatureCollection for a given table in a Selection.
There can be more than one Selection in a Session. The Selections collection contains all of the selections in the application. There is always at least one selection, known as the
DefaultSelection. Each Selection must have a name and unique alias. By default, map selection tools modify the Selection when used. Each tool can be set to use any particular
Selection.
A selection in MapXtreme 2004 is not a copy; it is a reference to an
IResultSetFeatureCollection for a given table in a Selection. If you attempt to modify a
Selection after you have closed the table that you are working with, the reference to the
IResultSetFeatureCollection will be invalid, causing an exception.
Features can be selected using tools or through search methods. For a discussion of the different selection tools that you can use when building a Windows Forms application, see
. For selection Web controls and tools, see
Specific Classes in Chapter 12 on page 149
Features can be selected through search methods from the MapInfo.Data.Catalog class which returns IResultSetFeatureCollection collections. A Selection object can be passed into a search, which can be used to populate or change a Selection.
Features can also be selected via the ExecuteFeatureCollection method from the
Data.MICommand class. In this case, you would execute SQL commands against the MapInfo
Data Provider.
For more information on features, tables, the Catalog and MICommand, see
.
Code Sample
This example demonstrates how to see if there are any objects selected from a table.
ISession session = MapInfo.Engine.Session.Current;
Table tableEurope = session.Catalog["Europe"];
// Get fc for selection on Europe.
IResultSetFeatureCollection fc = session.Selections.DefaultSelection[tableEurope]; int nCount=0; if (fc != null)
{ nCount = fc.Count;
}
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
51
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 5: Working with Core MapXtreme 2004 Classes
Using Selection Properties
The Selection class provides you with a number of properties to use. These properties are sued to set the (required) name and alias. To determine whether selection markings are visible or editable, use the Visible or Editable property, respectively.
Note:
If the Editable property is set to true, that table that you are working with must also be editable.
The Style property indicates the Selection's style and returns a copy of the Selection's composite style. Since a copy is returned, it cannot be modified. Styles are discussed in
Chapter 16: Stylizing your Maps
Selection Highlighting and Exporting
Selections are typically drawn on the map with special highlighting, to distinguish these features from surrounding non-selected features. The highlighting is controlled by the
Mapping.FeatureViewer.DrawSelections property.When this property is set to true, they are drawn with selection highlighting, provided they are drawn by a visible layer.
Similarly, the MapExport.ExportSelection property, can be used to control whether the selections are drawn into the exported image.
SelectionChangedEvent
A delegate is attached to the SelectionChangedEvent in order to receive notification that this selection has changed. For example, if a record is added, the SelectionChangedEvent is fired.
For a discussion of events fired when working with MapXtreme 2004 tools, see
Event Arguments
The Engine namespace contains various event argument classes that provide data for events.
Refer to the online help for more information. Some of the event argument classes include:
•
CollectionCancelableEventArgs – Provides data for a collection event that can be cancelled.
•
CollectionEventArgs – Provides data for a collection event.
•
NodeSelectionChangedEventArgs – Fires these event arguments when the node selection changes.
•
SelectionChangedEventArgs – Other objects can attach delegates to this event to get notified when a selection changes.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
52
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Exceptions
Chapter 5: Working with Core MapXtreme 2004 Classes
The Engine namespace contains various exception classes. Refer to the online help for more information. Some of the exception classes include:
•
CoreEngineException
•
ResourceNotFoundException – Throws exception when the requested object is not found in the Resource table.
•
ResourceTypeMismatchException – The exception that is thrown when object read from Resources was not of the expected type.
•
TimeoutException – The exception is thrown on Current timeout while waiting for a pooled ISession to become available.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
53
MapXtreme2004_DevGuide_A4.pdf
Adding Mapping
Capability to your
Applications
6
We use the MapInfo.Mapping namespaces to add mapping functionality to your application. This chapter explains how to use the Mapping namespaces to enhance your mapping application.
In this chapter:
!
!
!
!
!
!
Developer Guide Chapter 6: Adding Mapping Capability to your Applications
Introduction to the Mapping Namespace
The MapInfo.Mapping namespace contains classes, interfaces, and enumerations for creating, displaying, and exporting maps, layers, modifiers, thematics, legends, and labels.
The Map class is the top level object for a map in a desktop application. Each Map object can contain exactly one map. Each Map has one Adornment collection and one Layer collection.
When developing a web application a Map gets attached to a MapExport object in order to export that map image to a bitmap or stream.
As described in
Layers in Chapter 3 on page 37
, a map is basically a set of layers piled on top
of each other. Using the Mapping namespace classes, an application can be designed to manipulate those layers as needed.
Base Mapping Classes
This section discusses the base map classes in use in the MapInfo.Mapping namespace. The diagram below shows a UML representation of the Map hierarchy.
MapExport
The MapExport class is used to export a Map to an image. MapExport supports several different image formats including: WMF, EMF, BMP, WBMP, GIF, J2K, JPG, PNG, PSD, TIFF,
TIFFCymk, and TIFFLzw. The properties of this class specify each aspect of the image, such as BorderPen, ExportSize, Format, etc.
Example use of MapExport
using MapInfo.Data; using MapInfo.Mapping;
MapExport mapExport = new MapExport(null);
Map map = MapExport.Map;
Table table = MIConnection.Catalog.OpenTable("usa.tab");
FeatureLayer layer = new FeatureLayer(table); map.Layers.Add(layer); mapExport.ExportSize = new ExportSize(4, 3, PaperUnit.Inch, 96); mapExport.Format = ExportFormat.Bmp; mapExport.Export("SampleMap.bmp");
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
55
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 6: Adding Mapping Capability to your Applications
This example creates a MapExport object and gets the map reference from it. Then a table is opened, a FeatureLayer is created based on the table and then added to the map. The size of the map export is set to 4 by 3 inches and the resolution is set to 96 dpi. Finally the map is exported to the file SampleMap.bmp in the proper format. Note that the line that specifies the format is optional as Bmp is the default format.
Map
The Map class contains everything that you can put in a map. A Map object is placed in a
MapControl object for a desktop application or attached to a MapExport object for a web application.
A Map has the following properties:
•
Bounds
•
Center
•
Zoom
•
Scale
•
Size
•
Rotation
•
DisplayTransform
•
DisplayCoordSys
Each Map has a Layers collection, which holds all the layers that comprise the map (see
), and a single Adornment collection, which contains all of the map’s
adornments. Adornments include Legends, Titles, and Scalebars (see
).
MapFactory
The MapFactory class contains the objects used to create maps from Geosets, workspaces, and lists of tables. MapFactory also functions as a container of, and tracks, the collection of all maps created in a particular session.
Example use of MapFactory
using System.Drawing; using MapInfo.Mapping;
System.Drawing.Size size = new System.Drawing.Size(200,300);
Map map = session.MapFactory.CreateEmptyMap(size);
The above example creates an empty map 200 by 300 pixels in size using the
CreateEmptyMap method of MapFactory.
MapLoader
The MapLoader class provides a mechanism to load the layers of a map from Geoset files,
XML Workspace files, or TAB files. For each type of map to load, there is a subclass of
MapLoader that is used to load the map. These subclasses include MapGeosetLoader,
MapWorkspaceLoader, and MapTableLoader.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
56
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 6: Adding Mapping Capability to your Applications
MapViewList, MapView
These classes contain the objects that help to maintain a list of the previous and next views for a Map. Use the MapViewList class as a convenience to step through your stack of map views, displaying them with the MapView class which provides the specifics (Name, Center, and
Zoom) of each map view.
MapControl
The MapControl class contains the objects that allow the user to visualize a map on a screen.
Add a MapControl to a Windows Form to view a map. A MapControl also holds the MapTools collection.
Note:
The MapControl class is in the MapInfo.Windows.Controls namespace.
Layers
The following section discusses the Layers objects and classes. The diagram below is a UML representation of the Layers hierarchy.
FeatureLayer
A FeatureLayer is a layer that displays Features from a Table. FeatureLayers For example, a layer of region objects representing world countries is a FeatureLayer. FeatureLayers can be native .TAB data, remote RDB, seamless, or raster data.
Layers
Each map has a collection of FeatureLayers represented by the Layers class. The order in the collection is the order in which the layers are drawn. Methods in the collection class include
Add, Insert, Move, and Delete. The Layers collection is derived from the LayersBase class. The best way to enumerate through the layers is to use a Layer filter.
In order to change a layer it first needs to be made editable. This can be done changing its setting in the LayerControl or programmatically by changing its EditMode property. Once a layer is editable, features in that layer can be moved, resized, or deleted.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
57
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 6: Adding Mapping Capability to your Applications
Note:
Any edits made to a particular layer take effect immediately so exercise caution when selecting features in an editable layer.
To implement a filter use the MapLayerFilterFactory class. This class allows you to create a filter from a set of stock filters such as layer types or all visible layers. To create your own filter write a class that implements the interface, IMapLayerFilter.
MapLayer
The MapLayer class is the base class of any layer. This class implements the IMapLayer interface. Properties include Enabled, VisibleZoomRange, Name, and Alias. Use this class to access generic layer properties.
UserDrawLayer
The UserDrawLayer is an abstract class that allows you to override the draw method to draw your own layer.
ObjectThemeLayer
The ObjectThemeLayer class contains one of three different types of themes (pie chart, bar chart, and graduated symbol). This layer behaves just like other layers and can be grouped, have visibility set, etc.
GroupLayer
This is class represents a group of layers that are moved and turned on/off in unison. A
GroupLayer is a LayersBase collection combined with an IMapLayer. This object also supports the ability to do AnimationLayers, by turning off its backing store.
Layer Filters
The IMapLayersFilter and IMapLayersFilterFactory interfaces provide support for layer enumeration.
VisibilityConstraint
The VisibilityConstraint is an interface which determines whether a particular object is visible or not. This interface is implemented by FeatureLayer, ObjectThemeLayer, and LabelSource.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
58
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Labels
Chapter 6: Adding Mapping Capability to your Applications
The following section discusses the Labels objects and classes. The diagram below is a UML representation of the Labels hierarchy.
LabelLayer
The LabelLayer class allows the separate ordering of labels and layers. A LabelLayer is a kind of MapLayer and behaves as such. This similarity to MapLayer supports the placement of a
LabelLayer anywhere you can put a MapLayer allowing for relative positioning of the Labels compared to the other layers in the map. Each LabelLayer is made up of LayerSources and acts as a collection of those objects.
LabelSource
The LabelSource class graphically displays geographies as labels based on a data source and rules that define how the source is labeled. The LabelSource is added to a LabelLayer on the
Map so that it is drawn. The LabelLayer provides positioning within the Map as well as the rules that govern the interaction with other LabelSources. To use this class, specify a table from where to get the data (MITable), an expression which defines the label text, and other default label properties accordingly.
LabelModifier
The LabelModifier class is used to modify the default properties used to make a label. When the LabelLayer generates labels for each LabelSource in its Sources collection, it first uses the
DefaultLabelProperties to generate each label. It then uses each visible LabelModifier in the
Modifiers collection.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
59
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 6: Adding Mapping Capability to your Applications
ILabelSourceFilter
This interface allows you to enumerate through the collection of LabelSource objects in a
LabelLayer filtering on specific rules. You can also implement this interface to define your own filtering rules.
LabelProperties
This class has label property information, such as style, positioning, etc. It supports the representation of sparse label properties. This is very useful when using a LabelModifier to modify only a portion of the label properties. This class also allows you to set prioritization and improved placement of labels.
Example Label Code
The following example demonstrates the use of the classes associated with Labels.
using MapInfo.Data; using MapInfo.Mapping; table = session.MIConnection.Catalog.Opentable(datadir + "world.tab"); layer = new FeatureLayer(table); map.Layers.Add(layer); labelLayer = new LabelLayer("Label Layer", "Label Layer"); labelLayer.Sources.Append(new LabelSource(table); map.Layers.Add(labelLayer);
LabelSource source = labelLayer.Sources[0]; source.AllowDuplicates = false; source.AllowOverlap = true; source.PartialObjects = true; source.Maximum = 50; source.DefaultLabelProperties.Along = LabelAlong.MultiSegments; source.DefaultLabelProperties.Angle = 33.0; source.DefaultLabelProperties.CaptionExpression = "Capital"; source.DefaultLabelProperties.PriorityExpression = "Pop_1994"; source.DefaultLabelProperties.Offset = 7; source.DefaultLabelProperties.Position = TextPosition.BottomRight;
This sample does the following. First a table is opened and a feature layer is created based on that table. Then that feature layer is add to the map. A new label layer is created and the source is set for that layer to be based on the same table as in the feature layer. that label source is added to the label layer and then the label layer is added to the map’s layer collection. The labeling rules are set to allow no duplicates, allow for overlaps, and label partial objects. Lastly, the default label properties are set.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
60
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Adornments
Chapter 6: Adding Mapping Capability to your Applications
The Adornments class is an unordered collection of a map’s adornments. An adornment is either a Legend, a Title, a Scalebar, or some other user-defined object. Each map contains a single Adornments Collection. Each adornment belongs to a single AdornmentControl.
Legends
Legends are for used in conjunction with themes. See
for more information about themes. Legends are created using the LegendFactory
class off of the Session object. A Legend consists of one or more legend frames. Each frame is either a ThemeLegendFrame or a CartographicLegendFrame. Both kind of LegendFrames are created by using the LegendFrameFactory class from the created Legend object. For manipulation and customization of legends and their frames, use classes in the
MapInfo.Mapping.Legends namespace. Classes in this namespace include:
CartographicLegendFrame, ThemeLegendFrame, LegendFormat, LegendControl, and others.
Example Legend Code
The following code segment demonstrates the creation and manipulation of a Legend.
using MapInfo.Data; using MapInfo.Mapping; using Mapinfo.Mapping.Thematics;
Map map = mapControl1.Map;
Table table =
MapInfo.Engine.Session.Current.Catalog.OpenTable
(_datadir + "world.tab");
FeatureLayer layer = new FeatureLayer(table); map.Layers.Add(layer);
//create a bar theme
BarTheme theme = new
BarTheme(map,layer.Table,"Pop_0_14","Pop_15_64","Pop_65Plus");
ObjectThemeLayer themeLayer = new ObjectThemeLayer
("World Pop", null, theme); map.Layers.Add(themeLayer);
// create the legend
ThemeLegendFrame frame =
LegendFrameFactory.CreateThemeLegendFrame(theme);
Legend legend = map.Legends.CreateLegend(frame.Size); legend.Frames.Append(frame);
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
61
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Feature Style Modifiers
Chapter 6: Adding Mapping Capability to your Applications
Feature style modifiers allow a way of changing/modifying the style of a Feature before it is drawn. These classes use the sparse attribute aspect of CompositeStyle object to only modify the part of the style in which you are interested. Range, Individual Value, and Dot Density themes are style modifiers. Thematics are covered in detail in
. The diagram below shows a UML representation of the Modifier and thematics
hierarchy.
FeatureStyleModifiers
The FeatureStyleModifiers class is an ordered collection of FeatureStyleModifier objects contained within each FeatureLayer. Each modifier in the collection is called in order before a feature’s geometry is drawn.
FeatureStyleModifier
This is an abstract base class from which all modifiers must derive. The IndividualValue,
Ranged, and DotDensity themes are all FeatureStyleModifier objects. You can create your own class that derives from FeatureStyleModifier and override the Modify() method.
FeatureOverrideStyleModifier
The FeatureStyleOverrideStyleModifier is a simple kind of FeatureStyleModifier. This class provides style override functionality at the Layer level. The FeatureStyleOverrideStyleModifier has a composite style and implements the IvisibilityConstraint. This is similar to functionality found in MapX and MapInfo Professional.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
62
MapXtreme2004_DevGuide_A4.pdf
Map Geometry Objects
7
The Geometry namespace handles all geometric objects and coordinate systems in a mapping application. This chapter details the use of the MapInfo.Geometry namespace to create and manipulate these objects.
In this chapter:
!
!
!
!
Developer Guide Chapter 7: Map Geometry Objects
Introduction to the MapInfo.Geometry Namespace
The MapInfo.Geometry namespace is used for creating and manipulating geometry objects, and the coordinate systems in which they are used. Geometry objects are used in maps to represent single points, such as cities (represented as point objects), boundary lines, such as county borders (represented by MultiCurve objects), and regions, such as countries or zip code areas (represented by a MultiPolygon object).
The classes, interfaces, and enumerations in the MapInfo.Geometry namespace define the types representing the geometries and coordinate systems used in displaying geographic features on a map. Interfaces allow for creation and editing of the geometry objects. Methods such as Buffer, Combine, Difference, and Intersection provide object processing on single objects or pairs of objects.
Geometries
The Geometry class allows for the creation, editing, and other manipulation of geometry objects. Classes which inherit from the Geometry class and represent types of Geometry objects include Point, MultiPoint, Polygon, MultiPolygon, Curve, CurveSegment, LineString, and Ring. The following legacy classes are also inherited from the Geometry class: Rectangle,
RoundedRectangle, Ellipse, LegacyArc, and LegacyText.
The Geometry class represents the topmost level of the MapInfo Geometry object model. This class is abstract, and cannot be instantiated. All classes that derive from this class contain knowledge concerning their coordinate system. All classes are able to make copies of themselves, and compare themselves to other Geometry objects for equality.
The diagram below shows a UML representation of the new Geometry model.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
64
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 7: Map Geometry Objects
Geometry Objects
All geometry objects in MapXtreme 2004 are created with a specific coordinate system that cannot be changed. If you need to alter the coordinate system of an object you can make a copy of that object in the new coordinate system.
All Geometry objects contain a method for retrieving an interface to an editor that places the object into Edit Mode. Once editing is finished the EditingComplete() method needs to be called to signify that the editing of the object is complete. When the EditingComplete() method is called, the order of the objects contained by the Geometry is reshuffled and all references to them are dropped and need to be re-established in order to access them again.
For example, the user creates a MultiPolygon and then edits the MultiPolygon. If the user inadvertently moves a node of the interior ring to be outside of its containing Polygon the
Polygon is no longer valid. When EditComplete is called, all the contained objects within the
MultiPolygon are reshuffled, fixing the problem.
The geometry objects in the MapXtreme 2004 Object Model are described in the following sections:
FeatureGeometry Objects
The FeatureGeometry class is specifically designed to contain classes that can be placed in tables and that can be parts of Features and FeatureCollections. In order for something to be displayed in a map, it needs to be in a table. FeatureGeometry objects are by definition included in tables. Any object that is a subclass of Geometry and not a subclass of
FeatureGeometry cannot be saved to a table or included as part of a Feature or
FeatureCollection. An exception is thrown, or the program will not compile, if such an operation is attempted. The Geometry class, like the FeatureGeometry class is abstract and cannot be instantiated.
Point
Points are derived from the FeatureGeometry class and represent a single point on a map.
Points can be contained within a MultiPoint collection and then operated upon collectively.
Use the following example code to model the creation of a Point: using MapInfo.Geometry; using Mapinfo.Design.Windows;
CoordSys longLatNad83;
CoordSysFactory coordSysFactory = new CoordSysFactory(); longLatNad83 = coordSysFactory.CreateLongLat
(MapInfo.Geometry.DatumID.NAD83);
DPoint point = new DPoint(0.0, 0.0);
Point pointGeometry = new Point(LongLatNad83, point);
MultiPoint
A MultiPoint contains an unordered, disconnected set of Points and is useful for performing multiple operations on multiple points.
Use the following example code to model the creation of a MultiPoint object: using MapInfo.Geometry;
CoordSys longLatNad83;
CoordSysFactory coordSysFactory = new CoordSysFactory();
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
65
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 7: Map Geometry Objects
longLatNad83=coordSysFactory.CreateLongLat
(MapInfo.Geometry.DatumID.NAD83);
MultiPoint multiPointGeometry = new MultiPoint
(longLatNad83, pointArray); where pointArray
is an array of DPoints.
MultiCurve
The MultiCurve class is derived from the FeatureGeometry class, and contains a possibly disconnected set of Curves. These Curves may interact in many ways; they can be connected or disconnected, and can intersect or overlap each other.
Although the Geometry Object Model supports multiple CurveSegments for each Curve, the current version of the MapInfo engine is limited to having one CurveSegment per Curve that is part of a FeatureGeometry (i.e., MultiCurve). This limitation derives from the current TAB file format, which remains largely unchanged for this version of MapInfo. Hence, the limitation concerns FeatureGeometry objects only.
Upon construction of a MultiCurve where the constructor takes a Curve or Curves which may contain multiple CurveSegments per Curve, the actual Curves contained in the constructed
MultiCurve are altered to always contain only one CurveSegment per Curve. Currently, the only types of CurveSegments that exist are LineStrings. Curves containing multiple LineString
CurveSegments have the LineStrings combined to form one large LineString.
Upon completion of editing (signified by calling EditingComplete(), any Curve which was added to the MultiCurve and contained multiple CurveSegments is altered in a similar manner as noted above to produce Curves containing single CurveSegments.This limitation, of Curves contained in MultiCurves always containing only a single CurveSegment, should be removed in future versions of MapInfo as new types of CurveSegments are introduced (e.g., EllipticalArcs,
CircularArcs, and Splines), and the TAB file format is altered. Also, during construction and on completion of editing, any empty Curves are automatically removed from the MultiCurve.
The order of the Curves in a MultiCurve may be altered during construction, as compared to the array of Curves passed to the constructor, and upon completion of editing. Due to this, plus the removal of empty Curves, and limitations in the current implementation, any references to
Curves contained in a MultiCurve prior to and during editing may no longer be valid after editing is completed (i.e., after EditingComplete() is called). If these objects are referenced, they throw an ObjectDisposedException. After editing, the parts of a FeatureGeometry should be reacquired to obtain a valid reference.
Line objects made up of two points that exist in MapInfo TAB files become MultiCurve
FeatureGeometry objects. They can be detected as two-point Lines by using the IsLegacyLine property of the MultiCurve: using MapInfo.Geometry;
MultiCurve multiCurve =
<... FeatureGeometry obtained from TAB file...>; if(multiCurve.IsLegacyLine){
...}
A Line is created by using the CreateLine method in the MultiCurve class. The following code is an example using this method: using MapInfo.Geometry;
MultiCurve multiCurve = new MultiCurve(longLatNad83);
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
66
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 7: Map Geometry Objects
multiCurve = MapInfo.Geometry.MultiCurve.CreateLine
(longLatNad83, dpoints[0], dpoints[1]);
Example of Creating and Editing a MultiCurve
using MapInfo.Geometry;
// construct a MultiCurve
MultiCurve multiCurve = new MultiCurve(.....);
// get a reference to one of the Curves
Curve curve1 = multiCurve[0];
// put MultiCurve into Edit Mode
IMultiCurveEdit multiCurveEditor = multiCurve.MultiCurveEditor();
// add new empty curve
Curve newCurve = multiCurveEditor.CreateCurve(true); multiCurve.EditingComplete();
// at this point, newCurve is removed from multiCurve, because it is
// empty. curve1 is also no longer a valid reference
// It still exists in the Curve and can be retrieved again.
LineStrings
A LineString is a directed collection of sequential points that are connected in a linear manner.
Any two consecutive points in the LineString are connected by a straight line. LineStrings can be part of Curves or Rings, or they can exist as a stand-alone Geometry. LineStrings that are part of Curves or Rings inherit the coordinate system of their container. Stand-alone LineStrings can be empty. A LineString that is contained in a Curve or Ring that is not in Edit Mode cannot be empty, and must contain at least two points.
Use the following example code to model creating and editing a LineString.
using MapInfo.Geometry; longLatNad83 = coordSysFactory.CreateLongLat
(MapInfo.Geometry.DatumID.NAD83);
LineString lineString = new LineString(longLatNad83, dPoints);
ILineStringEdit edit = lineString.LineStringEditor; edit.Append(new DPoint(-75, 43)); lineString.EditingComplete(); dPoints
is a previously-declared array of Points.
Rectangle
A Rectangle Geometry contains two points representing the lower left hand and upper right hand corners of the Rectangle. The other two points are implied. Rectangles are always axis aligned, and always appear to be rectangular in shape, regardless of the coordinate system, and are not projected. They do not contain any warping that may be represented by the coordinate system.
Use the following example code to model the creation of a Rectangle: using MapInfo.Geometry;
CoordSys longLatNad83; longLatNad83 = coordSysFactory.CreateLongLat
(MapInfo.Geometry.DatumID.NAD83);
DRect rect = new DRect(-40.0, 60, -35.0, 65.0); coordSysFactory = new CoordSysFactory(); longLatNad83 = coordSysFactory.CreateLongLat
(MapInfo.Geometry.DatumID.NAD83);
Rectangle rectangle = new Rectangle(longLatNad83, rect);
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
67
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 7: Map Geometry Objects
RoundedRectangle
A Rounded Rectangle behaves exactly like a Rectangle but is displayed with the corners appearing rounded as a display-time only feature. The corners display as quarter circles and the radius of the circle is controlled by the CornerRadius parameter.
Because RoundedRectangle objects, like rectangle objects, are defined by two points and always display axis-aligned and unprojected, they are designed to be used primarily for cosmetic display purposes. While many operations are available using Rectangle objects (e.g.,
Combine), internally, a MultiPolygon copy of the Rectangle is used for these operations. The resulting MultiPolygon contains 5 points (with the first and last points being identical), and are effected by the coordinate system. In some instances, the converted Rectangle may no longer appear rectangular. Use the CreateMultiPolygon method to convert a RoundedRectangle to a
FeatureGeometry object.
Use the following example code to model the creation of a RoundedRectangle: using MapInfo.Geometry;
DRect rect = new DRect(-40.0, 60, -35.0, 65.0); double radius = 20;
DistanceUnit unit = DistanceUnit.Mile;
DistanceType type = DistanceType.Spherical; coordSysFactory = new CoordSysFactory(); longLatNad83 = coordSysFactory.CreateLongLat
(MapInfo.Geometry.DatumID.NAD83);
RoundedRectangle roundedRectangle = new RoundedRectangle
(longLatNad83, rect, radius, unit, type);
Ellipse
The Ellipse is inscribed in an axis-aligned rectangle defined by a DRect. The DRect is defined by two points, the opposite corners of a rectangle, with the other two corners of the rectangle implied. The Ellipse displays as if it were unprojected, regardless of the coordinate system, and any skew that may be represented by the coordinate system.
Because Ellipse objects are defined by two points and always display axis-aligned and unprojected, they are designed to be used primarily for cosmetic display purposes. While many operations are available using Ellipse objects, internally, a MultiPolygon copy of the Ellipse is used for these operations. The resulting MultiPolygon is effected by the coordinate system and in some cases may no longer appear as a perfect ellipse.
Use the following example code to model the creation of an Ellipse: using MapInfo.Geometry; using MapInfo.Design.Windows;
CoordSys longLatNad83; coordSysFactory = new CoordSysFactory(); longLatNad83 = coordSysFactory.CreateLongLat
(MapInfo.Geometry.DatumID.NAD83);
DPoint center = new DPoint(-20.0, 20.0); double xRadius = 100; double yRadius = 135;
DistanceUnit unit = DistanceUnit.Mile;
Ellipse ellipse = new Ellipse(longLatNad83, center, xRadius, yRadius, unit, DistanceType.Spherical);
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
68
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 7: Map Geometry Objects
LegacyArc
The LegacyArc object is a portion of an Ellipse and is defined by a DRect, a start angle, and an end angle. The Ellipse is constructed to be inscribed in the rectangle defined by the DRect. The rectangle, in which the Ellipse is inscribed, is axis-aligned and is always rectangular regardless of the coordinate system used. The angles are measured in degrees with zero being along the positive X-axis and positive angles being in the counterclockwise direction. The angles are only stored to a tenth of a degree resolution with values between 0.0 and 360.0.
Because LegacyArc objects are defined by two points (for the DRect) and angles, and are always displayed axis aligned, they are designed to be used primarily for cosmetic display purposes. While many operations are available using LegacyArc objects, internally, a
MultiCurve copy of the LegacyArc is used for these operations. This can sometimes lead to unexpected results.
Use the following example code to model the creation of a LegacyArc: using MapInfo.Geometry;
CoordSys longLatNad83; coordSysFactory = new CoordSysFactory(); longLatNad83 = coordSysFactory.CreateLongLat
(MapInfo.Geometry.DatumID.NAD83);
DRect rect = new DRect(-40.0, 60, -35.0, 65.0);
LegacyArc arc = new LegacyArc(longLatNad83, rect, 30.0, 60.0);
LegacyText
The LegacyText object is the MapInfo Professional equivalent of a text object. If a given database does not support Text the LegacyText object can be lost when using that format.
LegacyText objects are placed within a geographically-sized rectangle with a lower-left anchor point specified. The point-size of the text is based upon what fits best within the rectangle.
LegacyText objects do not fit nicely into the Geometry model. Several methods available on the
Geometry FeatureGeometry classes, such as Combine, make no sense for LegacyText and will throw a NotSupportedException. Text objects do exist in MapInfo native TAB files in the
Geometry column. The LegacyText class provides a way to access these objects. Refer to online reference for specific behaviors of LegacyText objects.
Geometry Objects
Geometry objects that are not also FeatureGeometry objects need to be converted to a suitable
FeatureGeometry object to be displayed on a map. Most FeatureGeometry classes contain constructors that take appropriate Geometry objects and create new FeatureGeometry objects: using MapInfo.Geometry;
Curve curve = new Curve(csys, lineString);
MultiCurve multiCurve = new MultiCurve(curve.CoordSys, curve);
The code above creates the Curve using parameters defined elsewhere in the code of a
CoordSys ( csys
) and a LineString ( lineString
). A new MultiCurve is then created using the
CoordSys property of the Curve and the Curve itself.
In the example above, as in all FeatureGeometries created from objects, a copy of the original object is created because the reference cannot be shared.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
69
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 7: Map Geometry Objects
Curve
The Curve class inherits from the CurveSegmentList class, and represents a contiguous linear
Geometry. Curves contain a collection of CurveSegments that must remain contiguous. This class is included in the model to allow for future expansion and is part of the OGC standards.
Use the following example code to model the creation of a Curve: using MapInfo.Geometry;
DPoint[] points = new DPoint[4]; points[0]= new DPoint(-88.135215,43.998892); points[1]= new DPoint(-104.875119,43.998892); points[2]= new DPoint(-120.242895,47.048364); points[3]= new DPoint(-89.135215 46.998892);
LineString lineString = new LineString(csys, points);
Curve curve = new Curve(csys, lineString);
CurveSegments
At present a CurveSegment can only be a LineString. The class is designed to expand in future iterations of the product to include Spline, CircularArc, and EllipticalArc CurveSegments.
Curves and Rings are comprised of CurveSegments.
Rings
A Ring is a collection of CurveSegments which must remain contiguous and closed.
Use the following example code to model the creation of a Ring: using MapInfo.Geometry; dPoints = new DPoint[102]; dPoints[0] = new DPoint(-109.171279,49.214879); dPoints[1] = new DPoint(-109.169283,49.241794);
...
dPoints[101] = new DPoint(-109.171279,49.214879);
Ring newRing = new Ring(longLatNad83, CurveSegmentType.Linear, dPoints);
Polygon
A Polygon is an object made up of Rings. A polygon must have at least a single Ring which defines the exterior boundary of the Polygon. Other Rings can be included inside which then define holes in the Polygon. Once a Ring is placed inside of another Ring the object becomes a
MultiPolygon.
Use the following example code to model the creation of a Polygon.
using MapInfo.Geometry;
DPoint[][] points = new DPoint[1][]; points[0] = polyPointArrays[0];
Polygon polygon = new Polygon
(longLatNad83, CurveSegmentType.Linear, polyPointArrays[0]);
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
70
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Including Your FeatureGeometry in a Map
Chapter 7: Map Geometry Objects
Once a geometry is created you then need to add it to a map, allowing you to display it, select it, label it, or perform any other map-related operations on it.
The following example code demonstrates how to do this: using MapInfo.Geometry; using MapInfo.Mapping; using MapInfo.Data; using MapInfo.Styles;
/// <summary>
/// Creates a temporary table, adds a Point feature, and displays
/// it on a map. This example uses wldcty25 as a template, so you'll
/// need to have world.gst open in a map control.
/// NOTE X and Y positions depend on the coordinate system!
/// </summary>
/// <param name="x">X position</param>
/// <param name="y">Y position</param> private void showPointOnMap(double x, double y)
{
Map map = mapControl1.Map;
//uses wldcty25 as a template
Table table =
MapInfo.Engine.Session.Current.Catalog.GetTable("wldcty25");
// create a temp table and add a featurelayer for it
CoordSys coordSys = map.GetDisplayCoordSys();
TableInfoMemTable tableInfo = new TableInfoMemTable("temp"); tableInfo.Temporary = true;
// add geometry column
Column column;
// specify coordsys for object column column = new GeometryColumn(coordSys); column.Alias = "MI_Geometry"; column.DataType = MIDbType.FeatureGeometry; tableInfo.Columns.Add(column);
// add style column column = new Column(); column.Alias = "MI_Style"; column.DataType = MIDbType.Style; tableInfo.Columns.Add(column);
Table pointTable = Session.Current.Catalog.CreateTable(tableInfo);
// Set the location and display style of the point
FeatureGeometry geometry = new MapInfo.Geometry.Point (coordSys, x, y);
SimpleVectorPointStyle vStyle = new SimpleVectorPointStyle
(37, System.Drawing.Color.Red, 14);
CompositeStyle cStyle = new MapInfo.Styles.CompositeStyle(vStyle);
//Update the table with the location and style of the new feature
MICommand cmd = miConnection.CreateCommand(); cmd.Parameters.Add("geometry",MIDbType.FeatureGeometry); cmd.Parameters.Add("style",MIDbType.Style); cmd.CommandText = "Insert Into temp (MI_Geometry,MI_Style) values (geometry,style)"; cmd.Prepare(); cmd.Parameters[0].Value = geometry; cmd.Parameters[1].Value = cStyle;
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
71
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 7: Map Geometry Objects
int nchanged = cmd.ExecuteNonQuery(); cmd.Dispose();
//add the table to the map map.Layers.Add(new MapInfo.Mapping.FeatureLayer(pointTable));
}
Coordinate Systems
Coordinate systems describe the domain in which a particular object or set of objects reside.
The coordinate system allows for the delineation, in specific terms, of the object or objects being described. The CoordSys classes contain methods, properties and interfaces that allow for the creation, manipulation, and editing of coordinate systems.
When Geometries are created, they are created in a particular coordinate system specified in the creation of the object. Objects cannot change the coordinate system in which they were created. They can only be copied into another coordinate system.
The CoordSys class facilitates the creation and manipulation of coordinate systems.
The Coordsys class uses a new XML version of the projection file
(
MapInfoCoordinateSystemSet.xml
). The CoordSysFactory object contains all registered coordinate systems. You have the ability to load one or more XML files into the
CoordSysFactory object and programmatically register coordinate systems into it as well. This class also allows the user to save the CoordSysFactory to the new XML format.
The CoordSysFactory object contains registered coordinate systems. CoordSys definitions can be registered by loading one or more XML projection files or by using the RegisterCoordSys, or
RegisterCoordSysInfo methods. Create CoordSys objects from the factory, or code-codespace
(EPSG, SRID), PRJ string, MapBasic string, and other Factory creation methods. There are also Military Grid Reference System conversion methods in the CoordSys class.
The following sample code shows the creation of CoordSys objects several different ways: using a MapInfo codespace; through EPSG; as longitude/latitude from a PRJ string; from a
MapBasic string; and through SRID.
using MapInfo.Geometry; using MapInfo.Engine;
// Declare the CoordSysFactory variable
CoordSysFactory cSysFactory = Session.Current.CoordSysFactory;
// Create CoordSys from a mapinfo projection (preferred method)
CoordSys csys = cSysFactory.CreateCoordSys("MapInfo:coordsys 1, 104");
// Create CoordSys from EPSG
CoordSys csys_EPSG = cSysFactory.CreateCoordSys("EPSG:4326");
// Create a Longitude Latitude projection (from a PRJ string)
CoordSys csys_LongLat = cSysFactory.CreateFromPrjString("1, 56");
// Create a CoordSys from a MapBasic string
CoordSys csysMB = cSysFactory.CreateFromMapBasicString(
@"CoordSys Earth Projection 4, 62, ""m"", 0, 90, 90");
// create a CoordSys from an SRID
CoordSys csys_SRID = cSysFactory.CreateCoordSys("SRID:8307");
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
72
MapXtreme2004_DevGuide_A4.pdf
Working with Data
8
The MapInfo.Data namespace contains the classes and interfaces that provide multiple ways of accessing data from a MapXtreme 2004 application.
In this chapter:
!
!
!
!
!
!
!
!
!
!
Developer Guide
Overview of MapInfo.Data Namespace
Chapter 8: Working with Data
The MapInfo.Data namespace contains the classes and interfaces that provide multiple ways of accessing data from a MapXtreme 2004 application. Within this namespace is the MapInfo
ADO.NET data provider with a new MapInfo SQL language for standard querying of databases and tables. The Feature object model is another way to access data that used objects instead of SQL. The Catalog is the starting point for data access, containing methods for managing tables (open, close, create) and searching for data in a variety of ways.
Catalog and Tables
Catalog
CloseAll
CreateTable
OpenTable
Search
SearchForFeature
SearchReader
SearchInfo
ITableEnumerator
ITableFilter
DbmsConnectionCollection
QueryDefinition
IQueryFilter
ISearchResultProcessor
B
Table
Close
AddColumns
InsertFeature
UpdateFeature
DeleteFeature
Pack
TableSessionInfo
Features and Feature Collections
MultiFeatureCollection
IFeatureCollection
Alias
Add
Remove
MultiResultSetFeatureCollection
GmlFeatureCollection
MIGmlFeatureCollection
Table
Feature
Key
Geometry
Style
Columns
IDynamicFeatureCollection
FeatureCollection
ITableFeatureCollection
IResultSetFeatureCollection B
Table Metadata
TableInfo
Alias
TableType
TableInfoAdoNet
TableInfoAscii
TableInfodBase
TableInfoGrid
TableInfoNative
TableInfoMemTable
TableInfoMSAccess
TableInfoRaster
TableInfoResultSet
TableInfoSeamless
TableInfoServer
TableInfoShapefile
TableInfoView
TableInfoWms
Metadata
CacheParameters
SpatialSchema
SpatialSchemaXY
SpatialSchemaPointRef
Columns
Column
Alias
MIDbType
GeometryColumn
CoordSys
Bounds
DefaultView
Current
A
MapInfo ADO.NET Data Provider
MIConnection
Catalog
Open
Close
MICommand
CommandText
Cancel
Dispose
ExecuteReader
ExecuteScrollableReader
ExecuteNonQuery
ExecuteFeatureCollection
Prepare
Parameters
MIDataReader
Read
GetValue
Close
MIScrollableReader
ReadPrevious
Rewind
Unwind
MIParameter
ParameterName
Value
Columns
Tables
The Table class is the basic unit of all data access. Table, Column, and all TAB file metadata information is accessible from a MapInfo Table. Tables may be mappable (contain a column of type FeatureGeometry) or non-mappable. Tables also may be open and accessed without displaying in a map.
Table Aliases
When tables are opened, they can be assigned a name (or alias) which is used while the table is open for referencing the table. For example, the table may be referred to an alias in SQL statements. A table that is opened from a TAB file is assigned a default alias if no alias is specified. The default alias is based upon the name of the TAB file. This property is optional and may be set to null. However, it is good practice to assign an alias.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
74
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 8: Working with Data
Columns
A Column object identifies the properties of a column in a table, feature, or feature collection and specifies the column's name (alias), data type, width (for string and decimal columns), and other properties of the column.
Supported data types include:
Int
Data Type
SmallInt
Double dBaseDecimal
Boolean
String
Date
FeatureGeometry
Binary
Key
CoordSys
Style
Raster
Grid
Wms
Description
Provides a 32-bit signed integer. This maps to the .NET Framework datatype Int32.
Provides a 16-bit signed integer. This maps to the .NET Framework datatype Int16.
A floating point number within the range of -1.79E +308 through 1.79E +308. This maps to Double.
Provides a floating point number which is treated internally the same as a Double.
The dBaseDecimal has a fixed precision and scale when persisted in a table. This is a legacy data type derived, as its name suggests, from the dBase file formats.
This maps to Double.
Provides a boolean value. This maps to Boolean.
Provides a variable-length, null terminated UNICODE string value. This maps to
String.
Provides a date value. This object model currently does not support Time.
Although fields of type MIDbType.Date return/accept DateTime values, the time is ignored. This maps to the .NET Framework datatype DateTime.
Provides a FeatureGeometry. See
Chapter 7: Introduction to the Map-
Provides an array of binary data. This maps to an Array of Byte values.
Provides a key from a table. This is the data type of the Key pseudo column on a
Table.
Provides a coordinate system. This type exists only for the purposes of binding a coordinate system object to an MICommand for functions which require the specification of a coordinate system.
Provides a style from table's style column. This is the data type of the AllStyle object stored in style column on a Table.
Provides a RasterInfo from table's raster column. This is the data type of the RasterInfo object stored in raster column on a Table.
A GridInfo from table's grid column. This is the data type of the GridInfo object stored in grid column on a Table.
Provides a WmsClient from the table's Wms column. This is the data type of the
WmsClient object stored in the Wms column on a Table.
The following sections provide you with MI_Key, MI_Geometry, and MI_Style column information.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
75
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 8: Working with Data
MI_Key
All tables have a pseudo column named MI_Key which return instances of Key. The MI_Key pseudo column is similar in concept to the rowid pseudo column in MapInfo Professional and
MapBasic. Unlike rowid, this column is not a numeric column. A Key instance may converted to or from a string literal.
MI_Geometry
A Geometry column object identifies the properties of a column in a table, feature, or feature collection that contains FeatureGeometry objects and specifies properties such as the coordinate system of the column, the entire bounds of all the geometry objects it contains, etc.
Geometry columns for most table types are given the name “Obj”. To be compatible with previous versions of MapX and MapInfo Professional, the alias “Obj” is resolved to the first
GeometryColumn in the table. Additionally, the alias “MI_Geometry” may also be used for any table to refer to the same column that “Obj” refers to.
MI_Style
Tables with a Geometry column also have a column with the name “MI_Style”, or if not found, from the first column with type MIDbType.Style. This column is used to hold the style information for Geometry objects. This column cannot be updated independently. The Style and
Geometry columns must be updated at the time.
Catalog
The Catalog class holds a list of tables that are currently open in the MapInfo session. Tables are also opened, created and closed from the Catalog. The MapInfo Catalog can be thought of as a single database holding all the tables opened in it, regardless of their actual data source. It initially contains no tables. When a table is opened, an alias (or name) is assigned to the table or provided by the caller. The alias is used to identify the table in queries and other operations.
The Catalog provides facilities for creating new table definitions and enumerating through tables which are currently opened.
The Catalog also contains search methods that can be used to access data in open tables.
Note:
Each MapXtreme 2004 Session manages a single Catalog.
Code Sample
// Catalog is accessible off the Session object
Catalog catalog = session.Catalog;
// Open several tables
Table table = catalog.OpenTable("States.tab"); table.SessionInfo.ReadOnly = true; // Make states ReadOnly table = catalog.OpenTable("world.tab"); table = catalog.OpenTable("worldcap.tab", "World Capitals");
// Enumerate the catalog directly - includes All tables foreach (Table t in catalog)
Console.Out.WriteLine("Table : {0}", t.Alias);
Console.Out.WriteLine();
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
76
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 8: Working with Data
// Now enumerate through only tables that are editable
TableEnumerator tenum = catalog.EnumerateTables(
TableFilterFactory.FilterEditableTables()); while (tenum.MoveNext())
{
Console.Out.WriteLine("Table: {0}",tenum.Current.Alias);
}
Catalog.CloseAll();
Locating Open Tables
To locate open tables, you must enumerate the catalog. This is done by using the methods in the following sections.
Catalog.GetTable
The GetTable method returns the Table object referenced by the TableAlias parameter. This must be a table which has already been opened. If no such table is found (or the table has subsequently been closed), then the method returns null.
Catalog Indexer
Catalog.Item property can be used as an indexer for locating a Table by its Alias. This is functionally equivalent to using the Catalog.GetTable method but generates code that is easier to read. The Alias must specify a table which has already been opened.
TableEnumerators
Table enumerators may be obtained through the various overloaded EnumerateTables methods. A table enumerator may be created with a filter. The filter determines which tables are actually included in the enumeration while the enumerator simply provides the mechanics of enumeration. You can create your own table filters to use in the TableEnumerator. You can also create your own table enumerator by implementing the ITableEnumerator interface.
Code Samples
The Catalog may be enumerated in a variety of ways. The simplest mechanism is to enumerate the catalog directly as follows: foreach (Table tbl in Session.Current.Catalog)
{
...
}
Another option is to use a table enumerator (TableEnumerator) as follows:
ITableEnumerator te = miCatalog.EnumerateTables(TableFilterFactory.FilterEditableTables()); while (te.MoveNext())
{
Table tbl = te.Current;
...
}
Closing a Table
Two methods are available to close tables. Catalog.CloseAll closes all open tables while
Catalog.CloseTable closes a single, open table.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
77
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 8: Working with Data
Packing the Files in a Table
The Table.Pack method packs the data in a table. When the table is packed, the table's
TablePacked event is raised. The arguments for the event indicate whether or not the table's keys changed as a result of the pack (which would be caused by removing deleted records).
Keys only change if the PackType includes RemoveDeletedRecords and if there actually were deleted records in the middle of the table. If the only deleted records in the table are at the end of the table, then no keys changed and the event does not indicate that keys were changed.
PackType Enumeration provides you with the following options.
•
PackGeometry – Indicates that the geometry objects are packed. Packing the objects attempts to remove as much unused space as possible. A fully packed RTree (the spatial index used to spatially access the geometry objects) may reduce performance by causing many more unnecessary reads. To balance disk space and processing speed, packing the geometry objects may continue to leave some unused space in the
RTree. Also note: a packed RTree results in a slight performance penalty for insert and update operations as there is a higher likelihood that the RTree needs to be expanded.
•
RebuildGeometry – Rebuilding the geometry objects removes unused space that has resulted from a series of insert, update, and/or delete operations. Unlike packing the geometry objects, this option intentionally leaves unused space in the RTree index to improve the performance of future insert and update operations.
•
PackIndex – Non-spatial indices are maintained as B*trees. These structures do not always have filled internal or leaf nodes. This is intentional by default to allow room for the index to accommodate insert and update operations without requiring a significant restructuring of the index. The unused space may be exacerbated by the occurrence of insert, update, or delete operations. Packing an index fully packs every internal and leaf node (except possibly the “last” node). This option reduces the disk space used by the index as much as possible and also improves the read-performance of the index.
There is a performance penalty for insert and update operations on a fully packed index.
•
RebuildIndex – Rebuilding an index does not fully pack the internal and leaf nodes like the PackIndex option. Instead, rebuilding an index recreates the index with the amount of unused space that is intentionally put into the index to balance disk space, read performance, and modify performance. After several modification operations, an index may contain a considerable amount of unused space. This option regains that unused space.
•
RemoveDeletedRecords – Some data sources, including MapInfo Native and dBase data sources, do not physically remove records when they are deleted. To physically remove the deleted records, the table must be packed with this option specified. The record number is typically used as the record key for these data source types.
Removing deleted records from a table may cause keys to become invalid since they may change as a result of the pack.
•
CompactDb – If the table's data source is Microsoft Access (TableType of Access), then the MDB file containing the table's data may also be compressed using the Pack method and specifying this option.
•
All – This is a convenience option that is equivalent to PackGeometry | PackIndex |
RemoveDeletedRecords.
Listening to Table and Catalog Events
Table exposes several events which applications may subscribe to. They are:
•
RowInsertedEvent – Occurs when a new row is added to the table.
•
RowUpdatedEvent – Occurs when an existing row in the table is updated.
•
RowDeletedEvent – Occurs when a row in the table is deleted.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
78
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 8: Working with Data
•
TablePackedEvent – Occurs when the table is packed.
•
TableCloseRequestEvent – Occurs when the table has been asked to close.
•
TableIsClosingEvent – Occurs when the table is closing.
•
TableClosedEvent – Occurs when the table is closed.
Catalog also exposes the following events.
•
TableOpenedEvent – Occurs when a table is opened.
•
TableCreatedEvent – Occurs when a new table is created.
•
TableIsClosingEvent – Occurs when the table is closing.
Table Metadata (TableInfo)
The TableInfo class in the Data namespace contains information, or metadata, about an existing table. Every MapInfo table has metadata or information about the table. This information includes:
•
Columns – number, names, data types, etc.
•
The description and pathname of the data source.
•
Client Metadata (the information between the begin_metadata/end_metadata tags in the TAB file).
TableInfo is also used to define a new table or to open an existing one. For example, when a
.TAB is not available for a data source, it may be opened via the Catalog using a TableInfo object.
The following diagram shows the structure of the TableInfo class and classes related to it.
TableInfo classes can also be used to access data from an RDBMS. See
for more information.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
79
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 8: Working with Data
Examining TAB File Metadata
TAB file metadata is accessible and editable. The TableInfo class can be obtained from the
Table to get information about the table structure. The following code demonstrates how to get the metadata for an open table. The code also demonstrates how to geometry column can be used to determine the coordinate system and bounds of the table.
using MapInfo.Data;
// Get the metadata for an open table
TableInfo ti = Session.Current.Catalog["states"].TableInfo;
// Print out some information to the console
Console.Out.WriteLine(
"Table Alias={0}, Datasource={1}, Description={2}, Type={3}", ti.Alias, ti.DataSourceName, ti.Description, ti.TableType);
// Print out some information about each column foreach(Column col in ti.Columns)
{
Console.Out.WriteLine("Column {0} Type={1} Width={2}", col.Alias, col.DataType, col.Width);
// If the column is a geometry column, print csys and bounds.
if (col.DataType == MIDbType.FeatureGeometry)
{
GeometryColumn geocol = col as GeometryColumn;
MapInfo.Geometry.CoordSys csys = geocol.CoordSys;
Console.Out.WriteLine("CSys : {0}", csys.MapBasicString);
MapInfo.Geometry.DRect dr = geocol.Bounds;
Console.Out.WriteLine("Bounds=({0},{1}),({2},{3})", dr.x1, dr.y1, dr.x2, dr.y2);
}
}
Creating a New Table
The following sections illustrate how to create a permanent native table, a temporary native table, and a temporary MemTable.
Create a New Permanent Native Table
The Table.TableInfo property for a MapInfo Native table returns an instance of TableInfoNative.
This class may be used to access properties that are specific to native table types. New instances of this class may be created and used to construct new tables.
Note the use of the ColumnFactory class. This is provided to help you know which arguments are necessary for different data types. For example, a geometry column requires a coordinate system.
using MapInfo.Data;
TableInfoNative ti = new TableInfoNative("NewTable"); ti.TablePath = @"c:\data\Capitals.TAB"; ti.Columns.Add(ColumnFactory.CreateIndexedStringColumn("Capital", 25)); ti.Columns.Add(ColumnFactory.CreateStringColumn("Country", 30)); ti.Columns.Add(ColumnFactory.CreateDoubleColumn("Pop_Grw_Rt"));
// Make the table mappable ti.Columns.Add(ColumnFactory.CreateStyleColumn());
CoordSys Robinson =
Session.Current.CoordSysFactory.CreateFromPrjString("12, 62, 7, 0"); ti.Columns.Add(ColumnFactory.CreateFeatureGeometryColumn(Robinson));
// Do not add a column of type Key. Every table automatically contains
// a column named "MI_Key".
Table table = conn.Catalog.CreateTable(ti);
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
80
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Create a Temporary Native Table
using MapInfo.Data;
Chapter 8: Working with Data
// First, construct a new TableInfoNative
TableInfoNative ti = new TableInfoNative("NewTable");
// Set the Temporary property to true. ti.Temporary = true;
// Create the column definitions for the new table…
Column col; col = ColumnFactory.CreateStringColumn("State_Name", 30); col.Indexed = true; ti.Columns.Add(col); col = ColumnFactory.CreateIntColumn("Population"); col.Indexed = true; ti.Columns.Add(col);
// Note we do not need to (nor should we) add a column of type Key. ////
Every table automatically contains a column named "MI_Key".
ti.Columns.Add(
// LongLatCSys is a ref to a CoordSys object
ColumnFactory.CreateFeatureGeometryColumn(LongLatCSys));
// Use the Catalog to create the new table
Table miTable = conn.Catalog.CreateTable(ti);
Create a Temporary MemTable
The Table.TableInfo property for a memory table returns an instance of TableInfoMemTable.
This class may be used to access properties that are specific to memory table types. New instances of this class may be created and used to construct new tables. using MapInfo.Data;
TableInfoMemTable ti = new TableInfoMemTable("NewTable");
// Note: The TablePath property does not apply - it can be set but it
// is meaningless.
ti.Columns.Add(ColumnFactory.CreateIndexedStringColumn("Capital", 25)); ti.Columns.Add(ColumnFactory.CreateStringColumn("Country", 30)); ti.Columns.Add(ColumnFactory.CreateDoubleColumn("Pop_Grw_Rt"));
// Make the table mappable ti.Columns.Add(ColumnFactory.CreateStyleColumn());
CoordSys Robinson =
Session.Current.CoordSysFactory.CreateFromPrjString("12, 62, 7, 0"); ti.Columns.Add(ColumnFactory.CreateFeatureGeometryColumn(Robinson));
// Note we do not need to (nor should we) add a column of type Key.
// Every table automatically contains a column named "MI_Key".
Table table = conn.Catalog.CreateTable(ti);
Adding Expression Columns to a Table
Use the Table.AddColumns Method (Columns) to add expression columns to a table. This form of AddColumns creates temporary columns based on expressions comprised of functions, operators, literal values, and other columns on the table. All instances of Column in the columns argument must have an expression string specified.
using MapInfo.Data;
Columns newCols = new Columns; newCols.Add(new Column("PopDensity1990", "Pop_1990 / MI_Area(Obj, 'sq mi',
'Spherical')")); newCols.Add(new Column("PopDensity2000", "Pop_2000 / MI_Area(Obj, 'sq mi',
'Spherical')")); tbl.AddColumns(newCols);
“Pop_1990 / MI_Area(Obj, 'sq mi', 'Spherical')”
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
81
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 8: Working with Data
The expression string
“Pop_1990 / MI_Area(Obj, 'sq mi', 'Spherical')”
represents derived information that will be placed in the temporary column. It says ‘For each record divide population by area in square miles to yield the population density.’ The SQL function MI_Area () in the expression will derive the area from the geometry of the record.
For more information on creating expressions, see
.
Data Sources
The following table lists the data sources supported by MapXtreme 2004.
Class
TableInfoNative
TableInfodBase
TableInfoMSAccess
TableInfoAscii
TableInfoServer
TableInfoShapefile
TableInfoMemTable
TableInfoView
TableInfoSeamless
TableInfoRaster
TableInfoGrid
TableInfoWMS
TableInfoAdoNet
TableInfoResultSet
TableType
Native dBase
Access
Ascii
Server
Shapefile
MemTable
View
Seamless
Raster
Grid
WMS
ADONET
ResultSet
Description
MapInfo native table. The table may have an associated MAP file containing geometry and style information.
Data stored in a dBase file. The table may have an associated
MAP file containing geometry and style information.
Microsoft Access database table.
Data stored in an ASCII text file.
A table based on a RDBMS server connection and query string
(possibly using SpatialWare or Oracle Spatial). SpatialWare 4.8 for SQL Server, SpatialWare 4.5.1 for Informix, Oracle Spatial
817, 9iR1, 9iR2, 9iR2Locator, XY and MICode.
An ESRI Shapefile table.
A temporary table with data stored in memory and geometry stored in a temporary MAP file.
A view based on a SQL Select statement (MapBasic or Map-
Info SQL - this is not the same as the server-side SQL used in a Server table). The expressions which appear in the select-list form the columns of the table and the records which satisfy the where clause constitute the membership of the table.
A seamless table
A table containing a raster image.
A table containing a grid image.
A table containing an image from a WMS server.
This is the table type which consists of client data imported into the DataAccess engine and exposed as an Table. The client's data may be supplied using a few forms of ADO.NET objects.
A ResultSet table is currently used exclusively for IResultSet-
FeatureCollections.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
82
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 8: Working with Data
Working with XY Spatial and PointRef Schemas
Spatial schemas are services that can be applied to a table to enhance its spatial capabilities.
There are two type of spatial schemas: XY and PointRef. Tables that have a GeometryColumn are referred to as mappable. Non-mappable tables do not have a GeometryColumn and thus cannot be displayed in a Map. Non-mappable tables that have attribute columns which represent X and Y values or that have an attribute column which can be used to reference a record in a mappable table may make use of a spatial schema service when the table is opened to synthesize a GeometryColumn.
XY Spatial Schema
The XY spatial schema is used by the table to construct a Point geometry from X and Y data values for each record. The XY spatial schema may be applied to tables of any data source except Seamless, Views, and ResultSet.
The XY spatial schema can be applied to a non-mappable table to make it mappable by specifying the columns that contain the X and Y coordinate values and the coordinate system which these values represent. When the table is opened, the table contains a
GeometryColumn and may be added to a Map as a layer. The geometry column
(MI_Geometry) is modifiable and modifies the X and Y values in the table. This allows tools in a
Map to be used to move a geometry. The X and Y columns are marked as read only.
using MapInfo.Data;
// Construct the table info for the Customers table
// NOTE: There is no entry in the MapCatalog for this table.
// Also NOTE: We are using an overload of the constructor to
//TableInfoServer which accepts the ConnectString, Query, and Toolkit.
TableInfoServer ti = new TableInfoServer("Customers",
"DRIVER={SQL Server};SERVER=your_server;DATABASE=your_db;"+
"UID=mapx;PWD=mapx;Trusted_Connection=No;",
"Select * from your_db.dbo.CUSTOMERS",
ServerToolkit.Odbc);
// Construct the XY schema information
SpatialSchemaXY xy = new MapInfo.Data.SpatialSchemaXY(); xy.CoordSysString = "CoordSys Earth Projection 1, 0"; xy.XColumn = "CustLoc_X"; xy.YColumn = "CustLoc_Y";
// Apply the XY schema information to our table info ti.SpatialSchema = xy;
// Open the table.
Table customers = catalog.OpenTable(ti);
The table should have a FeatureGeometry column and a Style column (MI_Geometry and
MI_Style). The original TAB file has not been modified and if re-opened (or opened in another session) would not be mappable. Use TableInfo.WriteTabFile to rewrite the TAB file with the new metadata properties. If the TAB file is rewritten, the spatial schema is automatically regenerated and used every time the table is opened.
PointRef Spatial Schema
This schema uses a lookup value in the table's data to create a Point geometry object by matching the lookup value against a mappable table.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
83
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 8: Working with Data
The PointRef spatial schema can be applied to a non-mappable table (i.e., a table without a geometry column) to make it mappable by using the value from a column in the table
(MatchColumn) to look up a Geometry in another table (the reference table).
If you have a table that is non-mappable, but which has a data value that can be associated with a value in a table that is mappable, the table may be accessed using the Point Reference spatial schema as the following example illustrates.
using MapInfo.Data;
TableInfo ti = TableInfo.CreateFromFile(@"c:\data\customers.TAB");
// a non-mappable table
SpatialSchemaPointRef pr = new SpatialSchemaPointRef(); pr.StyleType = StyleType.None; pr.RefTable = "us_zips"; // a mappable table pr.RefColumn = "zipcode";
// the column in RefTable which matches the MatchColumn in my data pr.MatchColumn = "zip"; // a column in the Customer table pr.RefTableLocation = @"c:\data\us_zips.tab"; ti.SpatialSchema = pr;
// Now set the spatial schema information before opening the table.
Table table = Session.Current.Catalog.OpenTable(ti);
The table should have a FeatureGeometry column and a Style column (MI_Geometry and
MI_Style). The original TAB file has not been modified and if re-opened (or opened in another session) would not be mappable. Use TableInfo.WriteTabFile to rewrite the TAB file with the new metadata properties. If the TAB file is rewritten, the spatial schema is automatically regenerated and used every time the table is opened.
Data Binding
Data binding is the process of bringing data from a data source into MapXtreme 2004. Data binding of external (ADO.NET and other legacy sources) data to MapInfo.Data.Tables is accomplished by opening an ADO.NET DataTable as a Table using TableInfoAdoNet. The table can then be joined with another table or use Table.AddColumns to bind columns to a second table.
If an application has data stored in a DataTable or data that is accessible through an ADO.NET data provider, that data can be presented to the MapInfo Catalog and treated as a MapInfo table. This would be primarily useful if the data were not accessible through one of the other table types. For example, if the data is stored in a dBase file, Microsoft Access table, or is accessible through ODBC or Oracle's OCI interface, it is recommended that those table types be used to access the data. Data which cannot be accessed through one of these types of tables, but that can be loaded into a DataTable or is accessible through some ADO.NET Data
Provider that implements the Command, Parameter and DataReader object types can still be accessed by the MapInfo Catalog.
An application may need to make data available as a MapInfo table so that queries can be executed to join the data with other MapInfo table data. It may also need to be made available to the Catalog so it can be used as the source data in a call to the Table.AddColumns.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
84
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 8: Working with Data
Accessing Client Application Data
The ADO.NET table can be in one of two forms: DataTable (in-memory data, allows read-write access); or IDbCommand (dynamic data, read-only).
Accessing Data in a DataTable
When using a DataTable, the MapInfo Catalog is essentially holding on to a reference to the
DataTable you supply to the call to Catalog.OpenTable (using the TableInfoAdoNet class).
MapInfo Tables based on DataTables are editable using the MapInfo ADO.NET Data Provider by issuing Insert, Update, and/or Delete commands. Your application may continue to access the DataTable directly as well. Note, however, that the structure of the table should not be changed while the MapInfo Catalog has a reference to it. Also note that changes to the data outside of the MapInfo data provider (e.g., without using the MICommand to issue Insert,
Update, or Delete commands) will not result in the raising of the insert, update, or delete table events.
The DataTable contains almost enough information for the Catalog to define the table. For string columns, however, the MapInfo Catalog needs to assign a length to this field. The length would be used when constructing temporary indices, temporary tables for aggregation, etc. For these types of operations, it is important to get the string length correct. The DataColumn has a
MaxLength property that should be set to indicate the maximum length string the column could hold. If not set, this value defaults to -1 in which case the value of 254 is used. Before checking the MaxLength property, the catalog looks to see if the DataColumn has a property defined in its ExtendedProperties collection with the name “StringWidth”. If found, the value for this property is used as the column's width.
This example illustrates how to create a MapInfo Table whose data is stored in a DataTable.
// Create a DataTable with state information in it.
DataTable data = SomeFunctionWhichReturnsADataTable();
// Create a MapInfo table that uses the DataTable as its data source.
TableInfoAdoNet tableInfo = new TableInfoAdoNet("StateInfo", data);
Table miStateInfo = catalog.OpenTable(tableInfo);
// Open tables States
Table states = catalog.OpenTable("States.tab");
// Now call AddColumns on states.
// Supply the miStateInfo Table as the source.
states.AddColumns( null,
BindType.Static, miStateInfo,
"stcode",
Operator.Equal,
"state");
// All columns
// Statically bind
// Source data (Table)
// Match columns between states
// and miStateInfo Where
// miStateInfo.stcode = states.state
Accessing Data Using an IDbCommand
The second form of ADO.NET table is based on the connected object types in ADO.NET:
Connection, Command, and DataReader. MapInfo Tables constructed in this fashion are readonly. These types of tables are created by passing to the Catalog an IDbCommand object that is already configured to return all of the data that is to comprise the table. When the table is initially created (by calling Catalog.OpenTable), ExecuteReader is called on the IDbCommand.
The resulting data reader is used to determine the columns and their data types. All
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
85
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 8: Working with Data
subsequent cursor requests (other than cursors which retrieve a specific record - called a key fetch) also call ExecuteReader to fetch the data to satisfy the cursor. Notice that this may be very inefficient. If at all possible, use one of the other table types to access your data.
Since the Command-based form of the ADO.NET table is designed to use the generic interfaces without requiring any specific knowledge of any particular implementation of these interfaces, the table also does not assume that the IDbCommand.CommandText is any form of standard SQL. In fact, it may not be SQL at all. This table type does not access, parse, or modify the CommandText. This means that this table type has no mechanism for knowing which column(s) in the results formulate a unique, non-null key value. For this type of table, it is required to tell the table which column(s) constitute the key. This is accomplished by specifying the KeyType as Explicit and setting the KeyColumns property.
There are many operations inside the MapInfo Data Provider which require the retrieval of a specific record by key (also referred to as a key fetch). Select statements with a where clause of the form MI_Key = '5' is a simple example in which we need to retrieve the record whose
MI_Key column can be represented by the string literal '5'. Key retrievals are very common in mapping selections, labeling, and scrolling in a MIScrollableReader (in which case the reader may be scrolling through a list of key values). MapInfo tables are dependent upon the ability to efficiently fetch records by key value. Just as the Command-based form of the ADO.NET table does not read, parse, or modify the CommandText of the IDbCommand object that defines the table (the “Sequential” IDbCommand), it has no ability to modify the IDbCommand object to fetch a specific record. Thus, a second IDbCommand object must be supplied for this purpose.
The “FetchByKey” IDbCommand object must meet the following requirements:
•
When ExecuteReader is called on this command object, it must produce a data reader that has the same columns as the sequential command object and in the same order.
•
The FetchByKeyCommand must contain a Parameters collection and must contain one parameter for each member of the key. For example, if the TableInfo.KeyColumns specifies a key as consisting of the “city” and “state” columns, then the
FetchByKeyCommand must contain two parameter objects. The first parameter object is assigned a value representing the first column specified in the
TableInfo.KeyColumns collection (e.g., a value for “city”), the second parameter object is assigned a value representing the second column specified in the
TableInfo.KeyColumns collection (e.g., a value for “state”), and so on. When
ExecuteReader is called on the FetchByKeyCommand, the reader must return the record which represent s the specified key.
This example illustrates how to create a MapInfo Table that accesses data through the
ADO.NET connected command objects.
TableInfoAdoNet ti = new TableInfoAdoNet("EuropeanCities");
OleDbConnection _conn = new
OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\Data\EuropeCities.mdb"); string selectQuery = "SELECT City, Country, Continent, Pop_1994 FROM
EuropeCities";
OleDbCommand _OleDbCommand = new OleDbCommand(selectQuery);
_OleDbCommand.Connection = _conn; selectQuery = selectQuery + " where City = @City AND Country = @Country" ;
OleDbCommand _OleDbKeyCommand = new OleDbCommand(selectQuery);
_OleDbKeyCommand.Parameters.Add("@City",OleDbType.Char);
_OleDbKeyCommand.Parameters.Add("@Country",OleDbType.Char);
_OleDbKeyCommand.Connection = _conn;
// The MapInfo Table will Open/Close the connection as necessary.
// If this is expensive, the application could open the connection
// before opening the table and closing the connection after the table
// is closed.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
86
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 8: Working with Data
ti.SequentialCommand = _OleDbCommand; ti.FetchByKeyCommand = _OleDbKeyCommand;
// Tell the table which column(s) constitute a key -
// for this table it's a compound
// key consisting of values from the City and County columns.
StringCollection sc = new StringCollection(); sc.Add("City"); sc.Add("Country"); ti.KeyColumns = sc; ti.KeyType = KeyType.Explicit;
// Ask the Catalog to open the table.
Table tbl = connection.Catalog.OpenTable(ti);
// Now the MICommand object may be used to select data from the table
// (by the name EuropeanCities since that is the alias we assigned to
// it). The data in this table may be joined with any other table and
// it may be used as source data in a call to AddColumns to populate
// temporary columns with data from this table.
Source Rows
Source rows represent a match between the table records involved in AddColumns. The
SourceRows class is a collection of SourceRows which identify the records from a data source that were aggregated together for each record in a destination temporary column added to a table.
The AddColumns methods can be used to add temporary columns to a Table. The values for the temporary columns may be computed automatically from associating records in the bind table to records in another data source. The SourceRows contains the mapping of records between the source data and the bind data (and also the refine table, if used).
The GeoDictionary
The GeoDictionary maintains information about which map entities can be matched to which information. The GeoDictionaries class is a collection of GeoDictionary objects. The
MapInfo.Data.GeoDictionary namespace provides support for data autobinding by being a programmatic representation of the GeoDictionary file. The GeoDictionary file contains information about tables (TAB files only). The GeoDictionary is used to automatically determine the table to which application data should be bound. The GeoDictionary is persisted in a file
(typically GeoDict.DCT) and is maintained using the GeoDictionaryManager utility application
(see
Appendix D: Using the GeoDictionary Manager
AutoMatching Using the GeoDictionary
The MatchResolver.AutoMatch method in the Data.GeoDictionary namespace initiates the
AutoMatching process. It does not call AddColumns, i.e., does not do the binding. A subsequent call to BindColumn is required to perform the autobinding, or a direct call to
AutoMatchAndBind.
Automatching can encounter ambiguous situations. These situations include:
•
multiple source columns are detected in the user data
•
multiple tables/layers are detected that match the source column
•
multiple geosets/workspaces are available for the matched table/layer.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
87
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 8: Working with Data
It is the MatchResolver object with which the GeoDictionary communicates during the match process to solve the ambiguity. It provides the matching algorithm. The basic class selects the first or the one with the highest matching percentage. This class is not sealed and client applications may derive their own class from this and override its behavior.
Features and Feature Collections
The Feature class object model in MapXtreme 2004 offers a non-SQL-based approach to access and manipulate data. This section covers the Feature class and IFeatureCollection interface. A key task in working with features is the ability to search for them using a query definition object.
Feature
Features are described by their geometry, style, data source, key and attributes. Typically a feature is a row in a table. A feature’s geometry is a FeatureGeometry object.
FeatureGeometries can cover a given area (MultiPolygon), a location (Points, MultiPoints); and distance (MultiCurves, LegacyArcs). Additional Geometry classes that derive from
FeatureGeometry and are used for map features are FeatureGeometryCollection and
LegacyText. (Rectangle, rounded rectangle and ellipse objects also derive from
FeatureGeometry, but are used primarily for cosmetic display purposes.)
One of the main uses of computerized maps is to gather information about the features. In
MapXtreme 2004 features are returned in FeatureCollections by any of several methods, either created from scratch using a schema, selected using selection tools or methods or by searching the Catalog for those that meet a specific set of criteria.
You can force a Load using the Load method. Changes made to the Feature are not reflected in the underlying table (if there is one) until the Feature is saved back to the table. This is done using the Update method, or UpdateFeature or InsertFeature.You can throw away any edits done to the Feature object before it is saved using the DiscardEdits method.
A Feature has a schema that describes the attributes of the Feature. The Columns property describes the schema.
Retrieving Features from a Table
A Table is a type of Feature collection. As such, the Features within the table may be enumerated directly. For example: foreach (Feature f in table)
{
...
}
The default feature enumerator for a table uses an MIDataReader internally with the following command: command.CommandText = "Select MI_Key, * From \"" + table.Alias + "\"";
To retrieve a subset of the features in a table, use one of the Catalog.Search methods or use one of the MICommand.ExecuteFeatureCollection methods.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
88
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Modifying Features in a Table
To modify features in a table, use one of the following methods.
•
Feature.Update
•
Table.UpdateFeature
•
Table.InsertFeature
Chapter 8: Working with Data
Feature Collections
Feature collections are a group of Feature objects. All Features in a collection share the same
Schema (columns). The Feature collection has a schema which is the schema of all of its member feature instances. Some Feature collections own their Features while other Feature collections maintain references to Features.
Searching for Features
One of the most common tasks in MapInfo’s mapping applications is to search for features that meet certain criteria. Once you have the features you are interested in, you can carry out further analysis, such as thematic mapping. In MapXtreme 2004, searching for features can be done in a number of ways: using tools, using Catalog search methods, or using SQL and the
MapInfo ADO.NET Data Provider.
The following code sample shows two ways to search for the same thing, in this case, cities in
New York.
// Using SQL command.CommandText = "Select Obj From States Where state = ‘NY’;
FeatureGeometry nyGeom = command.ExecuteScalar() as FeatureGeometry; command.CommandText =
"SELECT * FROM Cities WHERE Obj within @newyork"; command.Parameters.Add("@newyork", nyGeom);
MIDataReader reader = command.ExecuteReader();
// or… to get a FeatureCollection
IFeatureCollection fc = command.ExecuteFeatureCollection();
// Using Features
Feature fNY = catalog.SearchForFeature("States",
SearchInfoFactory.SearchWhere("state='NY'"));
SearchInfo si = SearchInfoFactory.SearchWithinFeature(fNY,
ContainsFilter.ContainsType.Centroid);
IDynamicFeatureCollection dfc = catalog.Search("Cities", si) as IDynamicFeatureCollection;
Console.Out.WriteLine(
"There are {0} cities whose centroid is within NewYork." dfc.Count);
SQL searches are more fully discussed in
MapInfo ADO.NET Data Provider on page 93
following sections focus on searches using the Catalog and SearchInfo.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
89
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 8: Working with Data
SearchInfo and SearchInfoFactory
The MapInfo.Data.SearchInfo class defines the query used in a search and handles any necessary post processing of the search results.
The SearchInfoFactory creates SearchInfo objects. SearchInfoFactory contains a number of search methods that allow you to search using spatial references to your search location or by using geometries that are drawn on the screen.
The following table describes the SearchInfoFactory search methods.
SearchInfoFactory
SearchAll
Methods
SearchNearest
SearchWhere
SearchWithinDistance
SearchWithinFeature
SearchWithinGeometry
SearchWithinRect
Behavior
Returns all the rows.
Returns the rows with table geometries that are closest to the given search point.
Returns the rows specified by the given where Clause.
Returns the rows where the table geometry is contained within a buffer of the search point, rectangle or geometry.
Returns the rows where the table geometry is contained within the search features's geometry.
Returns the rows where the table geometry is contained within the search geometry.
Returns the rows where the table geometry intersects the given rectangle.
SearchIntersectsFeature Returns the rows where the table geometry intersects with the search features's geometry.
SearchIntersectsGeometry Returns the rows where the table geometry intersects with the search geometry.
SearchWithinScreenRadius Creates a SearchInfo that returns the rows where the table geometry intersects a screen circle.
SearchWithinScreenRect Returns the rows where the table geometry intersects the given screen rectangle.
MapXtreme 2004 ships with a Search sample application that you can run and learn more about each search type. The illustration below shows the Search menu with the
SearchInfoFactory methods that use a spatial reference. The Map Search menu has methods for searching based on a drawn screen geometry object (circle or rectangle). The Query
Definition menu highlights the use of various filters that act on an SQL statement. Find the sample in the \Samples\Common\Features\Search folder.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
90
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 8: Working with Data
Code Samples
This section includes several code samples that pertain to SearchInfoFactory methods.
SearchNearest
Using the SearchNearest method, the code simulates the Select Point tool behavior to select the topmost items under a mouse click and add them to the selection.
// Get a point from mouse click. Hard coded value use in sample.
System.Drawing.Point pt = new System.Drawing.Point(100, 100);
// Assumes there is a MapControl with a map in it.
Map map = MapControl1.Map;
ISession session = MapInfo.Engine.Sesion.Current;
SearchInfo si =
MapInfo.Mapping.SearchInfoFactory.SearchNearest(map, pt, 3);
// 3 pixel tolerance radius si.QueryDefinition.Columns = null; // fetch all columns instead
// of just default
// Customize to stop at topmost layer where something is found
(si.SearchResultProcessor as ClosestSearchResultProcessor).Options
= ClosestSearchOptions.StopAtFirstMatch;
// Puts results of search directly into default selection
// Searches all tables in map in order from top to bottom.
Session.Catalog.Search(map.Layers.GetTableEnumerator(), si, session.Selections.DefaultSelection,
ResultSetCombineMode.Replace);
SearchIntersectsFeature
// search through all tables to find objects that intersect Germany private void menuItemSearchMultipleTables_Click(object sender,
System.EventArgs e)
{ try
{
Cursor.Current = Cursors.WaitCursor;
// find countries that intersect Germany
// then combine them and search all layers within
// also uses search for feature
Feature fDEU = _catalog.SearchForFeature
("europe", MapInfo.Data.SearchInfoFactory.SearchWhere
("Country='DEU'"));
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
91
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 8: Working with Data
SearchInfo si =
MapInfo.Data.SearchInfoFactory.SearchIntersectsFeature
(fDEU, IntersectType.Geometry);
IResultSetFeatureCollection fc =
_catalog.Search("europe", si);
MapInfo.FeatureProcessing.FeatureProcessor fp = new MapInfo.FeatureProcessing.FeatureProcessor();
Feature f = fp.Combine(fc); si = MapInfo.Data.SearchInfoFactory.SearchWithinFeature
(f, ContainsType.Centroid);
MultiResultSetFeatureCollection mfc =
_catalog.Search(_catalog.EnumerateTables
(TableFilterFactory.FilterMappableTables()), si);
SearchWithinScreenRadius
This sample illustrates how to search for features using a screen drawn circle.
// find nearest city to center of map private void menuItemSearchNearest_Click
(object sender, System.EventArgs e)
{ try
{
Cursor.Current = Cursors.WaitCursor;
// to compare to SearchWithinScreenRadius, we are
// calculating the search distance the same way it does
System.Drawing.Rectangle rect=mapControl1.Bounds;
System.Drawing.Point pt = new System.Drawing.Point(rect.Left, rect.Top); pt.X += rect.Width/2; pt.Y += rect.Height/2;
DPoint dpt1 = new DPoint();
// convert center point to map coords (could use map.Center)
_map.DisplayTransform.FromDisplay(pt, out dpt1);
Distance d =
MapInfo.Mapping.SearchInfoFactory.ScreenToMapDistance
(_map, 3);
SearchInfo si =
MapInfo.Data.SearchInfoFactory.SearchNearest
(dpt1, _map.GetDisplayCoordSys(), d);
IResultSetFeatureCollection fc =
_catalog.Search("uscty_1k", si);
MapInfo.Geometry.Point p = new MapInfo.Geometry.Point
(_map.GetDisplayCoordSys(), dpt1);
FeatureGeometry buffer = p.Buffer(d.Value, d.Unit, 20, DistanceType.Spherical);
ShowSearchGeometry(buffer);
SelectFeatureCollection(fc);
} finally
{
Cursor.Current = Cursors.Default;
}
}
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
92
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 8: Working with Data
Catalog Search Methods
The Catalog has a number of search methods as members. The overloaded Search method can be used to search on one or more tables. They include different arguments to make each search unique. For example, the basic Search (Table, SearchInfo) searches the given table and returns a FeatureCollection. The Search (ITableEnumerator, SearchInfo) method searches on multiple tables and returns a MultiResultSetFeatureCollection.
The SearchForFeature method returns the first Feature from the results.The SearchReader method returns an MIDataReader cursor with the results.
See the Catalog class in the MapXtreme 2004 Help for more information.
Code Sample: SearchForFeature
The following example shows how to use Catalog.SearchForFeature and
Catalog.SearchWithinGeometry. It finds all the cities in the uscty_1k table that are within
Florida. It assumes that tables “usa” and “uscty_1k” are open and that there is one map.
Feature fFlorida = _catalog.SearchForFeature("usa",
MapInfo.Data.SearchInfoFactory.SearchWhere("State='FL'"));
SearchInfo si =
MapInfo.Data.SearchInfoFactory.SearchWithinGeometry
(fFlorida, ContainsType.Centroid);
IResultSetFeatureCollection fc =
MapInfo.Engine.Session.Current.Catalog.Search
("uscty_1k", si);
// Set the map view to show search results
MapInfo.Engine.Session.Current.MapFactory[0].SetView(fc.Envelope);
// Set the view of the first map.
// Add results to selection.
MapInfo.Engine.Session.Current.Selections.DefaultSelection.Add(fc);
MapInfo ADO.NET Data Provider
MapXtreme 2004 provides mechanisms for issuing SQL commands which return record sets from tables using ADO.NET. This is the preferred mechanism for accessing data in .NET applications
A complete reference on the new MapInfo SQL language that MapXtreme 2004 supports is
Appendix A: MapInfo SQL Commands
. Additionally, you can view it directly from
Visual Studio .NET’s Dynamic Help system.
The following sections present the key interfaces and classes for accessing data via the
MapInfo .NET Data Provider.
MIConnection
An MIConnection represents a connection to the Catalog. The connection provides a starting point for issuing commands and obtaining results. Whereas most data provider connections allow the user to immediately begin issuing queries or other commands against existing tables
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
93
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 8: Working with Data
(or schema objects), the MapInfo data provider initially has no tables available. Tables need to be opened or created before they can be accessed. When opened, a name (alias) can be associated with the table which is used when resolving identifiers in the query engine.
Connections are not pooled in the MapInfo data provider and there is no connection string required to create a new connection.
The Session class creates and initializes the Catalog which may be accessed through the
Session.Current.Catalog property. The MIConnection.Open method obtains a reference to the
Catalog using the Session.Current.Catalog property and the MIConnection.Close method sets the internal reference to the Catalog to null.
using MapInfo.Data;
MIConnection connection = new MIConnection();
MICommand command = connection.CreateCommand(); command.CommandText = "Select * From States Where Pop > 1000000"; connection.Open();
MIDataReader reader = command.ExecuteReader(); int i,n = reader.FieldCount; for (i=0; i < n; i++)
{
Console.Out.Write("{0}\t", reader.GetName(i));
}
Console.Out.WriteLine(); while(reader.Read())
{ for (i=0; i < n; i++)
{ object o = reader.GetValue(i); if (o == DBNull) Console.Write("null\t"); else Console.Write("{0}\t", o.ToString());
}
Console.Out.WriteLine();
} reader.Close(); command.Dispose(); connection.Close();
MICommand
MICommand provides the necessary interface for executing SQL commands against the
MapInfo Data Provider. MICommand creates MIDataReader and MIScrollableReader instances for obtaining data via the ExecuteReader and ExecuteScrollableReader methods, respectively.
Supported Commands
The commands that are able to be understood by the MICommand are:
Select
SELECT < select_list >
FROM { < table_source > } [ ,...n ]
[ WHERE < search_condition > ]
[ GROUP BY expression [ ,...n ] ]
[ ORDER BY {expression | column_position [ ASC | DESC ] } [ ,...n ]]
< select_list > ::=
{
*
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
94
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 8: Working with Data
| { table_name | table_alias }.*
| { expression } [ [ AS ] column_alias ]
} [ ,...n ]
< table_source > ::= table_name [ [ AS ] table_alias ]
Insert
INSERT [INTO] { table_name } [ ( column_list ) ]
{ VALUES ({expression | NULL}[, ...n]) | query_specification
Update
UPDATE { table_name }
SET {{ column_name } = { expression | NULL }} [, ...n]
[WHERE < search_condition > ]
Delete
DELETE [FROM] { table_name } [ WHERE < search_condition > ]
< search_condition > ::=
{ [ NOT ] < predicate > | ( < search_condition > ) }
[ { AND | OR } [ NOT ] { < predicate > |
( < search_condition > ) } [ ,...n ] ]
< predicate > ::=
{ expression [ { = | < > | != | > | >= | < | <= } expression ]
| string_expression [ NOT ] LIKE string_expression [ ESCAPE
'escape_character' ]
| expression [ NOT ] BETWEEN expression AND expression
| expression IS [ NOT ] NULL
}
expression
Is a column name, pseudo column, column alias, constant, function, or any combination of column names, column aliases, constants, and functions connected by an operator(s). Column names and pseudo columns may be prefixed with a table name or a table alias followed by the dot (“.”) character.
group_by_expression
Is a reference to a column in the select list - either an exact copy of the select list expression, the alias, a 1-based number indicating the position of the column, or coln where n is a number representing a column.
order_by_expression
Is a reference to a column in the select list - either an exact copy of the select list expression, the alias, a 1-based number indicating the position of the column, or coln where n is a number representing a column.
For more information on expressions, where they are used and how to create them, see
ExecuteFeatureCollection
The ExecuteFeatureCollection method in the MICommand class is the bridge between the
MapInfo .NET Data Provider and the Feature object model. This method executes command text (SQL statements) against the data source connection, and builds an
IResultSetFeatureCollection.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
95
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 8: Working with Data
MapInfo SQL
MapInfo SQL is standardized based on SQL-3 Specification. For example, you will find that:
•
String constants are enclosed in single quotation marks
•
Identifiers may be enclosed in double quotation marks
•
Select has no relationship to the Selection
Use the following examples as a guide.
Spatial Query
FeatureGeometry nyGeom = SomeFunctionWhichReturnsNewYork(); command.CommandText =
"SELECT * FROM States WHERE Obj within @newyork"; command.Parameters.Add("@newyork", nyGeom);
MIDataReader reader = command.ExecuteReader();
// or ...to get a FeatureCollection
IFeatureCollection fc = command.ExecuteFeatureCollection();
Aggregation Query
command.CommandText = "SELECT State, Avg(Pop), Sum(Pop), "+
"MI_AggregateUnion(Obj) As UnionGeom "+
"MI_AggregateEnvelope(Obj) As TotalMBR"+
"FROM Cities Group By State";
MIDataReader reader = command.ExecuteReader();
Fetch a Specific Record (Fetch By Key)
command.CommandText = "SELECT * FROM States WHERE MI_Key = '5'";
MIDataReader reader = command.ExecuteReader(); if (reader.Read())
{
FeatureGeometry theGeom = reader.GetFeatureGeometry(0), string theStateCode = reader.GetString(1);
} reader.Close();
Fetch a Specific Value from a Specific Record
command.CommandText = "SELECT Obj FROM States"+
"WHERE MI_Key = '5'";
FeatureGeometry theGeom = command.ExecuteScalar() as FeatureGeometry;
Insert Statement
FeatureGeometry nyGeom = SomeFunctionWhichCreatesAGeoObject(); command.CommandText =
"Insert Into States (Obj, State, State_Name) "+
"Values (@stobj, 'NY', 'New York')"; command.Parameters.Add("@stobj", nyObj); int NumberOfRecordsAffected = command.ExecuteNonQuery();
Insert Statement with Select
FeatureGeometry floodGeom = SomeFunctionWhichCreatesAGeoObject(); command.CommandText =
"Insert Into TempCounties (Obj, County, State, Pop, PopDensity,
Area) " + "Select Obj, County, State, Pop, Pop / MI_Area(Obj,
'sq mi' , 'Spherical'), " +
" MI_Area(Obj, 'sq mi' , 'Spherical') " +
" From Counties Where Obj intersects @floodRegion";
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
96
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 8: Working with Data
command.Parameters.Add("@floodRegion", floodGeom); int NumberOfRecordsAffected = command.ExecuteNonQuery();
Update Statement
command.CommandText = "Update States Set Population =
Population * 1.05"+
" Where Population / MI_Area(Obj, 'sq mi', 'Spherical') > 2000"; int NumberOfRecordsAffected = command.ExecuteNonQuery();
Delete Statement
command.CommandText =
"Delete From States Where MI_Key = @varkey"; command.Parameters.Add("@varkey", "4");
// Could be a MapInfo.Data.Key object int NumberOfRecordsAffected = command.ExecuteNonQuery(); miCommand.Parameters["@varkey"].Value = "5";
NumberOfRecordsAffected = command.ExecuteNonQuery();
MIDataReader
The MIDataReader provides forward-only, read-only access to the data returned from executing a SQL Select statement. To create a MIDataReader, you must call the
ExecuteReader method of the MICommand object, rather than directly using a constructor.
The MapInfo data provider allows multiple MIDataReader instances to be in use on the same connection. However, if the Table being accessed resides on a Microsoft SQL Server database, only one MIDataReader may be open at a time.
IsClosed and RecordsAffected are the only properties that you can call after the MIDataReader is closed. Though the RecordsAffected property may be accessed at any time while the
MIDataReader exists, always call Close before returning the value of RecordsAffected to ensure an accurate return value.
When accessing the DataReader through the IEnumerator or IFeatureEnumerator interface,
Close() is automatically called when MoveNext() returns false. Only one enumerator can be used on a DataReader.
Note:
For optimal performance, MIDataReader tries to avoid creating unnecessary objects or making unnecessary copies of data. As a result, multiple calls to methods such as
GetValue may return a reference to the same object. Use caution if you are modifying the underlying value of the objects returned by methods such as GetValue.
Scrollable Data Readers
MIScrollableReader derives from MIDataReader and offers forward and reverse reading. Some of the options available with MIScrollableReader include:
•
ReadPrevious
•
Rewind
•
Unwind
•
ReadTop
•
ReadBottom
•
AtTop / AtBottom
Note:
An MIScrollableReader is more expensive to create than MIDataReader.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
97
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Expressions
Chapter 8: Working with Data
Expressions are statements that are used to describe and format data. For example, in English, an expression might read like “a median income of more than $50,000, or “female percent of population.”
Expressions are formed using column names, constants (i.e., specific data values), along with functions and operators that act upon the columns and constants. The operators and functions are defined in the MapInfo SQL Language, newly developed to support MapXtreme 2004 and other MapInfo .NET supported products going forward. For details, see
in this guide or view it online via the integrated Help in VisualStudio.NET (look for MapInfo SQL Reference in the Dynamic Help contents pane.
Use expressions to make the most of your data. By using expressions you can:
•
Show only the columns and rows of data that interest you.
•
Derive new columns by calculating new values based on the contents of your existing columns.
•
Aggregate data to work with subtotals instead of the entire table.
•
Combine data from two or more table into one results table.
Many of the data sets you will use include more objects and information than necessary for your projects. In many cases it is easier to work with a subset of the complete data product. For example, if you were tracking crime statistics for a certain county by census tract, you would not need the census tracts for the entire state. You would use an expression to extract just the census tracts for the county.
Expressions are used throughout MapXtreme 2004, in the following areas:
•
SQL statements (select, insert, update, delete, group by, order by)
•
SQL functions that take expressions as an arguments (e.g., the geometry argument in
MI_Area() is an expression that returns a geometry object.)
•
Adding columns (MapInfo.Data.Table.AddColumn creates a temporary column based on an expression.)
•
Feature searches (SearchInfo and SearchInfoFactory)
•
Themes (FeatureStyleModifier)
•
Labels (LabelModifier)
•
InfoTips (FeatureLayer, MapTools)
•
Expression dialog
Creating Expressions
The simplest possible expression consists of a constant, such as “
2
” (numeric example) or
“
Friday
” (text example).
Other simple expressions consist of a column name, for example:
POP_2000
STATE
When you request specific multiple columns in a select statement, for example, these columns together are known as an expression list.
Select colA, colB, colC from Table1, Table2
Select colA/2, ColB/ColC from Table1
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
98
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 8: Working with Data
You can also write expressions that perform mathematical operations on your data.
For example, RENT + UTILITIES is an expression that adds two columns together. This expression could be used in a SQL statement to find all apartments that have a total cost of less than $800 per month.
Where Clause - Boolean Expressions
A Boolean expression is search condition that results in a value of either True or False. For example, the expression
2 < 5 is a Boolean expression because the result is True.
All expressions that contain relational operators, such as the less than sign (<), are Boolean.
The operators AND, OR, and NOT, are Boolean operators. Boolean expressions are also called comparison expressions, conditional expressions, and relational expressions.
POP_2000 > 500000
POP_2000 <= POP_1990
PROVINCE <> ‘Ontario’
County = ‘Columbia’ AND VALUE >= 250000
Supported operators in MapInfo SQL are defined in
Operators in Appendix A on page 252
.
For query code examples, see
MapInfo SQL in Chapter 8 on page 96
Boolean expressions are used in the “where clause” of an SQL statement. The where clause is the expression that controls the rows that are returned (the rows that result in True).
For example, the boolean expression in this statement follows WHERE. Only objects in the
Europe table that fall within the boundary of France will be returned as True.
"SELECT * FROM Europe WHERE MI_Geometry within @France";
Functions In Expressions
Functions in MapXtreme 2004 are used to create even more complex expressions to retrieve data that meets specific criteria. For example, MapInfo SQL supports many of the usual database functions that work with strings, dates, and numbers.
The most powerful functions in MapInfo SQL are those that take advantage of the spatial nature of mapping data. These geographic functions are used to create new geometries, measure area and length, return spatial information, validate spatial relationships among geometries, and others. Supported functions are defined in the MapInfo SQL reference beginning on
Listing of Functions in Appendix A on page 253
An example of using a function in an expression might be when you wish to look at the area of a table of boundaries, such as school districts. Use the function
MI_Area()
to return the area of each record in the table.
Additional examples of functions in expressions are found in the Expressions Examples section below.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
99
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 8: Working with Data
Expression Examples
The following highlights some uses of expressions in various areas of MapXtreme 2004.
SQL Statement Example
This example will select all records from the Eurcity_1K table that are within Germany and have a population of over 1 million.
Select * from Eurcity_1K WHERE (MI_Geometry MI_Within @Germany) AND
Tot_Pop > 1000000
MI SQL Function Example
The following expression uses an MI SQL function to find features within a buffer.
Obj CentroidWithin MI_Buffer(Obj, 5, ‘km’, ‘Spherical’, 24)
This expression uses a MapInfo SQL special keyword reserved for geographic objects called
‘Obj’. This keyword describes the geometry of the object such as its coordinate system and bounds. This keyword is compatible with previous versions of MapX and MapInfo Professional.
It is equivalent to the column name MI_Geometry.
Note that km and Spherical are enclosed in single quotes. In MapInfo SQL, string literals must be enclosed in single quotation marks while identifiers such as column names, table names, aliases, etc.) should be enclosed in double quotation marks, but only needed if the parsing logic is unable to correctly parse the identifier. This would include identifiers that have spaces in their names or other special characters.
To find features that fall outside the buffer, the expression would look like:
NOT Obj CentroidWithin MI_Buffer(Obj, 5, ‘km’, ‘Spherical’, 24)
Add Columns Example
When adding temporary (computed) columns to a table using the AddColumns method, the columns supplied contain an expression that defines how the value for the column is computed. The expression may contain an aggregation function if multiple source records are expected to match up to a single record in the table to which the columns are being added.
The example below uses expressions to represent population density
"Pop_1990 /
MI_Area(Obj, 'sq mi', 'Spherical')"
. The expressions are preceded by their new column names.
PopDensity1990
and
PopDensity2000
.
Columns newCols = new Columns(); newCols.Add(new Column("PopDensity1990", "Pop_1990 / MI_Area(Obj,
'sq mi', 'Spherical')")); newCols.Add(new Column("PopDensity2000", "Pop_2000 / MI_Area(Obj,
'sq mi', 'Spherical')")); tbl.AddColumns(newCols);
Feature Search Example
The following example uses a boolean expression
SearchWhere("State='FL'")
that, when executed, will return a value of 1 for each row that contains FL.
Feature fFlorida = _catalog.SearchForFeature
("usa", MapInfo.Data.SearchInfoFactory.SearchWhere
("State='FL'"));
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
100
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 8: Working with Data
SearchInfo si =
MapInfo.Data.SearchInfoFactory.SearchWithinGeometry
(fFlorida, ContainsType.Centroid);
IResultSetFeatureCollection fc =
MapInfo.Engine.Session.Current.Catalog.Search("uscty_1k", si);
// Set the map view to show search results
MapInfo.Engine.Session.Current.MapFactory[0].SetView(fc.Envelope);
// Set the view of the first map.
// Add results to selection.
MapInfo.Engine.Session.Current.Selections.DefaultSelection.Add(fc);
Thematic Expression Example
A pie theme is an object theme that draws a pie chart based on the numeric value of the theme's expression. The expression for the theme is made up of three columns:
Pop_Native",
"Pop_Asian","Pop_Other"
. using MapInfo.Mapping; using MapInfo.Mapping.Thematics;
// Load a map based on one table map.Load(new MapTableLoader("world.tab"));
FeatureLayer lyr = map.Layers["world"] as FeatureLayer;
//Create new pie theme
PieTheme pieTheme = new PieTheme(map, lyr.Table,
"Pop_Native", "Pop_Asian","Pop_Other");
// Create an object theme layer based on that pie theme
ObjectThemeLayer thmLayer = new ObjectThemeLayer
("World Pop Growth Rate", null, pieTheme);
//Add object theme to the map’s layer collection.
map.Layers.Add(thmLayer);
Label Expression Example
Expressions are properties of a label modifier which you use to modify the default properties used to make a label. The highlighted line in the example below includes an expression to modifies the caption of the labels for the usa_cap.tab. The expression says to display the caption in this form:
Point: <name of capital>
.
...
// Create an instance of the modifier and modify caption:
ModifyPointLabelModifier modifier = new ModifyPointLabelModifier(); source.Modifiers.Append(modifier);
// Setup so it modifies the caption and minor priority:
modifier.Properties.Caption = "'POINT: ' + Capital"; modifier.Properties.Priority.Minor = "Pop_1990"; modifier.Properties.Attributes =
LabelAttribute.Caption | LabelAttribute.PriorityMinor;
// Now refresh the label layer to generate labels: layer.Refresh();
// Gets Juneau Feature:
MapInfo.Data.SearchInfo info =
MapInfo.Data.SearchInfoFactory.SearchWhere
("Capital='JUNEAU'"); info.QueryDefinition.AppendColumns(new string[] { "Capital" });
Feature juneau = Session.Current.Catalog.SearchForFeature(
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
101
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 8: Working with Data
table, info);
// After refresh, Juneau's caption should now be POINT: JUNEAU:
// source.Labels[juneau][0].Caption == "POINT: JUNEAU"
// After refresh, Juneau's minor priority is based off its
// 1990 population:
// source.Labels[juneau][0].Priority.Minor == "26751"
...
InfoTips Expression Example
InfoTips are text items that display when a tool hovers over a Feature. Expressions can be used to generate text for InfoTips in a similar fashion to the way they are used for labels. Use the MapTool.SetInfoTipExpression static helper function to set the InfoTip. It takes care of creating the InfoTip hashtable and adding the layer entry into the hashtable if it does not already exist. Each tool can be set to have InfoTips enabled or disabled.
MapTool.SetInfoTipExpression(mapControl1.Tools.MapToolProperties, lyr, "@TableAlias + char(13) + 'Centroid X:' + MI_CentroidX(obj) + ' Y:' +
MI_CentroidY(obj)");
The above example will generate a two-line text label to display the table alias and either the X or Y coordinate for the centroid of the object that the cursor is hovering over.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
102
MapXtreme2004_DevGuide_A4.pdf
Accessing Data from a
DBMS
9
MapXtreme 2004 provides Spatial Server Access. This is a powerful feature that allows developers to connect to live data stored in spatial servers, such as MapInfo's SpatialWare running on Microsoft’s
SQL Server, Informix, or the Oracle Spatial databases. Spatial servers allow companies to host their map data in their enterprise database for central management and security. Spatial servers like
SpatialWare offer advanced query processing and increased performance on the server for an organization's spatial data.
In this chapter:
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
Developer Guide
Accessing Remote Spatial Data
Chapter 9: Accessing Data from a DBMS
You can access data using MapXtreme 2004 with different DBMS servers. The servers include:
•
MS Access and SQL Server2000.
•
Informix IDS 9.3
•
Spatial servers such as SpatialWare 4.6 and 4.8.1 for Microsoft SQL Server 2000, and
SpatialWare 4.5.1 for Informix IDS 9.3.
•
The MapInfo Geocoding DataBlades for Informix.
•
Oracle Spatial (8.1.7, 9ir1, and 9ir2).
•
Oracle 9ir2 Locator
You can add a table from data in a DBMS using the TableInfoServer class in the MapInfo.Data namespace.
The details for adding spatial data are included in the following sections. Once you have decided how to handle your data, follow the instructions in the appropriate section.
MapXtreme 2004 only supports opening SpatialWare 4.5 (or higher) tables.
Accessing Remote Tables Through a .tab File
A MapXtreme 2004 application can access DBMS data “live”, or can open a MapInfo
Professional linked table. However, the linked table will be read-only and cannot be refreshed by your application. The data is actually from the remote database and does not reflect the data in the local linked version.
You can create a .tab file to provide access to remote data. To generate a .tab file using
MapInfo Professional, choose File -> Open a DBMS table.
The .tab file is a text file; you can create a .tab file using any text editor. Once you have created the .tab file, you can access it the way you access any other MapInfo .tab file programmatically through the Catalog object or through the Workspace Manager.
Accessing Remote Tables Without a .tab File
An application does not need a .tab file to access remote data. The following code sample illustrates this process:
// To open an RDB table without using a TAB file
//
// First, construct a new MITableInfoServer
TableInfoServer ti = new TableInfoServer("States");
// Now set the pertinent properties of the table info.
// Note that these properties are readonly on an open table.
ti.ConnectString = "DRIVER={SQL Server};SERVER="
+"SQLserverDB;DATABASE=QADB;"
+"Trusted_Connection=No;QuotedID=No;UID=mapx;PWD=mapx"; ti.Toolkit = ServerToolkit.Odbc;
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
104
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 9: Accessing Data from a DBMS
// Specify the Query that defines the table – here we are using
// SpatialWare. Any valid SpatialWare syntax may be used.
// This query is executed by the Server – not by MapXtreme 2004.!
ti.Query = "Select * from dbo.States";
// Now pass the table info to the catalog to open the table.
Table table = _session.MIConnection.Catalog.OpenTable(ti);
Mapping DBMS Data with X/Y Columns
You can access data from a DBMS table that has X/Y coordinates. You need to create a Map
Catalog and register the tables as SpatialType 4.0 and specify two column names as the coordinates. The columns should be indexed on the table. Connect to the DBMS via ODBC and specify the new columns as “OBJ” or “MI_FEATUREGEOMETRY” in your query.
Oracle Support
You can install Oracle Spatial in addition to the MapXtreme 2004 ODBC Connectivity component. Oracle Spatial is an implementation of a spatial database from Oracle Corporation.
Oracle Spatial maintains the Oracle SDO implementation via a relational schema which the
MapXtreme 2004 Object Model does not support. The MapXtreme 2004 Object Model does support simultaneous connections to Oracle via OCI.
Oracle Spatial Support
To connect to Oracle Spatial within MapInfo, you must have the Oracle client installed. See your Oracle documentation for detailed information.
Geometry Conversion
The table below shows the translation from MapXtreme 2004 objects to Oracle Spatial
(SDO_Geometry).
From MapInfo
NULL geometry
Point
To Oracle
NULL
1 POINT
MultiCurve (with IsLegacyLine = true) 2 LINESTRING Geometry contains one line string
Polygon 3 POLYGON Geometry contains one polygon.
FeatureGeometryCollection 4 Collection Geometry is a heterogeneous collection of elements.
MultiPoint
MultiCurve
5 MULTIPOINT
6 MULTILINESTRING Geometry has multiple line strings.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
105
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 9: Accessing Data from a DBMS
From MapInfo
MultiPolygon
Ellipse
LegacyArc
Rectangle
LegacyText
RoundedRectangle
PieTheme, BarTheme
To Oracle
7 MULTIPOLYGON Geometry has multiple polygons.
NULL
NULL
NULL
NULL
NULL
NULL
The table below describes the translation from Oracle (GTYPES) to MapInfo Spatial objects.
From Oracle GTYPES
0 UNKNOWN_GEOMETRY (Spatial ignores this geometry.)
1 POINT Geometry contains one point.
2 LINESTRING Geometry contains one line string.
Point
MultiCurve
To MapInfo
3 POLYGON Geometry contains one polygon.
MultiPolygon
4 Collection Geometry is a heterogeneous collection of elements.
FeatureGeometryCollection
5 MULTIPOINT Geometry has multiple points.
6 MULTILINESTRING Geometry has multiple line strings.
7 MULTIPOLYGON Geometry has multiple polygons (more than one exterior boundary).
MultiPoint
MultiCurve
MultiPolygon
Multi Dimension Geometry Support (Greater than two Dimensions)
MapXtreme 2004 applications can read these data and map them as layers for
SDO_GEOMETRY columns containing geometries defined in more then two dimensions.
However, only the first two dimensions are used as the x and y.
SDO_GEOMETRY Arc and Circle Translation
Circles and circular arcs can be resolved to MultiCurves with a resolution of 25 segments per
360 degree circle.
Visualization of Non-translatable Oracle Objects
Oracle Spatial Objects that your MapXtreme 2004 application is unable to translate produces a
Point object with a default style (a black star) at the location of the SDO_Spatial point, or the first SDO_Spatial ordinate in the ordinate array. This is to enable a visual representation of the non-translatable object in the proper geographic area to which it belongs. Examples of nontranslatable objects are user-defined objects GTypes 0,4,5, or invalid sdo_geometries containing unrecognized GTypes, ETypes, or interpretations. The second class should also fail using sdo_validate_geometry().
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
106
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 9: Accessing Data from a DBMS
Centroid Support
A MapXtreme 2004 application uses the SDO_POINT as the centroid value for polygons. This centroid feature is used to position labels, and also affects the tool selection of the object. The
Oracle SDO_GEOMETRY.SDO_POINT_TYPE field (if not NULL) is interpreted as the feature centroid if the point exists inside the region. If the point exists outside of the region, its centroid is calculated as always.
Note:
There is currently no method or tool in MapXtreme 2004 to set the centroid of a region feature, but one may read and use a stored centroid.
Additional Information
The following sdo_geometry values are not always translatable to or from MapInfo objects format without data loss. Some geometry details could be lost if updated.
•
GTYPE 0 – User defined/unknown geometry
•
GTYPE 4 – heterogeneous collection of elements
These types are interpreted (when possible) as single point SDO_POINTTYPE values if not already NULL. They “grab” the first point in the ordered array which would be interpreted as a
NULL geometry.
Note:
Any other SDO_GEOMETRY values that contain circles or arc components are translated into line strings containing 25 lines per 360 degrees.
Oracle Spatial Reference Support (SRID)
An Oracle SDO_GEOMETRY column may be defined with a spatial referencing system. This is done by providing the Oracle SRID in the USER_SDO_GEOM_METADATA and also by assigning that SRID in the stored SDO_GEOMETRY values. If a table contains an Oracle
Spatial column with an assigned SRID, your MapXtreme 2004 application is able to query and properly interpret the data. The MapInfo_MapCatalog must contain the same MapInfo
Professional CoordSys string as indicated in the SRID of the data, since it is the Coordsys in the MapInfo_MapCatalog that is currently used to interpret and update the data.
If the Spatial column does not contain an SRID value, (the value is NULL), your MapXtreme
2004 application is also able to interpret the data via the MapInfo Professional Coordsys defined in the MapCatalog.
When loading tables that use the Latitude/Longitude coordinate system (Geodetic Data) to
Oracle Spatial, it is important to verify that all geometry coordinates are between (-180,180) longitude and (-90, 90) latitude. Geodetic data coordinates beyond that range are not supported in Oracle Spatial and may cause problems. You can check your data using MapInfo
Professional before loading, or use the Oracle Spatial SDO_GEOM.VALIDATE_LAYER() function on the table after loading it to Oracle Spatial.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
107
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Connection Dialog Workaround
Chapter 9: Accessing Data from a DBMS
For Oracle Spatial, there is no connection dialog that displays if you do not specify the complete connection string. The DLG= option has no effect. If you do not provide the userID and password, the connection fails. Since DBMS table .tab files created by MapInfo
Professional do not contain passwords, (for security reasons), this causes the open on the .tab files to fail.
A way around this is to write a simple connect dialog that gets the password from the user and creates a connection to the desired database using the DbmsConnectionCollection class
(accessible through the Catalog’s DbmsConnections property. An Oracle connection string should be specified as follows:
"SRVR=OracleSpatial9i;UID=user1;PWD=secret;"
DBMS Connection String Format
ODBC Connection String Format
The format of the ODBC connection string is defined by several clauses separated by semicolons (;). Each clause has the form Key=Value. Important keys are listed below.
Keyword
DLG=
DSN=
DRIVER=
UID=
PWD=
Description
A number that controls the display of the connection dialog box:
0 – Suppresses the connection dialog.
1 – Displays the connection dialog.
2 – Displays the connection dialog, but only if needed (i.e., if not all required information was provided) [default].
Note:
ASP.NET Applications which use Pooling must have a DLG=0 clause in the connection string for ODBC.
Specifies the ODBC data source name.
Caution: If you use the DSN= syntax key, the name that you specify must match the data source name in use on the user’s system. Note that different users might use different names to refer to the same data source. If you cannot know in advance what data source name to use, use the DRIVER= syntax key instead of the DSN= syntax key.
Specifies the exact driver name of the installed driver. Used instead of the DSN= syntax key.
Example:
DRIVER={SQL Server}
Note:
Informix 2.80.0861 does not support DRIVER=. Also, it does not apply to
Oracle Spatial.
Specifies the desired UserId for the data source, if required.
Specifies the user’s password for the data source, if required. Passwords do not need to be in the connection string for the two strings to match. If two tables are in the same database, the connection string is the same.
Note:
Connection attributes/parameters do not have to be in order and one may use a dialog to get a connection from an existing connection pool to avoid redundant connections.
In previous version of our API, if you used a dialog each time to connect to the same
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
108
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 9: Accessing Data from a DBMS
database, or if you did not order the connection keywords in the connection string in the documented order, the connection would not be shared and you would get multiple connections.
ODBC Layers and Pooling in Web Applications
When adding remote layers via ODBC to an ASP.NET application that uses pooling, be sure to have the DLG=0 clause in the connection string. This will avoid the display of unnecessary user and password dialogs that can time out. This applies to TAB files and workspaces. The following connection string example shows the highlighted DLG=0 clause.
<ConnectString>DRIVER={SQL Server};DATABASE=Devel;Server=Paladin;
UID=devel;PWD=devel;QuotedID=Yes;Trusted_Connection=No;
Network=DBMSSOCN;Address=PALADIN,1433;DLG=0</ ConnectString>
Oracle Spatial Connection String Format
These are the Oracle Spatial keywords. The string is defined by several clauses separated by semicolons (;). Each clause has the form Key=Value. Important keys are listed in the table below.
Keyword
SRVR=
Description
Reflects the service name for the server set in the Oracle Net8 EasyConfig utility. This is required for Oracle connectivity, but does not apply to ODBC connections.
UID= Specifies the desired UserId for the data source, if required.
PWD= Specifies the user’s password for the data source, if required.
Sample Connection Strings
Here are sample connection strings for the Oracle Spatial, IUS/UDO, and SpatialWare ODBC drivers.
Oracle Spatial connection string:
UID=george;PWD=password;SRVR=OracleSpatial9i
IUS/UDO connection string:
DRIVER={INFORMIX 3.81 32 BIT};UID=informix;PWD=secret;DATABASE=sw;
HOST=HostName;SERVER=ServerName;SERVICE=sqlexec;PROTOCOL=onsoctcp;
SpatialWare for SQL Server string:
DRIVER={SQL SERVER};
SERVER=ServerName;VID=Troll;PWD=secret;Database=GEORGETOWN
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
109
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 9: Accessing Data from a DBMS
Defining Mappable Tables in Server Table Queries
The query you specify for a server table defines the result set of data from your DBMS that represents the data in the table being added. You can formulate a fairly complex query to do powerful server-side analysis that defines a mappable table in MapXtreme 2004. Your
MapXtreme 2004 application uses this query internally to access the data.
MapXtreme 2004 generates several internal queries based on your query to access the data in a map as well as selection/key based queries. The table from which the geometry column is selected must be registered in the MapInfo MapCatalog on the server. MapXtreme 2004 requires this to obtain certain metadata about the geometry column such as the coordinate system, spatial type, and default styles.
In order for a query to define a mappable table, the query must contain both a geometry column and a key column. Sometimes for more complex queries on small sets of data (where the spatial indexing or spatial predicate cause the query to fail), you can specify
TableInfoServer.MbrSearch=false
to enable the results to be mapped.
The Geometry Column
If you do not specify a geometry column that your MapXtreme 2004 application can recognize, the table is opened, but cannot be added to a map (the table is unmappable). MapXtreme 2004 determines the geometry column of the table by looking it up in the MapCatalog and by examining the result set datatype of the column. You can reference the geometry column generically via the pseudo column name “OBJECT”, or you may refer to the geometry column using its specific column name. This form is required to reference the geometry column for an
X/Y mappable layer. You can specify a geometry column via any server-supported geometry function/expression.
Example
Select OBJECT from rdbsdata
Select sw_geometry from rdbsdata select sw_member, ST_Buffer(geometry, 66.0, 0.1) from rdbsdata
// a geometry function
Select st_geometry(st_point(72.5, 42.5.) from rdbsdata
// a geometry constructor
Spatialware function examples:
select sw_member, ST_Buffer(sw_geometry, 66.0, 0.1) from rdbsdata select ST_Overlap(flood100.sw_geometry, lake.sw_geometry) from flood100, lake where ST_Overlaps(flood100.sw_geometry, lake.sw_geometry)
Oracle sdo_buffer example:
Select mi_prinx, mdsys.sdo_geom.sdo_buffer(geoloc, (select diminfo from sdo_geom_metadata where table_name = 'ALINE'), 20) from aline where prinx =
1
Oracle constructor example:
Select 1 "mi_prinx", mdsys.sdo_geometry(3,null,null,mdsys.sdo_elem_info_array(1,3,3), mdsys.sdo_ordinate_array(-79.919909,40.553465,-71.060457,45.363657)) from dual
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
110
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 9: Accessing Data from a DBMS
The Key Column(s)
A key column(s) must be returned in the query to enable it to be opened as a table. This is what enables your MapXtreme 2004 application to identify each row in the result set to perform shading, selection, and label operations on the layer.
The key column does not need to be specified in the query in most cases.
Your MapXtreme 2004 application can look up and determine the best key column(s) to use in order to uniquely reference a row in the result set, and then add them to the query if they are not present. In most cases, this is the primary key/unique index.
For Oracle Spatial tables, the MI_PRINX may be used.
For some queries, it is not possible for your MapXtreme 2004 application to identify the key.
This is the case in a query on a view or a synonym. The view or synonym must appear in the
MapInfo MapCatalog. They also must be registered as required with the underlying Spatial index system in most cases. Since MapXtreme 2004 cannot determine the key on these, a mechanism is provided to allow the application developer/query writer to identify the key column in the result set. The key must be a single column and must be a distinct value in the result set. To identify the column that is to be used as the key column, you can specify column alias of prinx or mi_prinx, (e.g., select custid mi_prinx, ccustname, object from mycust
).
Example
Select customer_id mi_prinx, obj, from customer_view
The column alias “mi_prinx” is used to identify and use the customer_id column as the key column for the table. You can alternately alias the desired key column in the create view statement to identify the key column automatically for any query on that view.
Example
Create view customer_view as select customer_id mi_prinx, geloc from customer
In general, if a column name or column alias of prinx
, or mi_prinx
is found in the result set, that column is used as the key column for the table. This enables the application/query writer to specify the key column they desire.
Accessing Attribute Data
To use all available data columns, specify a query such as
Select * From tablename
. You are not required to specify
*
(asterisk); instead, you can designate specifically which columns you want to use. For the best performance, limit your query so that it retrieves only the needed columns.
When you add a DBMS table, for performance sake, you should only specify the columns in the query that you intend to use in your application. These are the spatial column, the key column(s), which are added automatically if you do not specify them, and columns you want to label with, or create a theme from. You may use the pseudo columns “OBJ” for any mappable table to refer to the column(s) containing the spatial data. This is required for a table using the
MapMarker MDIGEOADDRESS column on a table with an X/Y column.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
111
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 9: Accessing Data from a DBMS
You can use any server side expression/function to specify a column. Also, avoid select * from tab in a real application.
The following code example defines a server table using a TableInfoServer and adds a layer to a map using this definition. You can now label or place themes based upon the columns in this table.
// Create a TableInfoServer with the desired settings
TableInfoServer tiServer = new TableInfoServer("StatesOnOracle"); tiServer.ConnectString = "SRVR=ontario;UID=mapx;PWD=mapx"; tiServer.Query = "Select * From States"; tiServer.Toolkit = ServerToolkit.Oci;
// Create maploader
MapTableLoader tl = new MapTableLoader(tiServer);
// Load tables into map map.Load(tl);
Performance Issues
Establishing a connection with the database server may take several seconds. This is a onetime cost, incurred when the table is first opened.
The map-display speed depends on how much data is retrieved from the server. In some cases, displaying a map from a server is noticeably slower than displaying a map from a local file. Speed also depends on whether your MapXtreme 2004 application has already cached the map features that are being displayed.
Working with the Cache
Knowing how to work with Cache in MapXtreme 2004 enables you to improve your application’s performance. The sections below describe what the Cache is, how it works in the
MapXtreme 2004 object model, and the CacheSettings property of the TableInfoServer object.
What Is the Cache?
In place of local files, applications can access MapXtreme 2004 features from a remote database. In place of reading these records from the database each time the map needs to be acted upon, your MapXtreme 2004 application can temporarily store these records in the cache. This limits the number of calls between the application and the remote database.
Records in a server table can be cached to improve the performance of your application (e.g., drawing, thematics, labeling, etc.). Server table data is cached internally as it is read and drawn to the Map window. All subsequent redraws read from this cache instead of going to the server database for the same data. The cache is able to offer significant redraw performance improvement.
There are several settings that developers can use to customize cache usage. The cache can be enabled (or disabled) when the server table is added by specifying the values for the
CacheSettings property of the TableInfoServer object and is On by default.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
112
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 9: Accessing Data from a DBMS
How the Cache Works
For each record that is cached, each attribute data value is stored in memory and each feature object is stored on disk in a temporary Rtree file. For tables with a lot of records and/or a large record size (for example, number of bytes per record for the attribute data), caching may use a significant amount of memory. If an application tries to cache too much data, too much virtual memory usage may be required, which can degrade performance. Applications should be selective about how the cache is utilized. MapXtreme 2004 offers a variety of mechanisms for controlling the cache.
The TableInfoServer Object and the CacheSettings Property
When a table is added to the map, the cache is enabled by default but can be further configured using the CacheSettings property of the TableInfo object. This property has four possible values: ON, OFF, ALL, USER, with ON being the default.
Parameter
OFF
ON
Description
A value of 'Off' means that the table will not use the cache at all. All data operations will go directly to the database server.
Caching is enabled and the table automatically performs caching based on the map view (center/zoom). The user may additionally control the cache through the cache constraint objects.
The cached table maintains the record cache in a fashion that best improves standard map operations. The cache is maintained to contain, at a minimum, all the records displayed in the current window of each Map the table is in (and visible). Once an initial map window has been cached, pan and zoom operations that fall entirely within the initial extents of the cache access the cached records and do not need to query the database. If a pan/zoom operation falls outside the cached region, the table adds the new map window MBR (view) to the cache and obtains the missing records from the database server and adds them to the cache. The old map view is not initially discarded; rather, an internal history of previous map views is maintained. To avoid having a cache that grows excessively large, there are controls that can be placed on the table's cache to determine when to discard old cached views (map window MBR regions).
These controls are properties of the CacheParameters object, which can be set at the time the table is initially opened. This allows the developer to set limits on the maximum amount of memory or disk space used by the cache, the maximum number of previous map window views to maintain in the history, the maximum number of records to maintain in the cache, and/or the maximum amount of time old map window views are allowed to remain in the cache history. These limits can be used individually or in combination to provide the cache management that best suits the application's needs.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
113
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 9: Accessing Data from a DBMS
Parameter
USER
ALL
Description
A value of USER for the LayerInfo CACHE parameter means that your application creates a cache, but the only records that are placed in the cache are those specified by the application developer. The mechanisms available for specifying which records are placed in the cache are BoundConstraint, FeaturesConstraint, and AllFeaturesConstraint objects. The word constraint implies that these objects are constraining the cache to include the specified records. The BoundsConstraint object can be used to place all records into the cache for which the MBR of the feature intersects the MBR of the constraint.
A FeaturesConstraint object can be used to add specific records to the cache. For example, if an analysis is going to be performed that involves multiple steps and/or reads of the Feature or RowValues of the feature, possibly on a set of features returned from a Layer.Search, Layer.SearchWithinDistance, etc., it may be advantageous to place these records into the local cache for the duration of the analysis and remove them when finished. The FeaturesConstraint provides this capability. If an application is going to perform an analytically intensive operation that may hit every record, it may be desirable to temporarily cache the entire set of data for the layer. This is accomplished by using the AllFeaturesConstraint. These cache constraint objects can also be used when the cache is set to ON. In this case, they may add records to the cache but have no effect on the cache's history of previous map window views. The constraint objects can also be used when the cache is set to OFF or ALL in which case they have no effect.
Note:
The constraint objects have no effect on non-server tables.
The entire table is cached. With this option, the table's data is retrieved from the server once and accessed locally from that point forward. To refresh the data in the cache, use the Refresh method on the table.
If you try to cache too much data or too many tables, virtual memory usage may be forced, and performance gain could be lost.
The MapInfo MapCatalog
In order to display data on a map, your MapXtreme 2004 application needs to access a special table, known as the MapInfo Map Catalog. One catalog must be created per database before any tables in that database can be viewed as a map layer in a MapXtreme 2004 application.
The Map Catalog must contain information about the spatial columns in each of the mappable tables you want to access from the database. The MapInfo EasyLoader utility automatically inserts the appropriate row into the MapInfo Map Catalog when the table is uploaded into the database.
Your application can use a Map Catalog that already exists on the server. (This same catalog is shared by various MapInfo client applications). If there is no Map Catalog on the server, you need to create one. Mapxtreme 2004 supports the storage of style information for individual features in remote databases.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
114
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 9: Accessing Data from a DBMS
Loading Spatial Data to DBMS
If you have spatial data in the form of a MapInfo table, you can import that data into your DBMS database.
To load data into SQL Server SpatialWare, Informix IDS SpatialWare, and Oracle Spatial, use the MapInfo EasyLoader, that is distributed with MapInfo Professional and available for download from
http://www.mapinfo.com
. The EasyLoader utility automatically creates a map catalog when you upload a table. if there is no map catalog already present.
Manually Creating a MapInfo MapCatalog
If you are not a MapInfo Professional or EasyLoader user, you will need to create the
MapCatalog (or have your database administrator create the MapCatalog) manually, as described below. You only have to create the MapCatalog once per server/database.
1.
Create the user MAPINFO in the specific database where the mappable tables are located.
2.
Create the table MAPINFO_MAPCATALOG in the database. The Create Table statement needs to be equivalent to the following SQL Create Table statement:
Create Table MAPINFO_MAPCATALOG (
SPATIALTYPE Float,
TABLENAME Char(32),
OWNERNAME Char(32),
SPATIALCOLUMN Char(32),
DB_X_LL Float,
DB_Y_LL Float,
DB_X_UR Float,
DB_Y_UR Float,
COORDINATESYSTEM Char(254),
SYMBOL Char(254),
XCOLUMNNAME Char(32),
YCOLUMNNAME Char(32),
RENDITIONTYPE INTEGER,
RENDITIONCOLUMN CHAR(32),
RENDITIONTABLE CHAR(32)
NUMBER_ROWS INTEGER
)
Note:
It is important that the structure of the table looks exactly like this statement.
The only substitution that can be made is for databases that support varchar or text data types; these data types can be substituted for the Char data type.
3.
Create a unique index on the TABLENAME and the OWNERNAME, so only one table for each owner can be made mappable. create unique index mapcat_i1 on mapinfo.mapinfo_catalog (OwnerName,TableName)
4.
Grant Select, Update, Insert, and Delete privileges on the MAPINFO_MAPCATALOG.
This allows users to make tables mappable. grant select, insert, update, delete on mapinfo.mapinfo_mapcatalog to public
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
115
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Adding Rows to the Map Catalog
Chapter 9: Accessing Data from a DBMS
For each spatial table that you want to access from your application, you need to add a row to the MAPINFO_MAPCATALOG table. If you do not use MapInfo Professional to manage the
Map Catalog, you will have to add rows to the MAPINFO_MAPCATALOG table manually. The following table describes the syntax and meaning of each column:
Column Name
SPATIALTYPE
TABLENAME
OWNERNAME
SPATIALCOLUMN
DB_X_LL
DB_Y_LL
DB_X_UR
DB_Y_UR
Values to Assign Examples
MapInfo Spatial Object Format
1
: Point layer in X/Y columns indexed with micode (a serialized quadtree key)
4
: Point layer in X/Y columns
5.
x: SpatialWare for Oracle
6.
x: Ingres SOL - Not Supported
7.
x: Sybase SQS - Not Supported
8.
x: Oracle SDO version 2 - Not Supported
9.
x: MapInfo Geocoding DataBlade
SpatialWare Point Module
10.
x: MapInfo Geocoding DataBlade XY Module
11.
x: SpatialWare IDS/UDO datablade
13.
x: Oracle Spatial
14.
x: SpatialWare for Microsoft SQL Server
Spatial Object Type
x.0: Points only x.1: Lines only x.2: Regions only x.3: All types supported
Note:
This column describes the Spatial Object
Format of how the data is stored and indexed and the Spatial Object type(s) supported and not supported in the column.
The digits to the left of the decimal point are the Spatial Object Format. The digits to the right represent the type of Spatial Object
Type that can be stored in the column
5.0 = Oracle
5.1
5.2
5.3
The name of the table.
The owner name of the table.
STATES
BOB
The name of the column, if any, containing spatial features:
SW_GEOMETRY
(mappable using SpatialWare Type/IDS/UDO)
NO_COLUMN
(mappable using X–Y)
MI_SQL_MICODE
(mappable using MI Code) Or the name of the IDS/UDO, or Oracle column that is
ST_SPATIAL datatype.
Name of the Oracle SDO_GEOMETRY column.
SW_GEOMETRY
The X coordinate of the lower left corner of the layer’s bounding rectangle, in units that are indicated by the COORDINATESYSTEM (see below).
–360
The lower left bounding Y value.
The upper right bounding X value.
The upper right bounding Y value.
–90
360
90
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
116
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Column Name
COORDINATESYS-
TEM
SYMBOL
XCOLUMNNAME
YCOLUMNNAME
RENDITIONTYPE
RENDITIONCOLUMN
RENDITIONTABLE
Chapter 9: Accessing Data from a DBMS
Values to Assign
A string representing a MapInfo CoordSys clause
(but without the keyword CoordSys at the very start), which specifies a map projection, coordinate units, etc. For simple Lon/Lat maps, specify Earth
Projection 1, 0
.
Examples
Earth Projection 1, 0
A MapInfo Symbol clause (if the layer contains only points); or a Symbol clause followed by a Pen clause
(indicating styles for linear features) followed by another Pen clause (indicating styles for the borders of regions) followed by a Brush clause.
Symbol(35,0,12)
Pen(1,2,0) Pen(1,2,0)
Brush(2,255,255)
For the X/Y mappable tables, specify the name of the column containing X-coordinates. If there is no such column (i.e., if this table uses a single spatial column instead of a pair of X-Y columns) then specify
NO_COLUMN
or leave empty.
NO_COLUMN
For the X/Y mappable tables, specify the name of the column containing Y–coordinates, or specify
NO_COLUMN
NO_COLUMN
This indicates how the object style information is applied.
0
– Indicates that all the objects will have the style specified in the symbol field of the Map.Catalog applied to them.
1
– Indicates that the table has a separate column which contains a string representation of the style information for each object in the table (e.g., each object may have its own style).
0
or 1
If RENDITIONTYPE is 1, this field stores the name of the column in the spatial table (identified by the
TABLENAME) that contains style information. This column is automatically added to any query against the table and is maintained (updated) as the object is updated. Users should NOT specify this column in their queries as problems can occur with intersect or update statements. Queries which include this column in the select clause (excluding the wildcard character “*”) may access the values through the
Dataset object. Rows with a NULL value in their style column will have the style from the SYMBOL field of the MapCatalog applied to the object.
MI_SYMBOLOGY
Currently not used, but reserved for future use, this column must exist in order for MapXtreme 2004 to correctly identify and apply record-level styles.
NULL
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
117
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 9: Accessing Data from a DBMS
Symbol, Pen, Brush Clause Syntax
If you are manually creating a MAPINFO_MAPCATALOG table to provide support for a remote spatial database, you will need to specify a symbol style, and possibly line and fill styles as well.
Specifying Point Styles
Use a Symbol clause to specify point styles. There are three types of Symbol clauses: one for specifying MapInfo 3.0-style symbols; one for specifying TrueType font symbols; and one for specifying bitmap symbols.
Symbol Syntax
Symbol(shape, color, size) or
Symbol(shape,color,size,font,fontstyle,rotation) or
Symbol(bitmapname,color,size,customstyle)
Example
Symbol(35,0,12)
Symbol
(64,255,12,"MapInfo Weather",17,0)
Symbol("sign.bmp", 255, 18, 0)
Specifying Line Styles
Use a Pen clause to specify line styles. In a Map Catalog, you may need to specify two pen clauses: one to specify the appearance of linear features, and another to specify the appearance of region borders.
Pen Syntax
Pen(thickness, pattern, color)
Pen(1, 2, 0)
Specifying Fill Styles
Use a Brush clause to specify the style for closed features (regions).
Example
Brush Syntax
Brush(pattern,color,backgroundcolor)
Example
Brush(2, 255, 65535)
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
118
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Per-Record Styles
Chapter 9: Accessing Data from a DBMS
Per-record style support brings a feature to spatial database implementations that has long been available in MapInfo TAB files. Specifically, it allows each geometry in a single table to have its own style. For example, a single 'public institution' table in Oracle Spatial can have schools, town halls, libraries, and police departments and each point type would be represented with its own symbol (i.e., a school symbol for all the schools). Similarly, a single road table in SpatialWare SQL Server may have different road types such that streets are shown as a single pixel black line, secondary roads as a double pixel red line and interstates as parallel red lines. Per-record styles can be activated for a table through the entry in the
MapCatalog according to the following table:
Column
RENDITIONTYPE
RENDITIONCOLUMN
RENDITIONTABLE
Data Type
INTEGER
VARCHAR(32)
VARCHAR(32)
Description
Numeric indicator of the table’s per-record rendition type. Valid values are:
0: No per-record styles are in effect for the indicated table. Objects will be read/updated as before using the default style for the table.
1: The indicated table uses The indicated table uses per-record styles. The column in the table which contains the style is recorded in RENDITIONCOLUMN and it contains a MapBasic string (e.g., the same format that is currently used in the Map Catalog’s SYM-
BOL column).
This column contains the name of the column in the indicated table which holds the object style value (for a rendition type of 1).
Presently this column is not used, however, it must be present before your application properly detects the existence of this new feature. A future enhancement has been proposed to have the styles managed in a separate table and to have the value in the column identified by the RenditionColumn contain a key that can be used to look up the style in the table identified by this attribute. This functionality is not implemented.
Note:
If these columns are not present, object styles will continue to work as before (e.g., the table’s default style will be applied to all objects).
Known Limitations/Requirements
LegacyText objects have their own way of displaying style that is separate from the use of the
MI_Style column. Therefore any form of text object needs to be treated differently than other objects. The style for any text object is embedded and a NULL value is inserted into the style column.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
119
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Troubleshooting
Chapter 9: Accessing Data from a DBMS
If you encounter problems with your SpatialWare or Oracle applications, use the following table to help analyze and solve the problem.
Problem Description
The table is not matchable.
No object was found using the index that you specified.
Map appears to have incorrect zoom level. For example, the map may be zoomed out too far to identify any geography.
Possible Cause Solution
Data binding was attempted against a SpatialWare layer.
A query was made against a table that does not exist.
AddColumns is not currently supported for SpatialWare layers.
Check that the table name is correct and in the proper case.
Also, the table may need to be mappable.
No spatial object is contained in the result of the spatial query.
Use the EasyLoader Upload utility to make the table a mappable table.
A query was made against a non-spatial table.
The MBR for a DBMS layer is determined by the
MapInfo_MapCatalog table.
The table extents in the Map-
Catalog result in a different zoom level than the one you desire for your output.
Check the query for possible syntax errors. Also make sure that the result of the query includes the field specified in the spatial column in the
MapInfo_MapCatalog.
Edit the extents (DB_X_LL,
DB_X_UR, DB_Y_LL,
DB_Y_UR) in the
MapInfo_MapCatalog using the
MapInfo Professional MDX tool,
MISETMBR.MDX.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
120
MapXtreme2004_DevGuide_A4.pdf
Finding Locations
10
The MapInfo.Data.Find namespace contains the classes to use when searching for map features by address, street intersection or name.
In this chapter:
!
!
!
Developer Guide
Functional Overview of Find
Chapter 10: Finding Locations
Find is used when you wish to locate map features by address, street intersection or name. To find features at locations using selection tools or queries, use the Search classes in the Data namespace (see
Searching for Features in Chapter 8 on page 89
).
A successful Find operation can result in an exact match, one or more close matches, or no match (failed match). The operation is controllable by a variety of properties and fallback options and are discussed in the
Overview of the Data.Find Namespace on page 124
section below describes how MapXtreme 2004 makes a match. The more you understand the
Find process, the more you can control the success of the operation.
The Find Process
MapXtreme 2004 locates map features by matching an address, street intersection or place name with information in the feature table. For example, you can find 1600 Pennsylvania
Avenue in Washington, D.C. provided a table of Washington D.C. streets is open.
Finding a map feature is similar. For example, you can find The White House if you have a mappable table of landmarks that contains the name “The White House” and its geo-referenced
(mappable) location. You don’t need to supply the address to find by place name.
To find a street intersection you must provide both street names that make up the intersection.
MapXtreme 2004 attempts to find an exact match in which the result is a character by character match to the input address, place name or intersection. If it cannot make an exact match,
MapXtreme 2004 attempts to find close matches based on its matching rules and your settings.
If it cannot find a close match, it returns a failed match. Note that matching is not casesensitive. Upper and lower case characters are successfully matched with one another.
A street address is normally made up of a street number, name and abbreviations that represent the street prefix, such as North, and suffix, such as Road. Addresses can take a variety of forms and may include additional information such as apartment number or route. In addition, some of the key components like street type may be missing from the input address.
MapXtreme 2004 looks at each component of the address and applies specific rules to it to find a match.
The following sections describe how MapXtreme 2004 handles specific information and conditions including street name, street abbreviations, address numbers, refining tables and results.
Matching to Street Name
A match to a street name is a straightforward character by character evaluation of the address against the information in the search table. For example, MapXtreme 2004 returns an exact match for the street name LaSalle if LaSalle is in the table, but may only return a close match if the address is spelled La Salle or LaSal.
Matching to Street Abbreviations
Street abbreviations vary widely in address records. Sometimes the component is missing altogether. In many cases, however, MapXtreme 2004 can make an exact match even if there are slight differences between the address and the search table. MapXtreme 2004 refers to a standardized address abbreviation and substitution list, called Mapinfow.abb, to find a suitable
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
122
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 10: Finding Locations
match. This list contains standard spellings of street prefix and suffix abbreviations, such as ST for Street and Av for Avenue. You must set a property to tell MapXtreme 2004 to use this abbreviations file, but it is a good way to increase the chance of exact matches or find more close matches than without the file.
The table below illustrates variations in address and whether or not it will result in an exact match based on the use of the abbreviations file. The first column contains a street name you want to find. The second column contains the corresponding street name from a source table.
The third column says why they do not match. The fourth column indicates whether the particular problem is one that can be corrected by using the abbreviation equivalence file. This table assumes that the addresses are the contents of a single column in a table. While the street number would often be in the same column, we don’t indicate street numbers here because they are handled differently than street names.
Address to Find
LaSalle Street
LaSalle Ave
LaSalle Ave
LaSalle
Search Table
Address
LaSalle St
LaSalle Av
LaSalle St
LaSalle St
LaSalle St North
LaSalle St North
LaSalle St Apt 3
LaSalle St
LaSalle St N
LaSalle St
Tenth St 10th St
10th Av Tenth Av
Saint John’s Lane St John’s Lane
Comment
“Street” and “St” do not match.
“Ave” and “Av” do not match.
“Ave” and “St” do not match.
“St” is missing from target.
Correctable with
Abbreviation File for an Exact Match
Yes
Yes
No
No. If the street abbreviation is missing, MapXtreme 2004 does make a guess on what it could be.
“North” is not in the search table.
No
“North” and N do not match.
Yes
Apartment number does not match anything in the source.
Yes. The apartment number is ignored.
“Tenth” and “10th” do not match.
Yes
“10th” and “Tenth” do not match.
Yes
“Saint” and “St” do not match.
Yes
If you find that you have repeated situations that do not match due to abbreviations, you can:
•
Edit your addresses to conform closer to the abbreviations file, or
•
Edit the abbreviations file with a text editor to add your specific abbreviations. The mapinfow.abb is located in C:\Program Files\Common Files\MapInfo\MapXtreme\6.0.
For more information about editing the abbreviations file, see
Matching Address Numbers
MapXtreme 2004 can match when the address number precedes the street name (as in North
American addresses) or when it follows the street name (common in European addresses). By default MapXtreme 2004 assumes the address number precedes the street name. You must set a property when the address number follows the street name.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
123
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 10: Finding Locations
MapXtreme 2004 compares the input address number to a range of address numbers.Typically the table contains address number ranges that correspond to the portion of the street the range covers. Address ranges can be matched to the exact side of the street, since often address ranges are odd-numbered on one side of the street and even-numbered on the other.
In cases where MapXtreme 2004 cannot match the address range exactly, you may be willing to settle for a close match in which the closest range would be considered a match. You would use the stricter exact match requirement only for very precise finds. Often that level of precision isn’t necessary. A close match is usually acceptable.
Matching with a Refining Boundary Table
MapXtreme 2004 can also find an address in one table in which there may be more than one possible match. To avoid finding the wrong address, you specify a refining table and column to focus the match to a smaller area.
This is useful, for example, when searching a table of streets that cover an entire county and you are looking for Main St. It’s likely that more than one town in the county will have a Main St.
By providing a refining table of town boundaries, you can specify that you are looking for the
Main St. only in Town A.
You can use any type of refining boundary table you wish, for example, postal code boundaries or census regions. Additionally, you can specific a second refining boundary in which to conduct a Find.
Find Results
MapXtreme 2004 returns either an exact match, one or more close matches, or a failed match.
The results depend on a number of factors including the quality of the input data and the conditions set for the operation. Information is also returned that explains how well each portion of the address matched (or failed to match).
Overview of the Data.Find Namespace
The MapInfo.Data.Find namespace contains classes that enable you to locate a map feature, street address, or street intersection within a mappable table. The properties and methods of the Find class are used to set up a Find. The results of a Find are returned using the
FindAddressRange, FindCloseMatch, and FindResult classes.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
124
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
The following UML diagram illustrates the Find namespace.
Chapter 10: Finding Locations
Find
The Find object is used to locate a map object, street address, or street intersection within a given mappable table. Find searches the table for a match and returns the result(s) in a
FindResult object.
To use Find in MapXtreme 2004, you must have:
•
A mappable table (a table that contains geometry objects)
•
An indexed column on which to perform the search
•
An item to search for, such as a place name, street address or street intersection
•
Optionally, a refining table in which to narrow the search to a more specific location.
The Find class provides a number of properties to control the search operation. For example, you can limit the number of close matches to be returned (CloseMatchesMax) or indicate that you wish to use the abbreviation file for increasing the likelihood of a match
(UseAbbreviations).
The Find class provides four search methods: two for searching addresses or features with or without a refining boundary, and two for searching street intersections with or without a refining boundary.
Property Description
AddressNumberAfterStreet Specifies whether the address number is located after the street name
(for example, “Smith Street 107”).
ChooseAlternateBoundary Specifies whether to match a record found in a refining region other than the refining region specified.
ChooseClosestAddress-
Range
Specifies whether to use the closest available address number in cases where the address number does not match.
CloseMatchesMax match is not found.
Specifies how many close matches to return if an exact match is not found.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
125
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Property
InsetDistance
InsetPercentage
InsetUnit
OffsetDistance
OffsetUnit
UseCloseMatches
Chapter 10: Finding Locations
Description
A positive value representing how far from the ends of the line to adjust the placement of an address location.
Represents the percentage of the length of the line where the address is to be placed.
Represents the distance unit to use for Inset.
Representing the distance to offset the placement of an address location back from the street.
Represents the distance unit to use for Offset. are used to find a match (for example, “Smith Street” is substituted with
“Smith St”).
Specifies whether to return “N” number of close matches if an exact match is not found.
Search
Method
SearchIntersection
Description
Searches a mappable table for a named location and returns a Find-
Result object.
Searches a mappable street table for a given intersection, returning a
FindResult object.
Find.Dispose method
Releases unmanaged resources held by the Find object. It is necessary to call this method when finished with the Find object.
Code Sample
The following code sample is based on the Find sample application provided with MapXtreme
2004. The sample application is located in the C:\Program Files\MapInfo\MapXtreme\6.0\
Samples\Features\Find directory.
// Here we declare the tables and columns to be used in our
// Find operation.
Table _searchTable;
Table _refiningTable;
Column _searchColumn;
Column _refiningColumn;
FindResult _result;
// Here we declare our Find object.
Find find = null;
//Here we define the table that contains the locations we want to find.
_searchTable = Session.Current.Catalog.OpenTable("US_CNTY.TAB"); if (_searchTable == null)
return false;
// Here we define the table that will narrow our search if our search
// table has duplicate named locations it might find.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
126
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 10: Finding Locations
_refiningTable = Session.Current.Catalog.OpenTable("USA.TAB");
// Here we define the column in the search table that contains the
// location we want to find. In this case we will be looking for
// particular county from a table of all counties in the United States.
Columns columns = _searchTable.TableInfo.Columns;
_searchColumn = columns["County"]; if ( _searchColumn == null)
return false;
// Here we define the column in the refine table that contains the
// location we want to use to narrow our search in the
// cases where we find non-unique county names. In this case duplicate
// counties will be further determined by the state
// they are in. This refining column gurantees a unique result.
columns = _refiningTable.TableInfo.Columns;
_refiningColumn = columns["State"];
// Here we create our find object. Here we are defining it to find
// counties in a table of US counties and if we find
// duplicate county names, return the one unique to a particular state.
find = new Find(_searchTable, searchColumn, _refiningTable, refiningColumn);
// Here we set some properties of the Find object. These properties
// define what to do if the result of our search is an inexact match.
// Here we say to return up to six close matches if no exact matches.
// Close matches refer to the name and are helpful in the case of
// misspellings, e.g., searching for Albny, NY would return Albany, NY.
find.UseCloseMatches = true; find.CloseMatchesMax =6;
// Here we perform the search on our Find object. The Search method
// returns a FindResult object. This object contains properties that
// describe the results of the Search operation. If the operation was
// successful you could use the FindResult.FoundKey property to get a
// key to the row in your search table that is the result of your
// search operation. Or you can uses as we do here the the FoundPoint
// property to get the point location of your successful match.
if ( _refiningTable != null && _refiningTable.IsOpen )
{
_result = find.Search("Albany", "NY");
} else
{
_result = find.Search("Albany");
} if (( _result.ExactMatch)
&& (_result.NameResultCode.Equals(FindNameCode.ExactMatch)
&& (_result.FoundPoint != null))
{
// We succeeded, display the point. (This function is in the Find
// sample application.) showPointOnSearchTableMap(_result.FoundPoint.X,
_result.FoundPoint.Y);
} else
{
// We failed to get an exact match but have close matches, enumerate
// through them.
string labelSearchResult.Text = _result.NameResultCode.ToString(); if ( find.UseCloseMatches )
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
127
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 10: Finding Locations
{ listBoxSearchResult.Visible = true;
FindCloseMatchEnumerator enumerator =
_result.GetCloseMatchEnumerator(); while ( enumerator.MoveNext() )
{
// This is in the Find sample application listBoxSearchResult.Items.Add(enumerator.Current.Name);
}
}
} find.Dispose();
FindAddressRange
The FindAddressRange object represents an address range item returned from the
Find.Search method. The FindAddressRange object is returned as part of the FindResult object when a street address is not found, the address number is not within the minimum/ maximum address ranges for a given street, or an address number was not specified.
Code Sample
public void GetAddressRangesOnStreetTable()
{
Table_table;
_table =
Session.Current.Catalog.OpenTable("North_Greenbush.tab");
{
Find _find = new Find(_table,_table.TableInfo.Columns[1]);
FindResult _findResult= _find.Search("Meadow Dr");
If ((!_findResult.ExactMatch) && (_findResult.NameResultCode ==
FindNameCode.ExactMatch)&& (findResult.AddressResultCode ==
FindAddressCode.AddressNumNotSpecified))
FindAddressRangeEnumerator _enum =
_findResult.GetAddressRangeEnumerator();
FindAddressRange _findAddressRange; int _iIndex = 0; while (_enum.MoveNext())
{
_findAddressRange = _enum.Current;
Console.WriteLine("_findAddressRange.BeginRange");
Console.WriteLine("_findAddressRange.EndRange");
_iIndex++;
} if(_table != null)
{
_table.Close();
_table = null;
}
}
} find.Dispose();
}
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
128
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 10: Finding Locations
FindCloseMatch
The FindCloseMatch object represents a close match item returned from the Find Search method. The object is returned as part of the FindResult object. A close match item is a returned match that closely matches the name of the requested search.
To use this feature, you must first set the UseCloseMatches and CloseMatchesMax properties of the Find object before you execute your search. For example if you tried to search for
“Washington Street,” and UseCloseMatches was set to true, a close match would be
“Washington Ave.”
Code Sample
public void CloseMatchesOnStreetTable()
{
Table _table;
_table = Session.Current.Catalog.OpenTable("Rensselaer.tab");
Find _find = new Find(_table,_table.TableInfo.Columns[1]);
_find.UseCloseMatches = true;
_find.CloseMatchesMax = 5;
FindResult _findResult= _find.Search("70 Washington"); if ((!_findResult.ExactMatch) && (_findResult.NameResultCode ==
FindNameCode.ExactMatchNotFound))
{
FindCloseMatchEnumerator _enum =
_findResult.GetCloseMatchEnumerator();
FindCloseMatch _findCloseMatch; int _iIndex = 0; while (_enum.MoveNext())
{
_findCloseMatch = _enum.Current;
Console.WriteLine(_findCloseMatch.Name);
_iIndex++;
}
} if(_table != null)
{
_table.Close();
_table = null;
} find.Dispose();
}
FindResult
The FindResult class returns information from the Find.Search method in the form of properties that explain what kind of match was made, as shown in the table below. If successful, the
FoundKey property contains the key of the object to be located. If successful, the FoundPoint property contains the point of the object located.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
129
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 10: Finding Locations
Property
AddressOutOfRange
Description
Specifies whether the address passed in was out of range.
AddressResultCode Identifies the result code for the address part of the search and returns a
FindAddressCode enumeration.
BoundaryResultCode Identifies the result code for the refining boundary part of the search and returns a FindBoundaryCode enumeration.
ExactMatch
FoundKey
Specifies whether an exact match was found.
Specifies the Key of the object that has been located.
FoundPoint Specifies the Point of the object that has been located.
IntersectionNotFound Specifies whether the intersection was not found.
MultipleMatches
NameResultCode
ResultCode
UseSubstitution
Specifies whether multiple matches were found.
Identifies the result code for the name being searched on and returns a Find-
NameCode enumeration.
If the Find results is an exact match, the value is one. If the Find results in an approximate match, the value is greater than one. If the Find fails to match the address, the result is a negative value.
Specifies whether a substitution was used from the abbreviation file.
FindAddressCode Enumeration
Identifies the result code for the address part of the search and is returned by the
FindResult.AddressResultCode property.
Note:
This result code should only be used when searching for a street or intersection.
Member Name
ExactMatch
SideOfStreetUndetermined
WithinMinMax
NotWithinMinMax
AddressNumNotSpecified
StreetsDoNotIntersect
NoMapObjectForRowMatched
Description
An exact match was found.
The side of the street was undetermined.
The address number was within minimum/maximum range.
The address number was not within minimum/maximum range.
An address number was not specified.
The streets do not intersect.
The row matched does not have a map object.
FindBoundaryCode Enumeration
Identifies the result code for the refining boundary part of the search and is returned by the
FindResult.BoundaryResultCode property. A refining boundary is used to distinguish between multiple features with the same name.
Note:
This result code should only be used when a region is being used to refine the search.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
130
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 10: Finding Locations
Member Name
ExactMatch
FoundInOneOtherRegion
FoundInMoreThanOneRegion
Description
An exact match was found.
The name was found in only one region other than specified region.
The name was found in more than one region other than the specified region.
NoRegionSpecifiedOneMatch No refining region was specified, and one match was found.
NoRegionSpecifiedMultipleMatches No region was specified, and multiple matches were found.
MultipleMatchesFound The name was found more than once in the specified region.
FindNameCode Enumeration
Identifies the result code for the name being searched on and is returned by the
FindResult.NameResultCode property.
Member Name
ExactMatch
SubstitutionUsed
Description
An exact match was found.
A substitution from the abbreviations file used.
ExactMatchNotFound An exact match was not found.
NoObjectNameSpecified No object name specified; match not found.
CloseMatch A close match was found.
Fine Tuning the Find Process
As we stated in the beginning of this chapter, the more you understand about how Find works, the better you can use its properties and your input information to improve the chances for a successful match. This section provides some help with developing strategies for improved results during a Find.
Editing the Mapinfow.abb File
The Mapinfow.abb file is an abbreviations and substitution file that ships with MapXtreme 2004.
This file can be used to improve the chances for a Find if the abbreviation in the input address can be found in the abbreviations file. This is covered in the section
. This section covers additional types of information you can include
in the file.
You can edit Mapinfow.abb in any text editor or word processor. Open the file and make your additions, adding keywords as necessary. Here is a standard version of the file:
!Version 3.0
FIRST
SECOND
1ST
2ND
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
131
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
THIRD
FOURTH
FIFTH
SIXTH
SEVENTH
EIGHTH
NINTH
TENTH
NORTH
SOUTH
EAST
WEST
ALLEY
AVENUE
AVE
BOULEVARD
BRIDGE
CIRCLE
COURT
DRIVE
EXTENSION
HIGHWAY
INTERSTATE
LANE
MOUNT
PARK
PARKWAY
PLACE
PLAZA
POINT
RAILROAD
ROAD
ROUTE
SAINT
SQUARE
STREET
STR
TERRACE
!EOLNOSPACE
,
;
#
!EOLSPACE
FLOOR
SUITE
"P.O. BOX"
!NOSPACE
.
\"
\!
\\
!SPACE
"STATE HIGHWAY"STHWY"
"N ST"NORTH ST"
"S ST"SOUTH ST"
"E ST"EAST ST"
"W ST"WEST ST"
"N AV"NORTH AV"
"S AV"SOUTH AV"
"E AV"EAST AV"
"W AV"WEST AV"
RT
ST
SQ
ST
ST
TER
MT
PK
PKWY
PL
PLZ
PT
RR
RD
BR
CIR
CT
DR
EXT
HWY
I
LN
E
W
N
S
AL
AV
AV
BLVD
3RD
4TH
5TH
6TH
7TH
8TH
9TH
10TH
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
132
Chapter 10: Finding Locations
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 10: Finding Locations
You can make additions to this file to take care of various problems. Most importantly, you can make several different kinds of additions. MapXtreme 2004 recognizes four classes of substitution items and it interprets these classes differently. Each class is preceded by the keyword used to identify it in the abbreviation file.
Space-delimited simple substitution
Simple truncation
Space-delimited truncation
Simple substitution
!SPACE
!EOLNOSPACE
!EOLSPACE
!NOSPACE
In order for MapXtreme 2004 to know how to interpret a line, or set of lines, in the abbreviation file, you have to precede the line with the keyword which indicates the appropriate interpretation strategy.
When all of the entries in the abbreviation file use the default interpretation, there is no need to precede any of them with a keyword. When there is no keyword at the beginning of the abbreviation file, MapXtreme 2004 will treat the initial entries as requiring the default interpretation. Once you add other types of substitution pairs, however, you have to start adding keywords.
Space-delimited Substitution
Space-delimited simple substitution is the default. What that means is this: MapXtreme 2004 compares spaced-delimited tokens in target addresses with the rows in the address file. A space-delimited token is a string of characters with a space before and a space after. For example, MapXtreme 2004 will match “Ave” with “Av” in “Park Ave” but it will not match “Avery
Blvd” to “Avry Blvd.” Both street names contain the string “Ave”. But that string is bordered by spaces only in “Park Ave”, not in “Avery Blvd.” In “Avery Blvd”, “Ave” is followed by “r”, not by a space.
All of the entries in the abbreviation file will receive this default interpretation. You can add other items to receive the same treatment. For example, you might want to add the pair “WK WALK” so that MapXtreme 2004 knows to interpret “WK” in a target address as though it were “WALK”.
Similarly, you might want to add a pair such as: “WAY WY”.
Use the keyword “!SPACE” to indicate space-delimited simple substitution. Entries following
“!SPACE” are given the default interpretation (this allows you to arrange the Abb.file contents in some other order). When MapXtreme 2004 encounters another keyword, it switches to the indicated interpretation strategy.
Simple Truncation
In simple truncation, MapXtreme 2004 finds an item in the address and simply ignores it and everything after it. These items do not have to be space-delimited. This strategy is useful for dealing with addresses such as:
123 Appian Way, Mail Stop 829
7305 Van Zandt # 23
In the first case, you want MapXtreme 2004 to ignore the comma and everything after it. In the second case you want MapXtreme 2004 to ignore the number sign and everything after it. To deal with such cases add the following to your abbreviation file:
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
133
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 10: Finding Locations
!EOLNOSPACE
,
#
“!EOLNOSPACE” is the keyword indicating that the following items are to be treated as cases of simple truncation. After that we have one line with a comma and one with a number sign.
Whenever MapXtreme 2004 encounters a comma or a number sign in an address it will ignore it and everything after. The examples become:
123 Appian Way
7305 Van Zandt
Space-Delimited Truncation
In space-delimited truncation MapXtreme 2004 looks for items which are space delimited and eliminates those items and everything following. For example:
73 Appian Way Suite 829
3033 Van Zandt Room 202
To deal with such cases add the following to your abbreviation file:
!EOLSPACE
SUITE
ROOM"
!EOLSPACE” is the keyword indicating that the following items are to be treated as cases of simple truncation. After that we have one line with “Suite”and one with a “ROOM”. Whenever
MapXtreme 2004 encounters those tokens it will truncate the address. The examples become:
73 Appian Way
3033 Van Zandt
Simple Substitution
MapXtreme 2004 uses simple substitution to remove items from an address and otherwise does nothing. Use it to deal with:
433 Van-Rensselaer
91 St Albans’
The goal is to strip out the hyphen and the apostrophe. Make the following entries to the abbreviation file:
!NOSPACE
–
’
“NOSPACE” is the keyword calling for simple substitution, and the hyphen and apostrophe on the following lines are the tokens to be removed. The examples become:
369 VanRensselaer
91 St Albans
Legitimate Spaces
There are cases where you want to indicate a substitution in which the searched for string contains spaces. You can use double quotes in such cases. Place a double quote:
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
134
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 10: Finding Locations
•
at the beginning of the line; and
•
between the searched for string and the substitution; and
•
at the end of the line.
For example, you might want to substitute “STHWY” for “State Highway”. To do that, use the following line:
"State Highway"STHWY"
This provides a solution to a subtle problem, that of street names which match items in the abbreviation file. For example, “North St” and “Park Av” both have initial strings which match terms in the abbreviation file. Consequently, MapXtreme 2004 will substitute “N” for “North” to yield “N St” and “Pk” for “Park” to yield “Pk Av.” You could add the following lines to the
Abbreviation file to rectify these substitutions:
"N ST"North ST"
"PK AV"PARK AV"
Note that these lines have to come after the entries which substitute “N” for “North” and “PK” for
“Park”. If they came before, they would have no effect. Thus:
...
...
NORTH
...
...
PARK
..
N
PK
....
"N ST"NORTH ST"
"PK AV"PARK AV"
...
...
When MapXtreme 2004 encounters NORTH N it will turn NORTH ST into N ST. When it encounters “N ST”NORTH ST” it will then turn N ST into NORTH ST. PARK AV is treated similarly.
Special Characters
MapXtreme 2004 uses the exclamation point (!), the double quote (") and the backslash (\) as special characters. These characters tell MapXtreme 2004 how to treat strings which follow them, but are not themselves ordinarily treated as characters in substitution strings. The exclamation point tells MapXtreme 2004 that the string should not be interpreted as an abbreviation. The double quote tells MapXtreme 2004 that spaces in the string are legitimate.
And the backslash tells MapXtreme 2004 to treat a special character as an ordinary character.
When you want to use any of these in a line where they are to be treated as simple characters, precede them by a backslash. Thus:
\!
\"
\\
Adding Lines to the Abbreviation File
You can add a new item to the file by adding a new row. The order in which you add rows is not significant, except in those cases where you expect one substitution pair to compensate for the effects of another. The number of spaces between the first and second items in a row is not significant either.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
135
MapXtreme2004_DevGuide_A4.pdf
Using Themes and
Legends
11
MapXtreme 2004 provides you many options for adding thematics and legends to your map. The following sections illustrate the different types of themes and legends available to you and explains how to use them.
In this chapter:
!
!
!
!
!
!
!
!
!
!
Developer Guide
Thematics Overview
Chapter 11: Using Themes and Legends
Thematic mapping allows you to present trends in data that would be difficult to see from tabular data. The theme is usually some piece or pieces of your data. You thematically shade a map using data from a data source, such as a native MapInfo table. For example, you can thematically shade a map of the United States based on the average temperature of each state. When you see red, you know it is hot (high number of degrees); where you see blue, it is cold (low number of degrees).
Themes represent your data with shades of color, fill patterns, or symbols. There are many uses for thematic maps to display your data. You create different thematic maps by assigning these colors, patterns, or symbols to map objects according to specific values in your data.
Mapping.Thematics Namespace
The MapInfo.Mapping.Thematics namespace contains classes that implement themes as style overrides on Feature layers and as Object themes. Modifier themes change the style, while object themes add a new layer. All themes implement the ITheme interface.
Modifier Themes
An example of a feature modifier theme are ranged, individual value and dot density thematic maps. They modify existing features in a layer. The following UML diagram gives an overview of the modifier theme hierarchy.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
137
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 11: Using Themes and Legends
Object Themes
Object themes include graduated symbol, and pie and bar charts. These themes create objects that represent the data values. The following UML diagram gives an overview of the object theme hierarchy.
GraduatedSymbolTheme
A graduated symbol theme is an object theme that contains point features whose symbol sizes are based on the numeric values of the theme's expression.
For instance, use graduated symbols to show housing income for a particular segment of the population across an area.
Example of a Graduated Symbol thematic map.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
138
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 11: Using Themes and Legends
When To Use a Graduated Symbol Theme
Graduated symbols maps work with numeric data only. If you are working with a table of restaurants, it makes no sense to create graduated symbols based on the type of cuisine each restaurant serves. However, graduated symbols are appropriate when you want to show the distribution of housing income by city.
Code Sample
using MapInfo.Mapping; using MapInfo.Mapping.Thematics;
// Load a map based on one table map.Load(new MapTableLoader("world.tab"));
FeatureLayer lyr = map.Layers["world"] as FeatureLayer;
//Create new graduated symbol theme
GraduatedSymbolTheme gradTheme = new GraduatedSymbolTheme
(map, lyr.Table, "Pop_Native");
// Create an object theme layer based on that graduated symbol theme
ObjectThemeLayer thmLayer = new ObjectThemeLayer
("World Pop Growth Rate", null, gradTheme);
//Add object theme to the map’s layer collection.
map.Layers.Add(thmLayer);
// Adjust how we graduate the size.
gradTheme.GraduateSizeBy = GraduateSizeBy.Constant; thmLayer.RebuildTheme();
PieTheme
A pie theme is an object theme containing pie charts with wedges that represent each data value. In pie charts you compare the wedges in a single pie, or examine a particular pie wedge across all of the pies. Pie charts also enable you to compare parts of a whole.
When To Use a Pie Theme
Pie charts are particularly useful for analyzing demographic data. For example, you have a dataset of demographic information for the United States. Your dataset shows the populations of several major demographic groups. Using pie charts, you can show the population of each demographic group, and see what fraction of the pie it makes up in each chart. This enables you to see the distribution of demographic groups on a per state basis, or across the entire
United States. You can also look at one demographic group and see how the relative population of the group varies in different states.
Code Sample
using MapInfo.Mapping; using MapInfo.Mapping.Thematics;
// Load a map based on one table map.Load(new MapTableLoader("world.tab"));
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
139
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 11: Using Themes and Legends
FeatureLayer lyr = map.Layers["world"] as FeatureLayer;
//Create new pie theme
PieTheme pieTheme = new PieTheme(map, lyr.Table, "Pop_Native",
"Pop_Asian","Pop_Other");
// Create an object theme layer based on that pie theme
ObjectThemeLayer thmLayer = new ObjectThemeLayer("World Pop Growth Rate", null, pieTheme);
//Add object theme to the map’s layer collection.
map.Layers.Add(thmLayer);
// DataValueAtSize is calculated automatically if not specified in
// pie’s constructor. But, we can adjust it. If we do so here, we’ll
// have to rebuild the theme. We can adjust it before creating the
// object theme layer, and that way the pies won’t need to be built
// twice.
pieTheme.DataValueAtSize /= 2; pieTheme.GraduateSizeBy = GraduateSizeBy.Constant; thmLayer.RebuildTheme();
BarTheme
A bar theme is an object theme that contains bar charts with bars that represent each data value. A bar chart is built for every map object (feature) at the centroid of the object, enabling you to analyze several thematic variables in a particular chart by comparing the height of the bars.
When To Use a Bar Theme
Bar themes are useful for examining the same variable across all the features in your map. For example, you have a table of U.S. state boundaries containing female and male population.
Using bar charts, you can create a thematic map that displays a two–bar chart for each state: one bar representing female, and the other representing male population. You can compare the population differences of each state, or you can examine several states and compare population differences to the others.
Code Sample
using MapInfo.Mapping; using MapInfo.Mapping.Thematics;
// Load a map based on one table map.Load(new MapTableLoader("world.tab"));
FeatureLayer lyr = map.Layers["world"] as FeatureLayer;
//Create new bar theme
BarTheme barTheme = new BarTheme(map, lyr.Table, "Pop_Native",
"Pop_Asian","Pop_Other");
// Create an object theme layer based on that bar theme
ObjectThemeLayer thmLayer = new ObjectThemeLayer("World Pop", null, barTheme);
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
140
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 11: Using Themes and Legends
//Add object theme to the map’s layer collection.
map.Layers.Add(barTheme);
// stack the bars and graduate by a constant amount.
barTheme.Stacked = true; barTheme.GraduateSizeBy = GraduateSizeBy.Constant; thmLayer.RebuildTheme();
RangedTheme
A ranged theme shows data grouped into ranges (bins) according to specific criteria. In
MapXtreme 2004 a ranged theme modifies an existing layer to reflect that criteria. It does not create a new layer, as range themes did in previous versions of MapX and MapXtreme. When you create a ranged thematic map, MapXtreme 2004 groups all dataset rows into ranges and assigns each row’s object the color, symbol, or line for its corresponding range.
Example of a ranged thematic map.
When To Use a Ranged Theme
A ranged theme is useful, for example, when you have demographic data for an area. For example, rural male population in Asia can be grouped into bins and shaded by color to indicate the population ranges that exist across the area.
All records in the dataset are assigned to a range and then drawn with a style based on that range. When using a yellow to green color range, for example, the countries with the highest population could be shaded yellow, the lowest shaded green and the intermediate ranges some color in between yellow and green. When the map displays, the colors make it readily apparent where the highest and lowest populations exist.
Ranges are also useful when the size of the region is not directly related to the magnitude of the data values.
Types of Ranged Values
MapXtreme 2004 can create ranges automatically using five distribution methods:
•
Equal count
•
Equal ranges
•
Natural break
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
141
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
•
Standard Deviation
•
Quantile
•
Custom
Chapter 11: Using Themes and Legends
Equal Count
Equal Count has the same number of records in each range. If you want to group 100 records into 4 ranges using Equal Count, MapXtreme 2004 computes the ranges so that approximately
25 records fall into each range, depending on the rounding factor you set.
When using Equal Count (or any other range method), it’s important to watch out for any extreme data values that might affect your thematic map (in statistics, these values are referred to as outliers).
Equal Ranges
Equal Ranges divides records across ranges of equal size. For example, you have a field in your table with data values ranging from 1 to 100. You want to create a thematic map with four equal size ranges. MapX produces ranges 1–25, 26–50, 51–75, and 76–100. Keep in mind that
MapXtreme 2004 may create ranges with no data records, depending on the distribution of your data.
Natural Break
Natural Break and Quantile are two ways to show data that is not evenly distributed.
Natural Break creates ranges according to an algorithm that uses the average of each range to distribute the data more evenly across the ranges. It distributes the values so that the average of each range is as close as possible to each of the range values in that range. This ensures that the ranges are well–represented by their averages, and that data values within each of the ranges are fairly close together.
Standard Deviation
When you create ranges using Standard Deviation the middle range breaks at the mean of your values, and the ranges above and below the middle range are one standard deviation above or below the mean.
Custom Ranges
If none of the distribution methods meet your needs, you can create custom ranges using the method DistributionMethod.CustomRanges, as illustrated below. This example shows four bins with varying ranges and a starting point above zero.
RangedTheme thm = new RangedTheme(_lyr, "Literacy", "World Literacy",
4, DistributionMethod.CustomRanges);
_lyr.Modifiers.Append(thm); thm.Bins[0].Min = 10; thm.Bins[0].Max = 50; thm.Bins[1].Min = 50; thm.Bins[1].Max = 100; thm.Bins[2].Min = 100; thm.Bins[2].Max = 125; thm.Bins[3].Min = 125; thm.Bins[3].Max = 150; thm.RecomputeBins();
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
142
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Code Sample
using MapInfo.Mapping; using MapInfo.Mapping.Thematics;
Chapter 11: Using Themes and Legends
// Load a map based on one table map.Load(new MapTableLoader("usa_caps.tab"));
FeatureLayer lyrPnt = map.Layers["usa_caps"] as FeatureLayer;
// Create a ranged theme on that feature layer, using Pop_1990 as the
// expression, name it USA pop, create 4 bins using the equal count
// distribution method.
RangedTheme thm = new RangedTheme(lyrPnt, "Pop_1990", "USA pop", 4,
DistributionMethod.EqualCountPerRange);
//Add the theme to the FeatureStyleModifiers list lyrPnt.Modifiers.Add(thm);
//Change the color of the first and last bin’s symbol thm.Bins[0].Style.SymbolStyle.Color = Color.Red; thm.Bins[3].Style.SymbolStyle.Color = Color.Blue;
//Spread the colors in all the theme’s bins by color with the RGB color
// spread method. Recompute the bin styles.
thm.SpreadBy = SpreadByPart.Color; thm.ColorSpreadBy = ColorSpreadMethod.Rgb; thm.RecomputeStyles();
//Change the pointsize of the first and last bin’s symbol thm.Bins[0].Style.SymbolStyle.PointSize = 10; thm.Bins[3].Style.SymbolStyle.PointSize = 25;
//Spread the bins by size using the Constant size spread method.
//Recompute the styles.
thm.SpreadBy = SpreadByPart.Size; thm.SizeSpreadBy = SizeSpreadMethod.Constant; thm.RecomputeStyles();
RangedLabelTheme
This class creates a range theme in which labels are drawn with a range style. For a more detailed discussion of ranged themes, see the section
.
When To Use a RangedLabelTheme Class
Ranged label themes are useful when you want use the labels to convey information about what you are labeling. For example, you could use a ranged label theme when labeling city or town populations. The label of a city with a large population would have a larger font than the label of a town with a small population.
// Create new ranged label theme based on the label source of a
// LabelLayer already in the map. It will use 5 bins of equal count.
RangedLabelTheme rangedLabelTheme = new
RangedLabelTheme(labelSource.Table, columnName, themeAlias, 5,
DistributionMethod.EqualCountPerRange);
// Add the label modifier to the label layer.
LabelModifier labelModifier = rangedLabelTheme as LabelModifier; labelSource.Modifiers.Insert(0, labelModifier);
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
143
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
IndividualValueTheme
Chapter 11: Using Themes and Legends
An Individual Value theme is a modifier theme that show points, lines, or boundaries that are shaded by individual values contained in a particular field of a dataset. You can use both numerical and nominal values in individual values maps. MapXtreme 2004 gives each unique value its own distinct style.
For example, a soft drink distributor maintains a table of the supermarkets that buy soft drinks from him in Washington D.C. Each supermarket sells the distributor’s brand of soft drink for a different price. If the distributor shades the supermarkets by price, using individual values, all stores that sell the soft drink for 49 cents are shaded one color, all stores that sell the soft drink for 51 cents are shaded another color, and so on. Each unique value is assigned its own color.
The distributor is able to see the price distribution among the supermarkets and can determine where he should increase his sales volume, based on the price.
When To Use an IndividualValueTheme Class
If you are shading your points, lines, or boundaries using nominal data, you can shade only by individual values. Nominal data is either non–numerical data (e.g., name, type of cuisine served, or brand of automobile sold) or numeric data where the numbers represent non– numeric data. Dates are considered numeric data and can be used in both ranged and individual values maps.
Code Sample
using mapInfo.Mapping; using MapInfo.Mapping.Thematics;
// Load a map based on one table map.Load(new MapTableLoader("World.tab"));
FeatureLayer fLyr = map.Layers["world"] as FeatureLayer;
// Create an individual value theme
IndividualValueTheme thm = new IndividualValueTheme(fLyr, "Country",
"World Pop");
//Add the theme to the FeatureStyleModifiers list fLyr.Modifiers.Append(thm);
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
144
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
IndividualValueLabelTheme
Chapter 11: Using Themes and Legends
This class creates an individual value thematic which operates on a layer's labels. For a more
detailed discussion of individual value themes, see the section
IndividualValueTheme on page 144
When To Use an IndividualValueLabelTheme Class
As with ranged label themes, individual value label themes are also useful when you want use the labels to convey information about what you are labeling. When working with street data, for example, you could use an individual value label theme to label different types of roads with different fonts. In this case, a highway would be represented by a label with a different style than the label for a county road.
//Create new individual value label theme
IndividualValueLabelTheme theme = new
IndividualValueLabelTheme(labelSource.Table, columnName, themeAlias);
// Add the label modifier to the label layer.
LabelModifier labelModifier = theme as LabelModifier; labelSource.Modifiers.Insert(0, labelModifier);
DotDensityTheme
A dot density theme is a style modifier that draws the fill pattern of a region, using dots based on the numeric value of the theme's expression.
Dot density maps use dots to represent the data value associated with a boundary or region.
The total number of dots in a region represents that region’s data value. If you have 10,000 senior citizens in a county, and each dot represents 100 senior citizens, there would be 100 dots in the county boundary.
When To Use a DotDensityTheme Class
A dot density theme is useful for showing raw data where one dot represents a large number of something: population, number of fast food restaurants, number of distributors who carry a brand of soda, etc.
For example, if you have a table of population broken down into county boundaries, you could use a dot density theme to show the concentration of people in each county boundary. There are two properties you control for dot density maps. You can specify the value of one dot. For example, to represent 20,000 high school students in Rensselaer County, New York using a dot density theme, you can specify that one dot represents 200 students. When you shade the county, the map would be drawn with 100 dots for that county.
Code Sample
using MapInfo.Mapping; using MapInfo.Mapping.Thematics;
// Load a map based on one table
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
145
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
map.Load(new MapTableLoader("World.tab"));
Chapter 11: Using Themes and Legends
// Create dot density theme.
// Add it as a modifier.
DotDensityTheme thm = new DotDensityTheme(lyr, "Pop_1994",
"World Pop", System.Drawing.Color.Red, DotDensitySize.Large);
FeatureLayer lyr = map.Layers["World"] as FeatureLayer; lyr.Modifiers.Append(thm);
Bivariate Thematic Maps
Bivariate thematic mapping uses point or line objects to represent two thematic variables. For example, a star can represent one variable, such as the number of teenagers, while a blue fill for the star represents their annual purchase amounts.
To create a bivariate map in MapX, you create two thematic maps, and layer one over the other so that the objects display two variables.
Types of Maps and Variables
The only types of thematic maps suitable for bivariate mapping are ranged and individual values maps. You can choose between two combinations for a bivariate map, depending on your data:
•
two ranged maps
•
one ranged map and one individual values map
If you have a non-numeric variable, one of your maps must be an individual values map. You cannot create a bivariate map with two non-numeric variables.
Displaying Attributes
To display two variables within one symbol, it is important to choose a different symbol attribute for each variable. For example, you cannot choose color for both variables because one color will overwrite the other. Choose from the following combinations:
•
color and symbol type
•
color and size
•
size and symbol type
Symbol type should only be used for nominal or non-numeric data, as there is no inherent association between a symbol type and a quantity.
Code Sample: Bivariate Thematic Map
RangedTheme thm = new RangedTheme(_lyr, "Literacy", "Pop_1994",
"Literacy Quantile by Pop", 4);
_lyr.Modifiers.Append(thm);
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
146
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Legends Overview
Chapter 11: Using Themes and Legends
The MapInfo.Mapping.Legends namespace contains classes, interfaces and enumerations for creating and displaying thematic and cartographic legends. Legends are a collection of
Thematic or Cartographic LegendFrames. Each frame contains a collection of LegendRows,
Each LegendRow has text and a style property.
Theme Legends
Theme legends provide a key of colors, symbols, and styles used for themes. This key explains what the colors, symbols, and styles represent.
When to Use a Theme Legend
A theme legend is useful whenever you have a map that contains themes. With a weather map that displays precipitation, rainfall may be represented by varying shades of green. A theme legend would be important in visually explaining that the darkest shade of green represents the highest amount of rainfall while lighter shades represent lower amounts of rainfall.
Code Sample
The following code is a portion of the ThemeLegends sample that demonstrates how to create a ranged theme on a table, add the theme as a FeatureStyleModifier (how styles for geometries are modified to reflect the bins of the theme); create a legend and legend frame and add it as an adornment. The complete code and VisualStudio solution can be found in the
Samples\Desktop\Features\ThemeLegend folder.
using MapInfo.Mapping; using MapInfo.Mapping.Thematics;
// Code prior to this section has created a ranged theme that groups
// the regions in the layer into 5 ranges by their area in square
// miles.
// Create a legend legend = map.Legends.CreateLegend(new Size(5, 5)); legend.Border = true;
ThemeLegendFrame frame = LegendFrameFactory.CreateThemeLegendFrame("Area",
"Area", thm); legend.Frames.Append(frame); frame.Title = "Area (sq. mi.)"; map.Adornments.Append(legend);
// Set the initial legend location to be the lower right corner
// of the map control.
System.Drawing.Point pt = new System.Drawing.Point(0, 0); pt.X = mapControl1.Size.Width - legend.Size.Width; pt.Y = mapControl1.Size.Height - legend.Size.Height; legend.Location = pt;}
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
147
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 11: Using Themes and Legends
Cartographic Legends
The cartographic legend class allows you to read and write cartographic legend metadata. The legend identifies each cartographic feature on the map using text and a style from the metadata.
When to Use a Cartographic Legend
A cartographic legend is very useful whenever you have a map that contains objects that represent items on the map. For example, a map with landmarks requires a cartographic legend. Hospitals, schools, churches, and airports would each be represented by a different symbol. The cartographic legend provides a visual explanation of the different types of landmarks that are represented on the map.
Code Sample
using MapInfo.Mapping; using MapInfo.Mapping.Thematics;
// Create the legend
System.Drawing.Size size = new System.Drawing.Size(400, 400); legendFactory = session.LegendFactory; legend = legendFactory.CreateLegend(map, size); frameFactory = legend.LegendFrameFactory;
// Add a legend frame to the legend frame = _frameFactory.CreateCartographicLegendFrame(lyr,
"State", "State", RowTextSourceType.Expression); legend.Frames.Append(frame);
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
148
MapXtreme2004_DevGuide_A4.pdf
Working with the Web-
Specific Classes
12
This chapter discusses MapXtreme 2004 Web controls and tools for working with ASP.NET applications.
In this chapter:
!
Overview of the Web.UI.WebControls Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . 150
!
!
!
!
Developer Guide Chapter 12: Working with the Web-Specific Classes
Overview of the Web.UI.WebControls Namespace
The MapInfo.Web.UI.WebControls namespace includes the user interface tools and web controls for designing and using Web Form applications built with MapXtreme 2004. Web controls provide drag and drop convenience onto Web Forms. Tools provide server and client side behaviors within a MapControl. The controls and tools span a variety of functionality including map display and navigation, feature selections, and layer management.
Web Controls
Web controls provide an interactive (drag and drop) development environment in Microsoft
Visual Studio.NET. Use these controls for creating simple mapping applications without writing significant code.
The Web controls are included in the MapInfo.Web.UI.WebControls namespace. They include:
MapControl, Toolbar, ZoomInControl, ZoomOutControl, CenterControl, PanControl,
DistanceControl, LayerControl, InfoToolControl and LegendControl.
These controls are available through the Visual Studio Toolbox under the MapXtreme Web
Controls tab.
Web Control
MapControl
ToolbarControl
ZoomInToolControl
ZoomOutToolControl
CenterToolControl
PanToolControl
Selections
InfoTool
DistanceTool
LayerControl
LegendControl
Purpose
Displays a map image and allows mouse interaction based on the selected tool.
Provides a panel for one/more map tools.
Use to get a closer area view of a map or a layer.
Use to get a wider view of a map.
Use to recenter the map on the clicked point.
Use to reposition a map within its window by dragging the map.
Select features at the location resulting from a mouse click operation. The following are available:
• PointSelectionToolControl
• RadiusSelectionToolControl
• PolygonSelectionToolControl
• RadiusSelectionToolControl
Use to get attribute information on the clicked point.
Use to get distance between two or more points.
Allows you to add/remove/edit properties in map layers.
Allows you to view a Legend on a form.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
150
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 12: Working with the Web-Specific Classes
Web Control Types
There are two types of web controls that can be used to develop applications: server controls and client side HTML controls.
Server Side Controls
With server controls, the drawing and events are mostly handled on the server side.
Certain server controls like the dropdown box or text box have a property called autopostback.
Autopostback allows controls to go to the server when selection changed or text changed events occur.
Note:
To improve your web application’s performance, consider changing this property to false (and submitting the whole page once with the submit button, rather than for every event for server controls).
HTML Controls
HTML controls are elements on an HTML page that are drawn by a browser. With these controls the object model is accessed on the client side through scripting.
Note:
Use HTML controls in place of server controls to improve performance. For more performance tuning tips, visit this Web site: http://samples.gotdotnet.com/quickstart/
aspplus/doc/perftuning.aspx
Using Web Controls
This section describes several key Web controls in MapXtreme 2004: MapControl,
LegendControl, and LayerControl.
MapControl
MapControl is a web control containing an instance of a Map object. This Map object is obtained from the MapFactory by using the MapAlias property it is pointing to. The map is drawn by exporting the map into an image and this image is used in the IMG html tag. The postbacks for tool controls are also handled in this control.
The following describes the behavior of MapControl at design and run time:
Design Time
At design time the following things happen:
1.
The map pointed by MapControl can be loaded from tables/geosets/workspaces using verb or can be changed by changing properties or using LayerControl.
2.
When any changes to map are done, the state of the map is stored in a workspace file in the same folder as the web project. When the project is closed and reopened, it reads from this workspace and loads the map to restore the map to previous state. The name of the workspace file is unique in that project qualified by form name and
MapControl unique ID. The property WorkspaceFileName is used for this purpose. It is not advisable to set this property at run time.
3.
The alias used in this process is serialized as a MapAlias property in the.aspx file and it is the same as the alias in the workspace file. If they mismatch it can result in unpredictable behavior. If you want to change this property, do so in the .aspx file.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
151
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 12: Working with the Web-Specific Classes
4.
The property UseDesigntimeWorkspace is used to specify whether this workspace is to be loaded at run time on the first occasion the page is requested. If that property is set to false, the workspace created at design time is ignored.
Run Time
The lifecycle of the MapControl at run time works as follows:
1.
In the constructor the tools collection is created which creates all default tools
2.
In OnInit following tasks are done:
a.
It tries to obtain the Map object with MapAlias it is pointing to from Session. If it doesn't exist then it creates a blank map. MapExport object is also created using this Map object to be used for exporting.
b. If it is the first time this page is being accessed and UseDesigntimeWorkspace flag is True, then it loads the workspace into the map.
3.
In OnLoad all the information that is required on the client is rendered, such as javascripts and tool information.
4.
In RenderContents, the tag that holds the MapControl and IMG tag representing the image is rendered. Other information is used by tools is for client side operations.
LayerControl is rendered in the form of javascript variables.
It is possible to deviate from the default approach and use your own Map object at run time in the Page_Load method of the Web Form. However the alias of this created map must match the MapAlias of the MapControl. While loading another workspace into the map, note that the alias of the map gets changed to the alias in the workspace. The following is an example: private void Page_Load(object sender, System.EventArgs e)
{ if (!Page.IsPostBack) {
// Remove the map from session; we want to use ours
MapInfo.Engine.Session.Current.MapFactory.Remove
(MapControl1.MapAlias);
// Create a empty map with same alias as MapControl
MapInfo.Engine.Session.Current.MapFactory.CreateEmptyMap
(MapControl1.MapAlias, MapControl1.MapAlias, new Size(200,200));
// Load the map with table.
MapInfo.Mapping.MapLoader ml =
MapInfo.Mapping.MapLoader.CreateFromFile(@"World.tab");
// Get the map object out of session we just created
MapInfo.Mapping.Map map =
MapInfo.Engine.Session.Current.MapFactory
[MapControl1.MapAlias]; if (map != null) { ml.Load(map);
MapControl1.Map = map;
}
}
}
LegendControl
The LegendControl is used to draw a legend for a map and legend object.
This control is unlike other controls we have, because it does not have any design time behavior at this time. The Map and Legend objects are set at run time. The correct way to use this LegendControl is:
1.
Drag and drop the control at design time. It will just display a rectangle with the proper message.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
152
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 12: Working with the Web-Specific Classes
2.
Write code in the Page_Load method to set Map and Legend objects.
The following is an example.
private void Page_Load(object sender, System.EventArgs e)
{ if (!IsPostBack) {
LegendControl1.Map = MapControl1.Map; if (MapControl1.Map.Legends.Count > 0) {
LegendControl1.Legend = MapControl1.Map.Legends[0];
}
}
}
LayerControl
LayerControl allows you to change settings on the associated map. LayerControl displays
Feature layers and Label layers in a tree view structure. It allows you to change visible, selectable, and zoom layering properties for these layers. Changes will not be reflected in the map until the Apply Changes button has been pressed. All changes are persisted only for the active life of the application using the LayerControl; they cannot be saved or persisted to a workspace file.
To use LayerControl, drop the control on your design form that already contains a map.
Highlight a layer in the treeview and change the settings as desired.
Using MapControls in a User Control
User controls are a collection of controls. They appear as items in the project and can be dragged and dropped onto a form. User controls are created so that they can be used repetitively in different forms. User controls also have a code-behind file where code for controls in that user control can be written.
You may wish to include a Web control in a user control. This section describes the use of a
MapControl in a user control.
When MapControl is dropped onto a form or user control it creates a workspace file in the project. This workspace stores all changes made to the map that the MapControl is pointing to.
The name of this workspace file is of the form <Web Form
name>_<MapControl.UniqueID>.mws so that it is unique across the project. When a
MapControl is dropped into a user control, the unique ID of the MapControl contains a colon
(“:”), which can lead to problems in the pathname of the workspace file.
The correct way to use the MapControl in a user control is:
1.
Drag and drop MapControl and all related MapXtreme 2004 controls into the user control.
2.
In the Properties Window, change the UseDesignTimeWorkspace property of
MapControl to False.
3.
Add the code for loading the map the first time the page is accessed in the code-behind file of the user control. For example:
Page_Load Method
'Put user code to initialize the page here
Dim wl As MapInfo.Mapping.MapWorkSpaceLoader
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
153
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 12: Working with the Web-Specific Classes
If Not Page.IsPostBack Then wl = New MapInfo.Mapping.MapWorkSpaceLoader
("c:\data\world.mws") wl.Load(MapControl1.Map)
End If
Make sure that the alias of the map in the workspace file matches that of the MapControl.
Web Tools Architecture
Tools in the MapXtreme 2004 Web object model provide server and client side behaviors within a MapControl. Each tool has a corresponding control. The controls are discussed in section
. The tools contain the logic to carry out the behavior. The control
is what allows you to use the tool in your Web Form.
Tools on the server side are responsible for:
•
extracting data
•
carrying out the business logic of the tool.
Tools on the client side are responsible for:
•
drawing and mouse operations (e.g., rubber band rectangle, mouse click)
•
collecting data from mouse operations
•
creating hidden fields for data
•
submitting the page to the server
MapControl has a tools collection that, when initialized, includes a set of default map navigation and selection tools: ZoomIn, ZoomOut, Pan, Center, Distance, Info, PointSelection,
RectangleSelection, RadiusSelection, and PolygonSelection tools. To activate one of these tools, set the tools collection’s current tool to one of them.
To change the tool on the server to zoom in tool:
MapControl1.MapTools.CurrentTool = ZoomInMapTool.Toolname;
To add your custom tool to the tools collection:
MapControl1.MapTools.Add(new CustomTool());
The MapXtreme 2004 web tools architecture is flexible because you can write your own tools, add them to the tools collection and use them by setting the current tool to it. Custom tools are not available at initialization of MapControl. They are added at Page_Load time.
Info Tool
After you have added the Info tool to the MapControl collection and set the current tool to it, you must add an event method to retrieve the features selected as the result of clicking with the Info tool. To achieve this, in your IDE, select the Info tool icon and right-click to bring up the
Properties window. Click the lighting bolt events icon to show valid events. Locate the
InfoRetrieved event and double-click on it. You can then add code similar to the snippet below to use the tool and retrieve the selected feature collection.
private void InfoToolControl1_InfoRetrieved(object sender,
MapInfo.Web.UI.WebControls.InfoToolEventArgs e)
{
// using MapInfo.Data
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
154
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 12: Working with the Web-Specific Classes
MultiResultSetFeatureCollection multiCollection = null; multiCollection = e.Features; foreach ( FeatureCollection fCollection in multiCollection )
{ foreach ( Feature feature in fCollection )
{
ListBox1.Items.Add(feature.Table.Alias);
}
}
}
Distance Tool
Like the Info tool, you must add an event to retrieve the distance calculated after the user double-clicks the tool. To do this, in your IDE select the distance tool icon and right click to bring up the Properties window. Click the lighting bolt events icon to show valid events. Double-click on the DistanceComputed event to add the event method to the tool. Add code similar to the example below to retrieve the distance and display it in a textbox control.
private void DistanceToolControl1_DistanceComputed(object sender,
MapInfo.Web.UI.WebControls.DistanceToolEventArgs e)
{
TextBox1.Text= string.Format("Distance calculated: {0}", e.Distance);
}
Creating a Custom Tool
The general procedure for creating a custom tool is:
1.
Derive a tool class from MapInfo.Web.UI.Controls.MapTool.
2.
Specify the Start and Stop methods for client side drawing.
3.
Override Execute method and write the business logic on it.
The following two examples are taken from the ToolsSample that ships with
MapXtreme 2004. Example 1 illustrates the server side, while Example 2 focuses on the client side.
Example 1: Writing a Server SIde Custom Tool
This example shows you how to write your own custom tool without writing significant code from scratch. Let's create a tool which zooms out by drawing a rectangle on the map call it
ZoomOutRectangleMapTool.
Now in order to create tool we need the following information:
•
How do I implement the class?
•
How do I draw a rectangle on the map on the web page?
•
How do I process the information on the server side to actually do the zoom?
•
How do I add it to the tools collection so that it can be used?
First let's write that class as follows:
// This class is a custom tool which allows users to draw a
// rectangle and then zoom out. ZoomOut tool for example just
// allows users to zoom out on a click.
public class ZoomOutRectangleMapTool : MapTool
{ private string _clientStartMethod; private string _clientStopMethod;
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
155
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 12: Working with the Web-Specific Classes
private string _clientCodeSource = null; private string _name; public static readonly string Toolname = "ZoomOutRectangleTool"; public ZoomOutRectangleMapTool()
{
//
// TODO: Add constructor logic here
//
// Name of the tool
_name = Toolname;
// We use MapInfo's rectangle drawing client side code
ClientStartMethod = "MapInfoWebRectangleStart";
ClientStopMethod = "MapInfoWebRectangleStop";
}
/// Name of the tool, by default it is ZoomInTool public override string Name
{ get { return _name; } set { _name = value; }
}
// Name of the client side method to set up mouse event handlers
// for drawing public override string ClientStartMethod
{ get { return _clientStartMethod; } set { _clientStartMethod = value; }
}
// Name of the client side method to cancel the mouse event
// handlers public override string ClientStopMethod
{ get { return _clientStopMethod; } set { _clientStopMethod = value; }
}
// Source or url where the client drawing code is located public override string ClientCodeSource
{ get { return _clientCodeSource; } set { _clientCodeSource = value; }
}
// Url of the cursor image when this tool is active public override string CursorUrl { get {return ""; } set {; }
}
// This method sets the zoom value public override void Execute(string dataString,
System.Collections.ArrayList arrayList,
MapInfo.Mapping.Map map) {
// Extract points from the string
System.Drawing.Point [] points = base.ExtractPoints(dataString);
// There will be two points, end of rectangle in screen
// coordinates, convert them to spatial
MapInfo.Geometry.DPoint from; map.DisplayTransform.FromDisplay(points[0], out from);
MapInfo.Geometry.DPoint to;
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
156
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 12: Working with the Web-Specific Classes
map.DisplayTransform.FromDisplay(points[1], out to);
// If first point and second points are very close to each
// other treat it like a click if(((points[0].X - points[1].X) <= 20) &&
((points[0].Y - points[1].Y) <= 20)) { map.Zoom = new MapInfo.Geometry.Distance
(map.Zoom.Value * 2, map.Zoom.Unit); map.Center = to;
} else {
// Determine the zoom factor as the ratio of the drawn
// rectangle to the bounds of the map and set the center
// of the map as the center of the rectangle
DRect r1 = new DRect(from, to); map.Center = r1.Center();
DRect rect = new DRect(); double mh = Math.Abs(map.Bounds.y2 - map.Bounds.y1); double mw = Math.Abs(map.Bounds.x2 - map.Bounds.x1); double rh = Math.Abs(to.y - from.y); double rw = Math.Abs(to.x - from.x); double ratio = Math.Min(mh, mw)/Math.Min(rh, rw); map.Zoom = new MapInfo.Geometry.Distance
(map.Zoom.Value * ratio, map.Zoom.Unit);
}
}
}
}
As you can see, the ClientStartMethod and ClientStopMethod specify name of the functions to draw a rectangle. The functions to draw the marquee rectangle, collect information, sending it to server after the operation is complete is all implemented in our javascript files installed with
MapXtreme 2004. The javascript sources are installed in IIS virtual directory called
MapXtremeWebResources (which points to the actual location).
On the server the significant portion of the code is in Execute(). This function gets automatically called from MapControl with the right information. It extracts the points from hidden variable and executes the code to change the zoom.
After creating this class, add it to your project. To use this tool, first add it to the tools collection of the MapControl by changing the Page_Load method of the page class.
private void Page_Load(object sender, System.EventArgs e)
{
// Add your custom tool
MapControl1.MapTools.Add(new ZoomOutRectangleMapTool());
}
To use the new custom tool, set the current tool to it. For example, for a button on the form that calls the handler when clicked, the current tool can be set as: private void Button1_Click(object sender, System.EventArgs e)
{
MapControl1.MapTools.CurrentTool =
ZoomOutRectangleMapTool.Toolname;
}
After this operation is complete users can draw rectangles on the map and zoom out.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
157
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 12: Working with the Web-Specific Classes
Example 2: Setting the Current Tool on the Client Side
The last portion of the above example demonstrates how to set the tool programmatically on the server side. If all you want to do is set the current tool, you can use Javascript code that works across most browsers. This is more efficient than going to the server for that purpose.
Note that you still need to write the server side code to change the map.
The following is taken from WebForm3.aspx in the ToolSample project.
<%@ Register TagPrefix="mapinfowebuiwebcontrols"
Namespace="MapInfo.Web.UI.WebControls" Assembly="MapInfo.Web" %>
<%@ Page language="c#" Codebehind="WebForm3.aspx.cs"
AutoEventWireup="false" Inherits="WebApplication4.WebForm3" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm3</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="C#" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
</HEAD>
<body MS_POSITIONING="GridLayout">
<asp:Label id="Label2" style="Z-INDEX: 106; LEFT: 704px;
POSITION: absolute; TOP: 328px" runat="server"
Height="16px" Width="56px" Font-Bold="True">Distance:
</asp:Label>
<br>
<strong>This project contains two custom controls which extend
MapInfo Web MapTool to do custom work.
<br>
The first one uses MapInfo client side drawing code
<br>
The second one uses the combination of custom client side drawing code and MapInfo client side API
<br>
<br>
This Page demonstrates the flexibility of how tools can be used in any UI, and current tool can be set on server side or on the client side through javascript.
<br>
It also makes use of DistanceComputed event of
DistanceMapTool to display distance in a textbox.
</strong>
<br>
<br>
<script src="JScript1.js"></script>
<form id="Form1" method="post" runat="server">
<MAPINFOWEBUIWEBCONTROLS:MAPCONTROL id="MapControl1" style="Z-INDEX: 100; LEFT: 160px; POSITION: absolute;
TOP: 176px" runat="server" Width="523px" Height="232px"
WorkspaceFileName="WebForm3MapControl1.mws"
BorderStyle="Solid" BorderWidth="1px" MapAlias="Map3"
Format="Gif"></MAPINFOWEBUIWEBCONTROLS:MAPCONTROL>
<asp:dropdownlist id="DropDownList1" style="Z-INDEX: 101;
LEFT: 704px; POSITION: absolute; TOP: 240px" runat="server" Width="160px" Height="40px"
AutoPostBack="True"></asp:dropdownlist>
<table style="Z-INDEX: 102; LEFT: 176px; POSITION: absolute;
TOP: 432px">
<TR>
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
158
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 12: Working with the Web-Specific Classes
<TD><STRONG>Select Current Tool:</STRONG></TD>
<TD vAlign="middle"><INPUT id="radio1" type="radio" align="middle" value="MapInfoWebZoomIn" name="click" onclick="SetCurrentTool
(this, 'MapControl1')">MapInfoWebZoomIn
</TD>
<TD vAlign="middle"><INPUT id="radio2" type="radio" align="middle" value="ZoomOutRectangleCustomClientDrawingTool" name="click" onclick="SetCurrentTool
(this, 'MapControl1')">
ZoomOutRectangleCustomClientDrawingTool
</TD>
</TR>
</table>
<asp:Label id="Label1" style="Z-INDEX: 104; LEFT: 704px;
POSITION: absolute; TOP: 208px" runat="server"
Height="16px" Width="136px" Font-Bold="True">
Select Current Tool:
</asp:Label>
<asp:TextBox id="TextBox1" style="Z-INDEX: 105; LEFT: 704px;
POSITION: absolute; TOP: 352px"runat="server"
Height="24px" Width="160px">
</asp:TextBox>
</form>
<script> if (_map.MapTools.CurrentTool != null) { var rad1 = document.getElementById('radio1'); if (rad1 != null && _map.MapTools.CurrentTool.Name == rad1.value) { rad1.checked = true;
} var rad2 = document.getElementById('radio2'); if (rad2 != null && _map.MapTools.CurrentTool.Name == rad2.value) { rad2.checked = true;
}
} function SetCurrentTool(radio, map)
{
MapInfoWebSetCurrentTool(map, radio.value); var v = document.getElementById('currentName'); if (v != null) { v.value = radio.value;
}
}
</script>
</body>
</HTML>
Client-Side Tools Examples
The following Javascript examples illustrate typical tool operations you would likely carry out on the client.
These variables that are rendered on the form can be used for tool names:
// Globals for default tool names var MapInfoWebZoomInTool = "MapInfoWebZoomIn"; var MapInfoWebZoomOutTool = "MapInfoWebZoomOut"; var MapInfoWebPanTool = "MapInfoWebPan"; var MapInfoWebCenterTool = "MapInfoWebCenter"; var MapInfoWebPointSelectionTool = "MapInfoWebPointSelection";
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
159
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 12: Working with the Web-Specific Classes
var MapInfoWebRadiusSelectionTool = "MapInfoWebRadiusSelection"; var MapInfoWebRectangleSelectionTool =
"MapInfoWebRectangleSelection"; var MapInfoWebPolygonSelectionTool = "MapInfoWebPolygonSelection"; var MapInfoWebDistanceTool = "MapInfoWebDistance"; var MapInfoWebInfoTool = "MapInfoWebInfo";
To get the map object given its ID, use
MapInfoWebGetMap(mapid)
. For example: var obj = MapInfoWebGetMap('MapControl1');
To set the current tool on the client side given the map ID and tool name, use
MapInfoWebSetCurrentTool(mapid, toolName)
. For example:
MapInfoWebSetCurrentTool('MapControl1',
MapInfoWebRectangleSelectionTool);
The following example demonstrates how to access a map object and the tools collection on the client side.
var map = document.getElementById('MapControl3_Image'); map.MapTools // to get tools collection map.MapTools.CurrentTool // to get current tool
The following are the start and stop methods that can be used for client side drawing.
To draw a rectangle:
MapInfoWebRectangleStart
MapInfoWebRectangleStop
To process a click:
MapInfoWebPointStart
MapInfoWebPointStop
To process panning of a map:
MapInfoWebPanStart
MapInfoWebPanStop
To draw a circle:
MapInfoWebCircleStart
MapInfoWebCircleStop
To draw a polyline:
MapInfoWebDistanceStart
MapInfoWebDistanceStop
To draw a polygon:
MapInfoWebPolygonStart
MapInfoWebPolygonStop
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
160
MapXtreme2004_DevGuide_A4.pdf
Planning a Web
Application
13
This chapter describes the various aspects of saving the state and persisting information and settings for ASP.NET mapping applications. This chapter also includes tips on optimizing the performance of your web application.
In this chapter:
!
!
!
!
Working with MapXtreme 2004’s State and Pool Settings . . . . . . . . . . . . . . . . . . . . 170
Developer Guide
Creating Your Application
Chapter 13: Planning a Web Application
When creating a web application using MapXtreme 2004, you need to consider the following subjects to fully take into account everything that is necessary for it to work as well as it can:
•
Loading Data
•
State
•
Pooling
•
Timing of ASP.NET events
•
Performance tips
Loading Data
One of the essential components of you web application is the data that makes up the map.
When planning your web application, what data you use and how you load it should be a main consideration. MapXtreme 2004 provides classes, controls, preload settings and utilities to make this job easier.
Data is loaded as tables and can be in the form of MapInfo native TAB format (.tab), MapX geoset (.gst) or the new MapInfo XML-based workspace format (.mws). Data is more fully discussed in
and
Chapter 9: Accessing Data from a DBMS
MapXtreme 2004 supports a number of table types including DBMS, raster (WMS, Grid),
seamless, and views. See the Data.Table class for more information and
The workspace format and a utility to build workspaces (Workspace Manager) are covered in
Chapter 18: Using the Workspace Manager
Appendix C: Understanding the New
The following sections cover key classes and tasks involved with loading data.
MapLoader Classes
The MapLoader class provides a mechanism to load the layers of a map from Geoset files,
XML Workspace files, or TAB files. For each type of map to load, there is a subclass of
MapLoader that is used to load the map: MapGeosetLoader, MapWorkspaceLoader, and
MapTableLoader.
MapLoader.Load() method is called by the Map. This is the main method that does all the work of creating and adding layers to the map, setting layer properties, and setting map properties.
When deriving your own class from MapLoader, put your implementation in the Load() method.
MapControl
MapControl is the web control containing an instance of a Map object. This Map object is obtained from the MapFactory by using the MapAlias property of the MapControl. The map is drawn by exporting the map into an image and this image is used in the IMG HTML tag. The postbacks for tool controls are also handled in this control.
At design time tables, geosets, or workspaces can be loaded into the map, pointed to by the
MapControl. If you start your web application development by using a MapXtreme 2004 web template, the MapControl automatically displays on your web form (see
Applications in Chapter 2 on page 29
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
162
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 13: Planning a Web Application
If you start from a Visual Basic or C# template, which is not a MapXtreme template, you must add the MapControl to the form in order to add the appropriate MapXtreme 2004 resources to
Building ASP.NET Web Applications Without A Template in Chapter 2 on page 32
When the map is changed in any way (e.g., changing a property or using a verb), the state of the map is stored in a workspace file in the same folder as the web project. When the project is closed and reopened, it reads from this workspace and loads the map to restore the map to previous state. The name of the workspace file is unique in that project qualified by the form name and the MapControl unique ID with the extension .mws. The property
WorkspaceFileName is used for this purpose.
Workspace Preloading
You can configure the Session to preload one or more workspaces on creation. This is particularly useful on an ASP.NET application since it allows you to automatically initialize the
Session with its initial state. To configure this, add the following bolded element to the
<appSettings>
element (which should be added under the
<configuration>
element, if not present) in your Web.config file:
<configuration>
<appSettings>
<add key="MapInfo.Engine.Session.Workspace" value="c:\my workspace.mws;c:\myworkspace2.mws" />
</appSettings>
</configuration>
This preloads workspaces c:\myworkspace.mws and c:\myworkspace2.mws into your session object. Each workspace file can be separated by either a comma or semicolon (
,
or
;
). The preloaded workspace option sets only the initial state and the session, you still need to handle saving and restoring state in your own application or through settings from request to request.
State
Web applications need to retain user settings from request to request. These settings can include the current map zoom, selected objects, map center, etc. Some web objects need to be retained between web requests. As discussed in
Chapter 5: Working with Core MapXtreme
, State is a necessary aspect of most MapXtreme 2004 applications. If you are
developing a web application you need to configure how Session is saved. The Session state can be set to either InProc, StateServer, SQLServer, or Off. When you use InProc, state is preserved using persistence and settings are kept in memory until the application is ended when the state is written to XML If you set your Session mode to either StateServer or
SQLServer, the serialization method of preserving state is used. Serialization is the conversion of the particular objects in your application to a stream of data that is stored on the server and deserialized (retrieved) when the same object is requested again by the application.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
163
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 13: Planning a Web Application
ASP.NET Time Line
In order to fully understand the process of maintaining state in a MapXtreme 2004 web application, it is essential to understand the calling sequence of a map request hitting a
MapXtreme 2004 ASP.NET application. The following diagram illustrates this sequence:
The flow of events for an initial ASP.NET HttpRequest
In the HttpApplication.BeginRequest handler we set up MapInfo.Engine.Session so the application programmer can access the Session in Application_BeginRequest() in the
Gloabl.asax file or the Page_Load event in the main flow of the application.
The ASP.NET framework automatically deserializes the context.Session[] array after
HttpApplication.BeginRequest handler.
Since MapInfo.Engine.Session was set up in HttpApplication.BeginRequest handler, the
MapInfo objects are deserialized into MapInfo.Engine.Session. MapFactory, Map, Layers,
Themes, Catalog, and Tables are refreshed with deserialized contents. This is why you do not need to load the map states but save them.
Initial Application State
The initial application state determines how your map object appears when it is first requested by any particular client. This is important when you are implementing your web application with a pool of session objects. When a user makes their first request that includes a map, they should see a page with a map image in it. That map image should appear the same way each time a new user makes a request so that you have a consistent initial map. By presetting the initial state of the map, any object taken from the pool is reset to a particular state allowing each user the same initial view of the map.
The initial application state is set either by using preloaded workspaces, by writing code in your application, or by letting the MapControl load the workspace it created at design time. The
MapControl has a property UseDesigntimeWorkspace that when set to true, the MapControl loads the workspace the first time a request is made.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
164
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 13: Planning a Web Application
Handling Application State
Handling application state is a consideration mainly for applications that use pooling (see
). Managing ongoing application state is the process of ensuring that the
user receives the result of any change they may make to their map object during a particular request/submit exchange. For example, the user receives a map and chooses to zoom in.
When they send their request, the result should have the same configuration of layers and other details that they have already set with only the apparent change being a change in the zoom. Depending on the mode of the stateSession object (set in the Web.config file of your application; see
The Web.config File on page 170
for more information), the process for maintaining state is different.
Serialization
Serialization is the process of converting an object to a stream of data in order to preserve it on the server. This process is an essential part of maintaining objects in MapXtreme 2004 web applications. If the objects are not maintained the server would need to recreate the object
(such as a map) for each web request. When the object is requested, it is deserialized (or recreated from the stream of data) and then modified. This algorithm does not make a copy of the object (as other serialization algorithms do) so that the object being modified is created only once.
The serialization is performed by formatters that are embedded in the Microsoft.NET
Framework. Two different formatters are included in the Framework, one for binary objects,
BinaryFormatter, and one for SOAP objects, SOAPFormatter. (SOAP is a lightweight protocol intended for exchanging structured information in a decentralized, distributed environment, such as the web.) SOAPFormatter is relatively faster than BinaryFormatter. SOAPFormatter is used for certain basic types of data (Int, Byte, Decimal, etc.) and BinaryFormatter is called for complex of objects. See the Microsoft MSDN documentation for more information about the
SOAPFormatter and the BinaryFormatter.
All serialization is done automatically by Microsoft Framework once an object is passed to the formatter. To pass an object to the formatter use the GetObjectData() method. To deserialize the object (restore it from the stream) use the SetObjectData() method.
The classes listed below are among the most commonly used that are serializable. For a complete list of serializable classes refer to the online help for the GetObjectData() method:
•
Session
•
Map
•
Layers
•
Layer
•
FeatureLayer
•
LabelLayer
•
GroupLayer
•
ObjectThemeLayer
•
UserDrawLayer
•
Theme
•
RangedTheme
•
IndividualValueTheme
•
DotDensityTheme
•
FeatureStyleModifier
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
165
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 13: Planning a Web Application
•
FeatureOverrideStyleModifier
•
Legend
•
Selections
•
Styles
•
FeatureCollection
A Map is bound to a Session object. You cannot take a Map object from one Session and use it in another. You have two options if you want to clone the entire Session object; either by using
Serialization or by using Persistence.
Serialize/Deserialize the Session Object
The MapInfo.NET Session object supports the ISerializable interface. This allows you to serialize and deserialize the entire Session object. Here's an example of how to do this:
// Create a MemoryStream to serialize into
MemoryStream stream = new MemoryStream();
// Serialize the MapInfo.NET Session object
BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, Session.Current); stream.Position = 0;
// Make changes to the Session object to make sure the
// deserialization works correctly
...
// Recreate the Session object from the stream
// Note: this will replace the current Session object with the
// contents of the stream formatter = new BinaryFormatter(); formatter.Deserialize(stream);
Note:
The stream parameter passed to the formatter.Serialize method can be anything derived from System.IO.Stream.
Note:
This serialization functionality was designed to be used for our State feature. If you persist this information to disk, then try to reload it in the future (with a different version of the product), it's not guaranteed to work.
ISerializable Interface on Selection and Selections Classes
We implement the ISerializable interface on the Selection and Selections classes. We needed this functionality to implement our State feature. Here's some sample code that demonstrates how to serialize or deserialize the Selections object:
// Create a MemoryStream to serialize into
MemoryStream stream = new MemoryStream();
// Serialize the Selections object
BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, Session.Current.Selections); stream.Position = 0;
// Make changes to the Session's Selections object to make sure the
// deserialization works correctly.
...
// Recreate the Selections object from the stream.
// Note: this replaces the current Session's Selections object with
// the contents of the stream formatter = new BinaryFormatter(); formatter.Deserialize(stream);
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
166
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 13: Planning a Web Application
Persistence
Persistence is the storing of the objects in an application into an XML format. Persistence is used to save and restore a workspace in either a web or desktop application. See
Understanding the New MapInfo Workspace
for more information about the XML schema
used for MapXtreme 2004 applications.
Persisting and De-persisting the Session Object
Persisting and de-persisting Session objects is done using the WorkSpacePersistence and
WorkSpaceLoader classes. These two classes will write out and read in MapInfo Workspace
(.mws) files. The application can write out the workspace (a copy of the Session), and apply the contents of the workspace file to a new Session object, creating a clone of the Session. Note that adding a workspace (using the WorkSpaceLoader class) is an additive process. To ensure the Session only contains the contents of the new workspace file, you need to call the Reset() method on the Session object first. This method closes down everything and gives you a ‘clean’
Session object.
Pooling
Pooling enables you to reduce the overhead of creating each object from scratch. When an object is needed, it is pulled from the pool. When the object is not needed anymore, it is placed back into the pool to await the next request. Pooling in MapXtreme 2004 means that multiple
Session objects can be created and available for web requests. The WebSessionActivator class manages the lifetime of the Session object for each Web client request and has pooled and non-pooled modes of operation.
Pooled
Pooled mode creates a pool of ISession instances. There is one pool per ASP.NET application
(or AppDomain). When an ASP.NET request begins, the WebSessionActivator acquires an
ISession instance from the pool. This instance is then available during the execution lifetime of the request by calling Session.Current(). When the request ends, the WebSessionActivator releases the ISession instance back into the pool. To enable pooling in your application, use the following element in your Web.config file:
<configuration>
<appSettings>
<add key="MapInfo.Engine.Session.Pooled" value="true" />
</appSettings>
</configuration>
You can configure a minimum and maximum pool size. The minimum size specifies how many
ISession instances should be created when the pool is first accessed. The maximum size specifies the maximum number of pooled ISession instances to create.
In addition to the pool size, you can configure a timeout period which defines how long the
WebSessionActivator should wait for an ISession instance to become available when they are all acquired. Use Component Services to configure these options as they are specific to the computer where you install MapXtreme. You can run Component Services from Administrative
Tools in the Windows Control Panel.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
167
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
To run Component Services:
Chapter 13: Planning a Web Application
1.
Expand the Component Services > Computers > My Computer > COM+ Applications >
MapInfo.CoreEngine > Components.
2.
Select MapInfo.Engine.Session+PooledSession and then run the Action >Properties menu item to go to its properties.
3.
On the properties dialog, go to the Activation tab to configure the pool size and creation timeout.
Non-Pooled
This mode creates an ISession instance for each ASP.NET session. This ISession instance is available when you call Current within your application code. This is the default mode, to turn pooling off, use the following element in your Web.config file:
<configuration>
<appSettings>
<add key="MapInfo.Engine.Session.Pooled" value="false" />
</appSettings>
</configuration>
This is the default mode if this element is not present.
The lifetime of the ISession instance depends on the Session State configuration. The ISession instance is cached in memory for the lifetime of your ASP.NET session if you use server-based
Session State and the ASP.NET sessionState element in your Web.config file is set to InProc.
The ISession instance is created and disposed for each ASP.NET request if you use any other type of Session State configuration (e.g., client-based or server-based with sessionState element set to StateServer or SQLServer). See
Session State Management on page 171
details on how to configure Session State.
Advantages to Using Pooling
Pooling helps reduce the number of concurrent MapInfo.Engine.ISession instances. This occurs when you have an application that has several ASP.NET sessions at the same time.
Pooling helps to optimize the server’s resources. The more ISession instances you have in your process the more of resources are used.
A web application that has several ASP.NET requests running concurrently can use pooling to improve overall response time. By pooling the MapInfo.Engine.ISession instances, you reduce the number of requests running at the same time, which actually maximizes CPU utilization by reducing thread context switching. This is particularly useful when your requests are CPU intensive (e.g., Map image exports). The general recommendation is to have a pool size of 1-2 sessions per CPU.
Configuring COM+ Application Pooling
When pooling is on, COM+ settings are used. To configure COM+ Application Pooling for a
COM+ application:
1.
In the console tree of the Component Services administrative tool, right-click the
COM+ application you want to be pooled and then click Properties.
2.
On the Pooling & Recycling tab, under Application Pooling, enter a value for Pool Size, depending on the number of instances of your application that you want to have running.
3.
Click OK.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
168
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 13: Planning a Web Application
The following function in Visual Basic demonstrates how to set the COM+ Application Pooling value (represented by its ConcurrentApps property) for any COM+ server application that you choose. To use it from Visual Basic, add a reference to the COM+ Admin Type Library.
Function SetMyApplicationPooling( _ strApplicationName As String, _ lngPoolValue As Long ) _
As Boolean ' Return False if any errors occur.
SetMyApplicationPooling = False ' Initialize the function.
On Error GoTo My_Error_Handler ' Initialize error handling.
Dim objCatalog As COMAdmin.COMAdminCatalog
Dim objAppCollection As COMAdmin.COMAdminCatalogCollection
Dim objApplication As COMAdmin.COMAdminCatalogObject
Set objCatalog = CreateObject("COMAdmin.COMAdminCatalog")
Set objAppCollection = objCatalog.GetCollection("Applications") objAppCollection.Populate
For Each objApplication in objAppCollection
If objApplication.Name = strApplicationName Then objApplication.Value("ConcurrentApps") = lngPoolValue
MsgBox strApplicationName & _
" pooling value set to " & lngPoolValue
Exit For
End If
Next objAppCollection.SaveChanges
Set objApplication = Nothing
Set objAppCollection = Nothing
Set objCatalog = Nothing
SetMyApplicationPooling = True ' Successful end to procedure
Exit Function
My_Error_Handler: ' Replace with specific error handling.
MsgBox "Error # " & Err.Number & " (Hex: " & Hex(Err.Number) _
& ")" & vbNewLine & Err.Description
Set objApplication = Nothing
Set objAppCollection = Nothing
Set objCatalog = Nothing
End Function
To use the function, provide a string value for the COM+ server application name and an integer value for the desired Application Pooling setting. The following Visual Basic code shows how to set the Application Pooling value to 15 for the application named “MyApplication”:
Sub Main()
If Not SetMyApplicationPooling("MyApplication", 15) Then
MsgBox "SetMyApplicationPooling failed."
End If
End Sub
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
169
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 13: Planning a Web Application
Working with MapXtreme 2004’s State and Pool Settings
The Web.config File
The Web.config file is a central player in any ASP.NET web application. This file controls settings that are relevant to the specific ASP.NET application. Specifically this is where you make any changes to the State and Pooled settings. The following code shows the default implementation of a MapXtreme 2004 ASP.NET application:
<appSettings>
<add key="MapInfo.Engine.Session.Pooled" value="false" />
<add key="MapInfo.Engine.Session.State" value="HttpSessionState"/>
<add key="MapInfo.Engine.Session.Workspace" value="c:\my workspace.mws"/>
<add key="MapInfo.Engine.Session.ExitProcess" value="true" />
</appSettings>
The properties of MapInfo.Engine.Session, set in this file, identify the following:
•
Are Sessions pooled?
•
Is the Session state saved manually ( value="Manual"
) or automatically
( value="HttpSessionState"
)?
•
Where is the Workspace to be preloaded?
•
Should the ASP.NET process be forced to shut down when the AppDomain is unloaded?
Engine.Session.State Settings
The choice of state for your Session has implications to the performance of your application.
Use the sections below to determine the most appropriate configuration for your application.
HttpSessionState
When Engine.Session.State is set to HttpSessionState, the state of the entire ISession instance is automatically saved and restored using the Context.Session object.
Since the Context.Session itself is saved and restored based on ASP.NET's
<sessionState> element in your Web.config file, the lifetime of the ISession instance varies according to the setting and whether ISession is being pooled or not:
•
<sessionState>
is set to
Off
: No state is saved. No exceptions are thrown.
•
<sessionState>
is set to
StateServer
or
SQLServer
: When pooling is enabled, the
WebSessionActivator restores the previous session after acquiring a pooled ISession instance. At the end of the request, it saves the state before releasing the pooled
ISession instance back into the pool. When pooling is disabled, the
WebSessionActivator restores the previous state after creating a new ISession instance. At the end of the request, it saves the state before disposing of the ISession instance. This means that each request uses a new ISession instance.
•
<sessionState>
is set to
InProc
: When pooling is enabled, the WebSessionActivator throws a NotSupportedException because you cannot keep a pooled ISession instance acquired as it will exhaust the number of available ISession instances in the pool. When pooling is disabled, the WebSessionActivator creates the ISession instance and keeps it in memory for the lifetime of the ASP.NET session.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
170
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 13: Planning a Web Application
Manual
When Engine.Session.State is set to Manual, the state of the entire ISession instance is not automatically saved and restored.
This setting allows the user to manually save and restore the state based on the nature of your application. Since saving and restoring the entire state of the ISession instance could be costly, you can opt to save and restore only the portions of the state you know are changing, thus need state. Other portions could be preloaded using workspace preloading.
Session State Management
Server-side ASP.NET controls in an application, such as web controls, are stateless. This means that they are constructed, executed, and disposed of, on each session request. You need state management in your application in order to restore and save the state on each request.
In the
<system.web>
section of the Web.config file there is another important setting for the mode of the stateSession. In MapXtreme 2004 ASP.NET applications this can only be set to
StateServer or SQLServer. MapXtreme 2004 throws an exception if you set this value to the other possibility, InProc. Refer to Microsoft's online help to see the difference between
StateServer and SQLServer.
ASP.NET provides you with a variety of options to save state. You can use the
Control.ViewState object (instance of class StateBag) to restore and save view-specific information that is preserved with the client. The ViewState is sent back and forth between the client and the server stored as a hidden form field in the HTML web page.
For more information see the ASP.NET documentation (
<sessionState>
Element).
Session Settings
The Web.config file also manages the ASP.NET Session objects for the application through the
WebSessionActivator class. The WebSessionActivator class manages the lifetime of the session object for each Web client request. This class is an IHttpModule and has to be registered in your Web.config file in order for your application to work properly. If you are using
MapXtreme Web controls, this class is automatically registered at design-time. If you are developing your own ASP.NET Web application or service, you need to add the following XML element to your Web.config file, under the
<system.web>
element:
<httpModules>
<add type="MapInfo.Engine.WebSessionActivator, MapInfo.CoreEngine,
Version=1.0.0.*, Culture=neutral,
PublicKeyToken=93e298a0f6b95eb1" name="WebSessionActivator" />
</httpModules>
Also include the following elements under the
<compilation>
element in order for the application to include MapXtreme 2004 assemblies in its compilation and deployment:
<assemblies>
<add assembly="MapInfo.CoreEngine, Version=1.0.0.*,
Culture=neutral, PublicKeyToken=93e298a0f6b95eb1" />
<add assembly="MapInfo.CoreTypes, Version=1.0.0.*,Culture=neutral,
PublicKeyToken=f548bcba69d4b8da" />
</assemblies>
If you are using MapXtreme 2004 Web controls, this is also done automatically at design-time.
In that case, the MapInfo.Web assembly is also added. This assembly includes MapXtreme
2004 Web controls implementation:
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
171
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 13: Planning a Web Application
<add assembly="MapInfo.Web, Version=1.0.0.*, Culture=neutral,
‘PublicKeyToken=1687fa7c79f74305" />
Note:
Version=1.0.0.*
needs to reflect the version of the MapInfo assembly you are using.
An example of a valid assembly would look like
Version=1.0.0.75
.
The WebSessionActivator class manages the lifetime of the Session object for each Web client request. This class is only available if you are building an ASP.NET application or service. The
WebSessionActivator class currently has pooled and non-pooled modes of operation.
Optimizing by Selectively Saving Objects
If you set State to HttpSessionState, MapXtreme 2004, through the ASP.NET framework, automatically handles saving or restoring the application’s state. In this case, the entire
Session object is serialized. This is not the ideal approach, in regards to optimizing performance of the server, because it saves and restores everything (i.e., Catalog, Maps/
Layers, Selections, etc.). Saving the entire Session object allows for quick implementation, but includes a lot of unnecessary overhead.
If you set State to Manual, MapXtreme 2004 does not save or restore any state automatically.
This allows you to selectively choose which objects within the Session really need to be saved and restored because the user is likely to change them. Selection of individual objects is done by is done by placing objects to save and restore into the ASP.NET Session object. For example, the following code snippet saves and restores state for all of the Layers in a Map:
// Save the map's layers collection
Session["Layers"] = map.Layers;
Note:
The ASP.NET framework automatically handles restoring state for the application. By the time the Page_Load() method is called, all of the serialized objects have been deserialized.
Examine your application to determine which objects need to be serialized. The decision about what to serialize depends on what the application allows the user to change. For example, if the application allows users to change properties on layers or create or remove layers or themes, the application would need to serialize the entire Map.Layers collection. If the application only allows the user to pan and zoom, only the map's center and zoom values would need to be serialized. The easiest way is to serialize the entire Map object. However, this saves every property on the Map and all of the Map's Layers, which is overkill if all the application is doing is changing the map's center and zoom. One way to deal with this is to serialize the map’s center and zoom and then reapply these values in the Page_Load() method. This approach is more efficient than saving the entire Map object as there is far less information being serialized.
Optimizing State Handling Code by Preloading a Workspace
You can configure the Session to preload one or more workspaces on creation. This is particularly useful on an ASP.NET application since it allows you to automatically initialize the
Session with its initial state. To configure this, specify the file(s) to preload in the
<appSettings>
element in the Web.config file with the filenames separated by either a comma or semicolon (
,
or
;
), as follows:
<add key="MapInfo.Engine.Session.Workspace" value="c:\MyWorkspace.mws;c:\MyWorkspace2.mws" />
This element preloads workspaces C:\MyWorkspace.mws and C:\MyWorkspace2.mws into your session object.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
172
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 13: Planning a Web Application
Preloading workspaces and setting state to “Manual” helps to optimize the performance of your application. A typical application usually modifies only a portion of its workspace. For example, an application that shows routes can optimize its response time by preloading the workspace that includes the map being used. It then saves and restores the state of the temporary Table and FeatureLayer being used to display routes. When a new ASP.NET session starts, the application ensures the temporary table and layer are present and empty.
This is done because the state of the pooled ISession might have been used by a different
ASP.NET session request.
Nothing needs to be initialized because the ISession is already configured to preload the workspace and the application is not changing anything other than the temporary table and layer. After the workspace is loaded you can save or restore the state of the table and layer by using the Context.Session table in ASP.NET by adding the table and the layer (in that order) during the Page_Unload event. (You need to make sure that the
<sessionState>
in configured to be
StateServer
or
SQLServer
in the Web.config file.) By taking care of the initial state of the temporary table and layer through application code and subsequent state using the
Context.Session table, your application does not waste time saving or restoring state that does not change.
For a good example of how this whole process works look at the sample web application installed with MapXtreme 2004. the application is called FindSampleWeb and it contains a good illustration of session state management.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
173
MapXtreme2004_DevGuide_A4.pdf
Using the Desktop Tools
14
The MapInfo.Tools namespace contains all of the classes that allow you to create tools in MapXtreme
2004.
In this chapter:
!
!
!
!
Developer Guide
Overview of the MapInfo.Tools Namespace
Chapter 14: Using the Desktop Tools
The MapInfo.Tools namespace contains the all the classes that allow you to create stock and customizable tools for your MapXtreme 2004 application. The available tools can be broken down into five different categories: View tools, Select tools, Add tools, Base tools, and Custom tools.
The stock Select Tools include SelectPoint, SelectPolygon, SelectRect, SelectRadius, and
SelectRegion. The stock Add Tools include AddPoint, AddLine, AddPolyline, AddPolygon,
AddCircle, AddEllipse, AddRectangle, and EditText. For each Add tool, there are Style and
Insertion Layer properties.
Custom Tool base classes include Point, Line, Polyline, Polygon, Circle, Ellipse, and
Rectangle. These are provided to create custom tools. You can derive custom tools from the
Custom Tool base classes, or even from stock tool classes.
Tools can be assigned to a particular mouse button (left, right, or middle).
The diagram below shows a UML representation of the MapTool class.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
175
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Available Tools
Chapter 14: Using the Desktop Tools
The Tools included in this namespace can be divided into five categories: Add tools, Custom tools, Base tools, View tools, and Select tools. Within these categories are similar shape tools
(Ellipse, Arc, Circle, Rectangle, Polygon, Point, Line, and Polyline).
Add Tools
The Add family of tools (AddArcMapTool, AddCircleMapTool, AddEllipseMapTool,
AddLineMapTool, AddPointMapTool, AddPolygonMapTool, AddPolylineMapTool, and
AddRectangleMapTool) are all based upon the AddMapTool class. The Add tools add a particular geometric object to your map. In order to add an object to a map, you must have an insertion layer in your map and it needs to be active. This layer is where the object resides after it is created. The size and shape of the particular object depends on the tool used and can be constrained through the use of the modifier keys (Shift and Ctrl) while the tool is being used.
Custom Tools
The Custom tools (CustomArcMapTool, CustomCircleMapTool, CustomEllipseMapTool,
CustomLineMapTool, CustomPointMapTool, CustomPolygonMapTool,
CustomPolylineMapTool, and CustomRectangleMapTool) are very basic tools that only fire the events. Use these classes to design custom behaviors for specific tools. For example, you can use the CustomEllipseMapTool to draw green Ellipses with a red outline every time the tools is used. Use the various tool events (see
behaviors to respond to specific events generated by the tools.
Select Tools
The Select family of tools (SelectMapTool, SelectPointMapTool, SelectPolygonMapTool,
SelectRadiusMapTool, SelectRectMapTool, and SelectRegionMapTool) select points and regions that fall within the geometric object shaped by the use of these tools. The
SelectPointMapTool can rotate objects. Select node mode allows individual points to moved, added, or removed from objects. Dynamic Selection shows what objects are in the selection as the mouse is being moved.
View Tools
The View tools (ZoomMapTool, CenterMapTool, and PanMapTool) change the view of the map accordingly to the tool being used.
Shape Tools
The Shape Tools draw geometric features to your map. Most of these tools are used by “clickand-drag.” As you click and then drag to another location on your map, a rubber-band image is displayed showing the current size and shape of the object being drawn. Each of these tools uses the ESC key to cancel the completion of an object (if appropriate).
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
176
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 14: Using the Desktop Tools
Line Tools
The tools included in this group are AddLineMapTool and CustomLineMapTool. These tools draw a Line. The tool is activated by clicking and dragging from the beginning point to the end point. Releasing the mouse button creates the Line. If the Shift key is pressed while dragging, the angle of the Line is constrained to multiples of 45°. If the Ctrl key is pressed while dragging, the line doubles in length and height. Pressing Esc before releasing the mouse cancels the operation.
Polyline Tools
These tools draw a Line with multiple segments. The tool is activated by clicking on a point and then clicking on a subsequent point. When you are done clicking on points, click again on the last point and the Polyline is drawn. If the Shift key is pressed while dragging, the angle of the
Line is constrained to multiples of 45°. The Ctrl key has no effect on this tool. Pressing Esc before completing the line, cancels the operation.
Ellipse and Arc Tools
The tools included in this group are: AddArcMapTool, AddEllipseMapTool, CustomArcMapTool, and CustomEllipseMapTool. These tools draw an Ellipse. The tool is activated by clicking and dragging from a point on one side of the perimeter to a point on the other. Releasing the mouse button creates the Ellipse. Note that the drawn object is always axis-aligned. If the Shift key is pressed while dragging, the Ellipse is constrained to a circle where the radius is constant. If the
Ctrl key is pressed while dragging, the Ellipse is drawn with the starting point in the center.
Pressing the Esc key before releasing the mouse cancels the operation. The Ellipse that is drawn is always axis-aligned.
Arc tools draw one quarter of the axis-aligned Ellipse. All other behaviors of the Ellipse tools apply to the Arc tools as well.
Circle Tools
The Circle tools draw a Circle. This is equivalent as using the Ellipse tool while holding down the Shift key. The tool is activated by clicking and dragging from the center point of the Circle center to a point on the perimeter. As you drag, you will see the size of the Circle expand around that center point. Releasing the mouse button creates the Circle. If the Ctrl key is pressed while dragging, the Circle is drawn from perimeter point to perimeter point. Pressing the Esc key before releasing the mouse cancels the operation.
Rectangle Tools
These tools draw a Rectangle. The tool is activated by clicking and dragging from one corner to the opposite corner. Releasing the mouse button creates the Rectangle. Note that the drawn object is always axis-aligned. If the Shift key is pressed while dragging, the Rectangle is constrained to a square. If the Ctrl key is pressed while dragging, the Rectangle is drawn with the starting point in the center. Pressing the Esc key before releasing the mouse cancels the operation.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
177
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Customizing Tools
Chapter 14: Using the Desktop Tools
Tools can be customized in two ways. They can be customized by creating a subclass of an existing Tool, or by using one of the Tools in the Custom Tools group. Any of the Tool classes provided in MapXtreme 2004 can be customized by creating a sub class derived from the desired particular Tool class. An example of this is deriving from AddLineTool. The tool could be changed to a particular behavior (e.g., always beep when line is drawn), a particular appearance (e.g., always draw the line in red), or to a particular functionality (e.g., always constrain line drawing to 90 degree increments). Another example would be to create two different tools based upon the same tool. The AddPointTool could be used to subclass two other tools that each use different symbols for indicating two kinds of points on a map. Assign one tool to the left mouse button and assign the other to the right mouse button.
The following code example illustrates a customization of the AddPolygonTool.
using MapInfo.Mapping; using MapInfo.Styles; using MapInfo.Tools;
// set the map layer filter for the insertion layer
IMapLayerFilter insertionLayerFilter =
MapLayerFilterFactory.FilterByLayerType(LayerType.Normal);
// set the default style for the new objects (red fill with blue
// border)
CompositeStyle style = new CompositeStyle
(new MapInfo.Styles.AreaStyle(
MapInfo.Styles.StockStyles.BlueLineStyle(),
MapInfo.Styles.StockStyles.RedFillStyle()));
AddMapToolProperties addMapToolProperties = new AddMapToolProperties(
MapLayerFilterFactory.FilterForTools(map, insertionLayerFilter,
MapLayerFilterFactory.FilterVisibleLayers(true),
"CustomPolygonAddMapToolProperties", null), style);
// create an Add polygon tool with non-default properties
MapTool maptool = new AddPolygonMapTool(true, mapcontrol.Viewer, mapcontrol.Handle.ToInt32(), mapcontrol.Tools, new MouseToolProperties(Cursors.Default, Cursors.Default,
Cursors.Default),mapcontrol.Tools.MapToolProperties, addMapToolProperties);
// add it to the MapTools collection
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
178
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Tool Events
Chapter 14: Using the Desktop Tools
The Tools namespace supports improved Tool events with information and the ability to cancel the tool operation. The Select Tools event lists the items being selected or deselected. Events can be fired at every stage of use of a particular tool. In your code you can trap certain moments in the lifecycle of the usage of a tool. Adding code to particular events gives you the maximum flexibility on customizing the use of each tool in your mapping application.
The events in the namespace are as follows:
FeatureAddingEventArgs
This event is fired when an add tool is about to draw an object.
FeatureAddedEventArgs
This event is fired when an add tool has added an object to a table and map.
FeatureSelectingEventArgs
This event is fired when a selection tool is about to change the selection.
FeatureSelectedEventArgs
This event is fired when a selection tool changes the selection.
FeatureChangingEventArgs
This event is fired when a selection tool is about to change a feature. Use this event to check to see if the change that is going to happen is valid.
FeatureChangedEventArgs
This event is fired after a selection tool changed a feature.
NodeChangedEventArgs
This event is fired when a selection tool alters the nodes in a selection.
NodeChangingEventArgs
Fired when a selection tool is about to change a node of a selected feature. Use this event to check to see if the change that is going to happen is valid.
ToolActivatedEventArgs
This event is fired when a mouse tool is activated.
ToolActivatingEventArgs
This event is fired when mouse tool is about to be activated.
ToolEndingEventArgs
This event is fired when a mouse tool is about to end. This is a good place to have a a new action begin.
ToolUsedEventArgs
This event is fired when a mouse tool is in use. Use this event to set flags for the beginning, middle, and end of a the sequence of mouse clicks.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
179
MapXtreme2004_DevGuide_A4.pdf
Dialogs and Controls for
Desktop Applications
15
This chapter contains descriptions of the various controls and dialogs that can be used when creating a graphical user interface for a MapXtreme 2004 application.
In this chapter:
!
Overview of the MapInfo.Windows.Controls Namespace . . . . . . . . . . . . . . . . . . . . . 181
!
!
Overview of the MapInfo.Windows.Dialogs Namespace . . . . . . . . . . . . . . . . . . . . . . 184
!
Developer Guide Chapter 15: Dialogs and Controls for Desktop Applications
Overview of the MapInfo.Windows.Controls Namespace
The MapInfo.Windows.Controls namespace contains classes that implement controls in desktop applications. The use of Windows controls is quite simple as you drop the desired control onto your form and use the various properties to configure them to your specifications.
You will find that the controls in this namespace are similar to controls found in the
MapInfo.Web.UI.WebControls namespace. However, the controls in each namespace cannot be substituted for each other. The controls in this namespace are specifically to be used in desktop applications. For information about controls for web-based applications, see
Controls in Chapter 12 on page 150
.
Note:
Some controls do not display at design time. When dragged and dropped onto a form they merely appear as a rectangle. These controls display properly at run time.
The desktop controls included with MapXtreme 2004 can be categorized into Standard
Controls, and Map-specific controls. Standard controls include buttons, view tools, label tools, all kinds of boxes, etc. These are quite similar to (and in many cases, inherited from) classes from the System.Windows.Forms namespace.
The Map-specific controls are specific to MapInfo’s mapping implementations. These include controls that set or modify aspects of object styles, labels, layers, coordinate systems, themes, and other related functions.
Key Controls to Use in Applications
While all the controls included in MapXtreme 2004 are useful, several stand out from the rest as being central to most mapping applications. The following sections discuss these. Each of these controls assume the presence of the appropriate references included in your project.
(These are automatically included if you have created your project from the mapping template installed with MapXtreme 2004 in Visual Studio.)
Note:
If you are not creating your project from one of our templates, please make sure to add references to the components, MapInfo.CoreEngine, MapInfo.Windows,
MapInfo.Windows.Dialogs, and MapInfo.Windows.Framework.
The Map Control
The Map Control is necessary for every application that displays a map. To add a Map Control to your form, merely drag and drop it onto your form from the toolbox in Visual Studio. Once the
Map Control is on your form there are several operations you can perform on it to make your map more useful to the user.
All of the modifications to the MapControl can be found in the Properties Window when the
Map Control is selected on your form. At the bottom of the window are four menu items: L
OAD
M
AP
..., C
LEAR
M
AP
, L
AYER
C
ONTROL
..., and C
REATE
T
HEMATIC
.... L
OAD
M
AP
... opens a standard file picker from which the developer can choose a map to preload into the
MapControl. C
LEAR
M
AP
clears any map already in the control, either when adding the Map
Control to the form or somewhere in the middle of the design process. L
AYER
C
ONTROL
... launches a Layer Control dialog box that allows you to customize the map (see
). C
REATE
T
HEMATICS
... launches the Create Theme Wizard (discussed in
) allowing you to create a theme on the map.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
181
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 15: Dialogs and Controls for Desktop Applications
The Map Control also has several properties relating to the loaded map that can be preset so that the map shown at run time is further customized for the specific application. Properties that can be modified include Zoom level, coordinate system, Map Center, and settings for three mouse buttons during run time. The mouse buttons can be set to Zoom, Pan, Draw geometries,
Select, or any of several other map tools.
You can also set a design time tool to further manipulate the map while working in Visual Studio
.NET. Design time functionality includes Zoom in, Zoom Out, Select, Pan, Center, and the default arrow. Clear Map removes all layers from the MapControl’s map and closes the corresponding tables (if they are not in use in another MapControl.
A Form showing a MapControl, a LayerControl, and a MapToolBar
The MapToolBar
The MapToolBar combines several of the map tool controls (e.g., zoom in, open table) into a single control.
If you create a new MapXtreme 2004 Map application using the templates that comes with
MapXtreme 2004, the application will contain a MapToolBar. Alternatively, you can add a
MapToolBar to your form, by dragging it onto your form from the Visual Studio toolbox. By default, the MapToolBar contains the following buttons: OpenTable, LayerControl, Select,
ZoomIn, ZoomOut, Pan, and Center.
You can also add buttons to the MapToolBar using the following steps:
1.
Open the ToolBarButton Collection Editor by clicking on the elipsis (...) next to the
Buttons property in the Properties window
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
182
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 15: Dialogs and Controls for Desktop Applications
The ToolBarButton Collection Editor is displayed.
2.
Click on the A
DD
button.
This creates a new MapToolBarButton below the last one in the list.
Note:
If you would like to add a customized tool you need to click on the arrow next to the Add button and choose ToolBarButton. You need to write a customized handler for the new button.
3.
Name the new button.
4.
Select the ButtonType from the right-hand pull-down menu.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
183
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 15: Dialogs and Controls for Desktop Applications
5.
Click OK.
The MapToolBarButton is now created and added to the button bar. The newly added tool works in the default manner.
The Layer Control
The Layer Control dialog box shows all the layers that make up the current Map window and the status of the layer attributes. These attributes are: visible, editable, selectable, and auto label. The icons above each check box column represent the attributes. ToolTips display over the attribute icons when you move your cursor over them to help familiarize yourself with each icon. It is easy to change a layer’s, or multiple layers’, attributes using the check boxes.
The Layer Control also has options available to change the Display and Label settings; modify any thematic maps you have displayed; and reorder, add, or remove layers.
You can rearrange layers in the Layer Control by dragging and dropping them in the
LayerControl Layers list.
Note:
Dropping a layer onto a Label Layer adds a new set of labels to the Label Layer. This can happen by accident—for example, if you were attempting to move a layer to the spot just above the Label Layer. Similarly, if you drop a layer onto a Group Layer, the layer that you drop will be placed inside the Group Layer, which might not be what you wanted.
Tip: If you want the dropped layer to be placed outside of the Group Layer or Label
Layer, hold down the Shift key before you drop the layer. As you press and release the
Shift key, the cursor changes to indicate whether the dropped layer will go above or inside the target layer onto which you are dropping.
The Layer Control puts all the functionality of the Layer Control Dialog Box onto a form. After adding the control to your form, a single line of code is necessary in the Form_Load() method to link the LayerControl to the MapControl’s map. layerControl1.Map = mapControl1.Map;
Overview of the MapInfo.Windows.Dialogs Namespace
The MapInfo.Windows.Dialogs namespace contains classes that create dialog boxes with specific functions. Contrary to controls, dialog boxes are not visible during design-time and can only be created and configured in code. You can create your own customized dialog boxes using classes from the MapInfo.Windows.Controls namespace and then utilize them by calling the System.Windows.Forms.Form.ShowDialog() method.
To use a particular dialog box in your application, add the class to your code page. For example: using MapInfo.Windows.Dialogs
private void DoLayerControl()
{
LayerControlDlg layerControl = new LayerControlDlg(); layerControl.Map = mapControl1.Map; layerControl.ShowDialog(this);
}
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
184
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 15: Dialogs and Controls for Desktop Applications
The code above displays the Layer Control dialog box when the DoLayerControl() method is called.
CreateThemeWizard
The CreateThemeWizard is a convenience class used to create thematics. There are three basic steps to creating a theme: 1) Select the theme type; 2) Select the table and columns to use for the theme; and 3) Modify the theme attributes (style, number of ranges, etc.). The wizard ties all these settings together into a sequence of dialog boxes to make theme creation as simple and consistent as possible for the end users of MapXtreme applications.
Using the CreateThemeWizard
The CreateThemeWizard displays some of several different dialog boxes, depending on the choices made by the user. The first dialog box displayed is always the first step: Select a theme type.
Create Theme: Step 1 of 3 dialog box
If the user chooses a single value theme type (Ranged, Dot Density, Individual Value, or
Graduated Symbol) the second dialog box displayed allows them to choose a table and single column.
Create Theme: Step 2 of 3 dialog box (single column)
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
185
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 15: Dialogs and Controls for Desktop Applications
If the user chooses a multiple value theme type (Pie or Bar), the second dialog box displayed allows them to choose multiple columns of data from which to create the theme.
Create Theme: Step 2 of 2 dialog box (multiple columns)
The dialog box that follows this one is specific to the type of theme chosen in Step 1. The following figure shows a Step 3 dialog box specific to a ranged theme.
Create Theme: Step 3 of 3 dialog box (Ranged Theme)
The Create Theme Wizard is accessible from many different places at design time and at runtime, depending on the controls in your application. At design-time the CreateTheme
Wizard can be accessed from the menu at the bottom of the MapControl properties window and also from the LayerControl by right-clicking on a layer and choosing A
DD
T
HEME
....
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
186
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 15: Dialogs and Controls for Desktop Applications
Developing with the CreateThemeWizard
To add a CreateThemeWizard programmatically to your application write something similar to the following example code.
using MapInfo.Windows.Dialogs;
CreateThemeWizard themeWiz = new CreateThemeWizard(mapcontrol1.Map, this);
Methods
Once the CreateThemeWizard is created, the CreateTheme() method can be called to create the theme. An optional string parameter can be added to set the theme’s alias. The alias can be used to access the theme from the Layers collection in the case of an ObjectTheme (Bar,
Pie, GraduatedSymbol) or the Modifiers collection in the case of a FeatureStyleModifier
(Ranged, RangedLabel, IndividualValue, IndividualValueLabel, Dot Density). You would access the theme to modify or delete it.
ITheme theme = themeWizard.CreateTheme("theme1");
If you already know which table is to be themed or which label source to use for a label theme, you can use the methods, CreateFeatureTheme() (for tables) or CreateLabelTheme() (for labels).
Properties
There are a few properties that can be useful for obtaining information about the theme creation. WizardResult contains an enumeration WizardStepResult that allows you to check how the user exited the wizard. These choices are WizardStepResult.Done and
WizardStepResult.Cancel. These are useful to appropriately update the controls or menus in your application.
Here’s an example of the use of this.
if (createTheme.WizardResult == WizardStepresult.Done
{
// Update the menus mnuRemoveTheme.Enabled = true; mnuModifyTheme.Enabled = true;
}
SelectedLabelSource, SelectedLayer, and SelectedThemeType are properties that can be used to find out which layer/label source the theme has been applied to. This is useful when you want to provide the ability to modify a theme and need to access that object.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
187
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 15: Dialogs and Controls for Desktop Applications
Customizing Controls and Dialog Boxes
MapXtreme 2004 ships with a wide variety of dialog box classes in the
MapInfo.Windows.Dialogs namespace. Each of the dialog boxes represented there have possible customizations specific to each one. To modify a specific dialog box, merely assign values to the different properties that are specific to each dialog box. Since there are so many, it is not practical to list all the possible customizations here. Please refer to the online reference for details about each dialog box.
An example of customizing a dialog box is as follows: The LineStyleDlg class creates a Line
Style Dialog Box. This dialog box can be created in either a sparse style mode (where nothing is selected when opened), or in a mode where some choices are visible but not enabled
(grayed out).
The customization provided by setting property values is obviously limited to the specific dialog object being modified. To create a new dialog box based upon a design of an established one is done by adding some controls to a new form at design time. For example, to create a modified
LineStyle Dialog Box, you can drop a LineStyle Control on a new form and then add other controls to that form, making, in effect, a modified LineStyle Dialog Box.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
188
MapXtreme2004_DevGuide_A4.pdf
Stylizing your Maps
16
Styles in MapXtreme 2004 affect many components of a mapping application, not just how a map feature looks. Styles are used for labels, text, themes, legends, selection and presentation with many controllable attributes so you can design practically any style you like.
This chapter discusses styles in terms of the MapXtreme 2004 framework, specifically the
MapInfo.Styles namespace.
In this chapter:
!
!
!
!
!
Developer Guide
Overview of the MapInfo.Styles Namespace
Chapter 16: Stylizing your Maps
The MapInfo.Styles namespace highlights the new Styles object model for MapXtreme 2004.
The Style class is the base class of all styles. Classes that derive from Style include AreaStyle,
BaseLineStyle, BaseInterior, BasePointStyle, CompositeStyle, Font, RasterStyle, and
TextStyle. Derived from BaseLineStyle is the SimpleLineStyle class. Derived from BaseInterior is the SimpleInterior class. Derived from BasePointStyle are the BitmapPointStyle,
FontPointStyle, and SimpleVectorPointStyle classes. Additionally, GridStyle is derived from
RasterStyle to include grid specific style settings. A StockStyles class is provided to create common style types.
You cannot instantiate the abstract style classes Style, BaseLineStyle, BaseInterior or
BasePointStyle. You must create a particular type like SimpleLineStyle, or create them as a
CompositeStyle.
All style classes support the ability to be applied in a sparse manner. See the section on
FeatureOverrideStyleModifiers.
Styles are used in many areas of MapXtreme 2004 including the lines, interior fills and point styles that represent geographic features. Styles are also an integral part of labels, text, layouts, themes, overrides, legends and selections. Style properties range from standard color fills, line width and point size, to background effects, bitmaps as point styles, and rotation angle.
Practically any style property you can imagine is available for you to incorporate into your application. Styles can be changed globally or per feature, overridden for the current display or made as a permanent change.
MapXtreme 2004 comes with a number of sample styles to get you started. There are more than 170 interior fill patterns, approximately 120 line style patterns, and approximately 70 bitmap point style images. You can create bitmap images in any application that can create bitmaps, like MS Paint or Paint Shop Pro. There are virtually no size limitations on the image; however, the ability of MapXtreme 2004 to display it will depend on available memory. The image does not have to be square and can also have up to 24-bit color depth. To make sure the image is displayed at the height and width you want, select the 'Display at actual size' option for
BitmapPointStyles. Once the image is created, place it in the CustSymb directory. Custom symbols are located in C:\Program Files\Common Files\MapInfo\MapXtreme\6.0\CustSymb folder.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
190
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 16: Stylizing your Maps
Additionally, MapXtreme 2004 ships with style controls and dialogs that allow you to rapidly add them to a form or web application. See the ChangeStyles and FeatureStyles sample applications under the Samples folder which bring together all the style classes discussed in
this chapter. For more information on form style controls and dialogs see
MapInfo.Windows.Controls Namespace in Chapter 15 on page 181
Web Controls in Chapter 12 on page 150
Regarding MapBasic styles from previous releases of MapX and MapXtreme, many of the style classes have a ToString method, which supports getting a MapBasic string representation of the style, if it is supported.
Style Descriptions
AreaStyle
The AreaStyle class contains style properties used for drawing regions. Regions are drawn using a BaseLineStyle and BaseInterior.
BitmapPointStyle
The MapInfo BitmapPointStyle class contains style properties for drawing points using custom bitmaps ( ). Use this class for marking point locations. BitmapPointStyle is one of three types of supported point styles, the others being FontPointStyle and SimpleVectorPointStyle.
BitmapPointStyle has a ShowWhiteBackground property; if set to false, any white pixel in the bitmap is transparent. By default, ShowWhiteBackground is set to false. For example, you may wish to use your corporate logo to represent office locations worldwide, but do not want to cover up other map features in the immediate area. There are other settings that control how
BitmapPointStyles are displayed. See the BitmapStyles enumeration in the online help for more details.
MapXtreme 2004 ships with a number of bitmap point styles to get you started. They are located in the CustSymb directory. You can also add your own bitmap images to this directory.
The maximum number of images allowed is 32,767.
CompositeStyle
The CompositeStyle class encompasses the collection of all the style types used for default styles, modifier styles, and layer override styles. The CompositeStyle can also be used to describe styles for the Collection object type. The style types contained are AreaStyle, a
BaseLineStyle derived class, TextStyle, a BasePointStyle derived class, RasterStyle and
GridStyle. The CompositeStyle can be constructed with any or all of these types, but must contain at least one of the above.
For example, you can create a style override (a FeatureOverrideStyleModifier) to alter the appearance of all features in a layer. Since a single layer can contain points and lines and regions, you might need to specify point, line and area styles when you build your style override. You can specify all necessary style types in one CompositeStyle object, which you then pass to the FeatureOverrideStyleModifier constructor.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
191
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 16: Stylizing your Maps
SimpleInterior
The MapInfo SimpleInterior class contains style properties used for filling the interior of regions.
SimpleInterior attributes include pattern, foreground and background color, and background transparency. The default for a SimpleInterior is a solid white interior.
Font
The MapInfo Font class contains style properties used for drawing text. Attributes for fonts, include bold, italic, underline, strikeout, shadow, halo, all caps, double space, size, foreground and background color. You can also change the font type (e.g., Arial, Times New Roman) and the font size. Note that the outline font property has been removed. To create an outline, use halo with a black background.
FontPointStyle
The FontPointStyle class contains style properties used for drawing points using mainly the
MapInfo.Styles.Font class. You can customize the point size, font color, angle of rotation and other font properties. The maximum point size allowed is 240 points.
GridStyle
This is a helper class containing display style information about a grid such as color inflections, null cell color and transparency. A grid is a map of continuous color gradation that represents interpolated data values. For more information on grids see
RasterStyle
This is a helper class containing display style information for a raster image including brightness, contrast, grayscale (color on/off), transparency, and translucency. For more information on raster images see
Chapter 17: Working with Rasters and Grids
.
Hillshade
This is a helper class used to store the parameters for hill shading on a grid. Hill shading, also called relief shading, can be added to grid maps to show the effect of a light source on the map.
This gives a grid map greater definition, particularly useful for elevation maps. Hill shade properties include the horizontal and vertical angles of the light source, and a vertical scale factor. For more information on grids see
Chapter 17: Working with Rasters and Grids
Inflection
This is used to hold a single inflection point which associates a color with a value. A grid has an array of inflections to represent its colors. A grid map is a map that shows a gradual color change across an area. The blending of one color into the next is due to the inflection. For more information on grids see
Chapter 17: Working with Rasters and Grids
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
192
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 16: Stylizing your Maps
SimpleLineStyle
The SimpleLineStyle class contains style properties used for drawing polylines based on the
MapBasic Pen clause. It is used for map features such as streets and cable lines, as well as borders around regions. Attributes to describe SimpleLineStyles include pattern, width (in pixels or points) and color. The default for a SimpleLineStyle is a solid black 1-pixel wide line.
Units for SimpleLineStyle are pixels (default) or points.
The LineWidth class in the MapInfo.Styles namespace is a helper class used to define the width and units of a line style.
BasePointStyle
This is an abstract base class for all MapInfo point styles. It cannot be instantiated.
SimpleVectorPointStyle, BitmapPointStyle and FontPointStyle derive from this class.
BaseLineStyle
This is an abstract base class for all MapInfo line styles. It cannot be instantiated.
SimpleLineStyle derives from this class.
BaseInterior
This is an abstract base class for all MapInfo interior styles. It cannot be instantiated.
SimpleInterior derives from this class.
StockStyles
This class contains static methods to create various default style objects, including black, blue, red and white interiors, black, blue, and red lines, hollow interiors and lines, and default fonts and point styles.
SimpleLineStyle redLine = StockStyles.RedLineStyle( );
TextStyle
This class contains style properties used for drawing text. It contains a MapInfo.Styles.Font class and a BaseLineStyle derived class for callout lines. The BaseLineStyle is optional (the
TextStyle may or may not contain one).
SimpleVectorPointStyle
This class contains style properties for drawing points using MapInfo's 3.0 Compatible proprietary font (MapInfow.fnt ships with MapXtreme 2004). SimpleVectorPointStyle properties include color, point size and the shape code of the actual symbol you wish drawn for the point.
The standard set includes symbols 31 through 67.
Note:
Another symbol font set, called MapInfo Symbol, is a TrueType font set that displays using the FontPointStyle class.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
193
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Pre-defined Styles and the StyleRepository Class
Chapter 16: Stylizing your Maps
MapXtreme 2004 ships with a variety of bitmap images covering many themes that can be used as bitmap point styles. More than 170 fill patterns and line styles are also available for use. These are all installed by the application and accessible either through the style dialogs
(e.g., LineStyleDlg) or through the various StyleRepository classes.
StyleRepository Class
The StyleRepository class contains style collection classes (VectorSymbolRepository,
BitmapSymbolRepository, LineStyleRepository, InteriorStyleRepository), which allows you to iterate through all current styles, as well as reload the collections with new styles from a specific file(s) or directory. The StyleRepository class also contains a repository
(TrueTypeFontInfoRepository) that represents information about the TrueType fonts installed on the system.
The VectorSymbolRepository represents the set of symbols from the MapInfo 3.0 Compatible symbol set. The BitmapSymbolRepository represents the set of images currently found in the
CustSymb directory. The LineStyleRepository represents the current set of patterns available for line styles. And the InteriorStyleRepository represents the set of interior patterns available.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
194
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Using Styles
Chapter 16: Stylizing your Maps
Styles and Layer Control
Use LayerControl at design or runtime to modify and override styles. See the sample application LayerControl for an introduction to the MapInfo.Windows.Controls.LayerControl object model. This code sample uses a LayerControl object directly on a form; it does not demonstrate using the LayerControlDlg dialog box, which is a related, but separate class.
Every operation demonstrated in this code sample could be applied to a LayerControlDlg object, as well, since the LayerControlDlg class exposes a LayerControl property.
Overview of the MapInfo.Windows.Controls Namespace in
Chapter 18: Using the Workspace Manager
.
Creating a Custom Bitmap Style
You can create bitmap images in any application that can create bitmaps, like MS Paint or Paint
Shop Pro. There are virtually no size limitations on the image; however, the ability of
MapXtreme 2004 to display it will depend on available memory. The image does not have to be square and can also have up to 24-bit color depth. To make sure the image is displayed at the height and width you want, select the 'Display at actual size option' for BitmapPointStyles.
Once the image is created, place it in the CustSymb directory.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
195
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Overriding Styles
Chapter 16: Stylizing your Maps
Styles can be permanently changed for features by saving the new style to the table. Styles for features can also be changed by overriding the current style with another. This does not change the style permanently. It only changes it for the current display. For example, a ranged theme overrides the style of a region object to shade it. See
for more information.
Style can also be overridden for labels. This section introduces you to the main style override class for features. See more about features and labels in the chapter on the Mapping namespace
Layers in Chapter 6 on page 57
Labels in Chapter 6 on page 59
FeatureOverrideStyleModifiers
This class implements FeatureStyleModifier to provide override style functionality for features.
Its Style property is a composite style object that is used to specify what parts of a feature's style to override.
Code Sample: FeatureOverrideStyleModifier
The following sample demonstrates how to use FeatureOverrideStyleModifier and layer
FeatureStyleModifiers to change styles of various features within a map.
In this snippet from the \Sample\Features\ChangeStyles.csproj, we want to override the world capitals layer with a single yellow symbol, but not change the point size.
using MapInfo.Styles; using MapInfo.Mapping;
// Get the layer we want
FeatureLayer fLyr = this.mapControl1.Map.Layers["worldcap"] as FeatureLayer;
// Create a sparse point style
SimpleVectorPointStyle pointStyle = new SimpleVectorPointStyle();
// Change the color and code and turn just those attributes on; this
// changes all point styles to this yellow vector symbol, but does not
// change any point style sizes.
pointStyle.Color = Color.Yellow; pointStyle.Code = 55; pointStyle.Attributes = StyleAttributes.PointAttributes.VectorCode |
StyleAttributes.PointAttributes.Color;
// And apply to the layer
FeatureOverrideStyleModifier fsm = new
FeatureOverrideStyleModifer
(null, new CompositeStyle(pointStyle)); fLyr.Modifers.Append(fsm);
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
196
MapXtreme2004_DevGuide_A4.pdf
Working with Rasters and Grids
17
The MapInfo.Raster namespace contains all of the classes that control the use and display of raster and grid images in MapXtreme 2004. Rasters are computer graphics that are composed of pixels that render a whole image. Many satellite images are rendered as raster images. Grid images are thematic maps that show a continuous gradation of color to represent interpolated information.
In this chapter:
!
!
!
Developer Guide Chapter 17: Working with Rasters and Grids
Overview of the MapInfo.Raster Namespace
The MapInfo.Raster namespace exposes the full functionality of MapInfo’s C/C++ Raster and
Grid Engine APIs. Raster images are bitmaps that provide useful background and reference layers to maps. Grid images are a type of theme that shows a continuous gradation of color across the image. The gradation represents an interpretation of the underlaying data. Grid images are rasters that have data associated with them. A common example is an elevation map. Rasters do not have any underlying data.
Raster Images
Raster images make excellent backgrounds for maps. For example, aerial photographs that show real-world detail such as buildings, refineries, and vegetation are well-suited as base layers for a map. Scanned paper maps are another example of a raster image. Use a raster image as a base layer and overlay vector data such as street networks, point locations representing customers, and postal boundaries, to create useful and visually appealing maps.
Raster images used with vector data must be registered so that known geographic points on the image coincide with the same features on the vector data. Additionally, company logos and other art you wish to display in MapXtreme 2004 must be registered to some location on earth, even though they are not true geo-referenced data. Many raster images available today come with a registration file. Examples include GeoTIFF, ADRG, ASRP, CADRG, and CIB. To register a raster image, you can bring it into MapInfo Professional and register it there. The registration information is stored in a .TAB file.
Below are the raster image formats supported in MapXtreme 2004:
•
TIFF and GeoTIFF (*.tif)
•
MrSID (*.sid)
•
ECW (*.ecw)
•
Spot (*.bil)
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
198
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 17: Working with Rasters and Grids
•
JPEG (*.jpg)
•
JPEG2000 (*.jp2, *.j2K)
•
PCX (*.pcx)
•
GIF (*.gif)
•
Windows Bitmap (*.bmp)
•
PNG (*.png)
•
Photoshop (*.psd)
•
Targa (*.tga)
•
Windows Metafile (*.wmf)
•
Vertical Mapper Continuous Grid (*.grd)
•
Vertical Mapper Classified Grid (*.grc)
•
ADRG - ARC Digitized Raster Graphics (*.gen)
•
ASRP - ARC Standard Raster Product (various file extensions)
•
CADRG - Compressed ARC Digitized Raster Graphics (*.gen)
•
CIB - Controlled Image Base (various file extensions)
•
NITF - National Imagery Transmission Format (*.ntf)
Additional raster formats may be supported on a system if a custom raster handler is installed.
Raster Handlers
MapXtreme 2004 can use one of many different libraries to load a raster image. When a raster image is loaded by MapXtreme 2004, it searches through these DLLs and checks if the given file can be read by that DLL. Once a DLL/Raster format match is made, MapXtreme 2004 knows which DLL does the format handling for the file. The Format handlers are named
“xxxxxxxx.RHx”. The base part of the name is based on the format. The extension always begins with RH, but can end in any letter (A-Z). When searching for a format handler,
MapXtreme 2004 searches the format alphabetically, starting with RHA and continuing until
RHZ. This process allows MapXtreme 2004 to prioritize which handlers are used. For example,
SPOT files should be checked for before any other formats since they are just raw data that can be confused with other formats. The SPOT handler's extension is RHD. The Halo format handlers are named RHV. The LEADTOOLS format handlers are named RHX.
LEADTOOLS Win32 Pro provided by LEAD Technologies, Inc. and HALO Imaging libraries provided by Media Cybernetics are included with MapXtreme 2004. LEADTOOLS loads the entire raster image into memory at the time the image is referenced in MapXtreme 2004. This means that the image takes longer to load, but panning and zooming is faster. HALO only loads into memory what it needs to display, so it loads the image faster, but panning and zooming is slower. By default, HALO is attempted first. There may also be some formats which are not supported by either library and therefore need their own separate library. The raster handlers include within MapXtreme 2004 are bundled inside the MapInfo.CoreEngine.dll and so are not accessible or modifiable by the developer. Therefore, the order of the checking of the handlers is not able to be altered. For example, if checking a JPEG, which both Halo and LEADTOOLS can handle, Halo always prevails because of its *.rhv (over LEADTOOLS *.rhx) extension.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
199
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 17: Working with Rasters and Grids
There are a few raster formats that we do not support in multi-threaded applications (e.g., in an
ASP.NET application). These formats are as follows:
Reading
Vertical Mapper GRD, GRC
Export
JPEG 2000 (Win2k only) from LeadTools
JPEG from Halo (Note: the LeadTools JPEG handler is threadsafe)
TIFF CMYK from LeadTools
TIFF w/jpeg compression from Halo
Note:
The LeadTools TIFF handler is threadsafe
Raster Classes
The main classes for raster images are MapInfo.Raster.RasterInfo and RasterRead. Style information is handled by MapInfo.Style.RasterStyle.
RasterInfo provides information about the height and width of the image in pixels, raster format, color depth, and registration information.
RasterRead is the class that reads the raster image and style information in order for the image to be rendered.
RasterStyle is concerned with how the raster looks. You can control brightness and contrast, display a color image as grayscale, set the transparency and translucency. MapXtreme 2004 supports transparency for one color per image. That means that everywhere that color exists in the image it will be invisible, which allows the layer below the image to show through.
Translucency is the degree of transparency for the entire image. If you need a layer below a raster image to show through, set a high translucency (100 percent is transparent).
Raster Images and Coordinate Systems
When you display a raster, grid or WMS image as a map layer, MapXtreme 2004 automatically sets the rotation and projection of all the vector map layers, so that they match the rotation and projection of the raster image.
If a map includes more than one raster, grid or WMS image layer, MapXtreme 2004 automatically displays the map in the projection specified by the most visible raster image. The coordinate system could then change as the map view changes (due to zooming or panning) if a different image with a different projection becomes the most visible. In this case, you cannot change the map's display coordinate system.
Raster Image Limitations
•
You cannot select any features a raster layer.
•
You cannot search for features a raster layer.
Code Sample: Adding a Raster Image to a Map
Adding a raster image to a map is the same as adding any other layer.
Table MyTable = Session.Current.Catalog.OpenTable("MyRaster.tab");
FeatureLayer MyLayer = new FeatureLayer(MyTable);
MyMap.Layers.Add(MyLayer);
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
200
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 17: Working with Rasters and Grids
Code Sample: Retrieving Information from a Raster Image
This sample gets RasterInfo from a given table.
// Each raster table has exactly one associated raster image, and thus
// only one record.
// Reading that record with a data reader, we can get
// a FeatureGeometry - a bounding rectangle,
// a Style - the Raster style,
// a key - a RasterInfo object.
private MapInfo.Raster.RasterInfo GetRasterInfo(Table table) {
MapInfo.Raster.RasterInfo rasterInfo = null;
MIDataReader rdr = null; string projectionlist = "obj, MI_Key, MI_Raster, MI_Style"; rdr = table.ExecuteReader(projectionlist); string name; string typename; int n = rdr.FieldCount;
MapInfo.Styles.Style style;
MapInfo.Geometry.FeatureGeometry featureGeometry;
MapInfo.Data.Key key; if(rdr.Read()) { for(int i =0; i < rdr.FieldCount; i++) { name = rdr.GetName(i); typename = rdr.GetDataTypeName(i); if(typename == "MapInfo.Styles.Style") { style = rdr.GetStyle(i);
} else if(typename == "MapInfo.Geometry.FeatureGeometry") { featureGeometry = rdr.GetFeatureGeometry(i);
} else if(typename == "MapInfo.Data.Key") { key = rdr.GetKey(i);
} else if (typename == "MapInfo.Raster.RasterInfo") { rasterInfo = rdr.GetRasterInfo(i);
}
}
} rdr.Close(); rdr.Dispose(); rdr = null; return rasterInfo;
} private MapInfo.Styles.RasterStyle GetRasterStyle(Table table) {
MapInfo.Styles.RasterStyle rasterStyle = null;
MIDataReader rdr = null; string projectionlist = "MI_Style"; rdr = table.ExecuteReader(projectionlist); string name; string typename; int n = rdr.FieldCount;
MapInfo.Styles.Style style = null; if(rdr.Read()) { for(int i =0; i < rdr.FieldCount; i++) { name = rdr.GetName(i); typename = rdr.GetDataTypeName(i); if(typename == "MapInfo.Styles.Style") { style = rdr.GetStyle(i);
}
}
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
201
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 17: Working with Rasters and Grids
} rdr.Close(); rdr.Dispose(); rdr = null; if (style != null) { rasterStyle = style as RasterStyle;
} return rasterStyle;
} private void DoShowRasterInfo(MapInfo.Data.Table table) {
// Get Raster info from the table.
MapInfo.Raster.RasterInfo rasterInfo = GetRasterInfo(table);
MessageBox.Show(this, String.Format("imageHeight = {0}\n imageWidth = {1}\n", rasterInfo.Height, rasterInfo.Width));
} private void DoShowRasterStyle(MapInfo.Data.Table table) {
// Get Raster info from the table.
MapInfo.Styles.RasterStyle rasterStyle = GetRasterStyle(table);
MessageBox.Show(this, String.Format("Brightness = {0}\n
Contrast = {1}\n", rasterStyle.Brightness, rasterStyle.Contrast));
} private void button2_Click(object sender, System.EventArgs e) {
DoShowRasterStyle(_rasterTable);
}
}
}
Grid Images
As stated previously, grid images show an interpolation of data values across an area. A grid image is created from a data file in which data is measured at evenly-spaced points. The entire map area is converted to a grid in which each grid cell represents a value. Grid values don't have to be interpolated to produce a grid, although the data collection points need to be regularly spaced. MapInfo Professional creates grids by interpolating values using a grid handler.
In addition to the color gradations, grid images can also show hill, or relief, shading. Relief shading allows the grid surface to be shaded according to a virtual light source. The brightness of each grid cell corresponds to the light striking the surface and is adjusted based on its orientation to the light source. This is well suited for elevation grid maps where you can take surface slope and direction into account relative to the direction of the light. Maximum brightness is assigned at points where the sun’s rays are perpendicular to the surface. As the slope faces turn away from the light source, the brightness values are lower.
Supported grid formats include:
•
MapInfo Grid (*.mig)
•
USGS DEM (*.dem)
•
GTOPO30 (*.dem)
•
DTED (*.dt0, *.dt1, *.dt2)
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
202
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 17: Working with Rasters and Grids
•
Vertical Mapper Continuous Grids
1 2
(*.grd)
Additional grid formats may be supported on a system if a custom grid handler is installed.
Grid Classes
The main classes for grid images are MapInfo.Raster.GridInfo, GridRead, ContinuousGridWrite and HillShadeWrite. GridInfo and GridRead are like RasterInfo and RasterRead, in this case, provide the ability to get information about a grid file. Grids are created for a layer of data points using ContinousGridWrite. HillShadeWrite allows you to add or alter relief shading to the grid.
Many of the properties of a grid are inherited from RasterInfo, including the image class, coordinate system, raster control points and minimum bounding rectangle (MBR).
Code Sample: Adding a Grid Image to a Map
Adding a grid image to a map is the same as adding any other layer.
Table MyTable = Session.Current.Catalog.OpenTable("MyGrid.tab");
FeatureLayer MyLayer = new FeatureLayer(MyTable);
MyMap.Layers.Add(MyLayer);
Code Sample: Retrieving Data from a Grid Map
This code snippet shows how to read each grid cell value from a grid file.
public void ReadAllGridCells()
{
// create a GridRead class for a give grid file
GridRead gridread = new GridRead(strGridFilename,
GridRead.DefaultHillshadeFilename(strGridFilename));
// get the GridInfo for the grid file
GridInfo gridinfo = gridread.GridInfo;
// need to do this before getting any grid cell values gridread.StartRead(); bool bIsNull; // whether the cell is a null cell double dValue; // if not a null cell, this is the cell value
// for each row in the grid file for (int y = 0; y<gridinfo.Height; y++)
{
// for each grid cell in a row for (int x = 0; x<gridinfo.Width; x++)
{
// get the grid cell value gridread.GetValue(x, y, out bIsNull, out dValue);
}
}
// need to shut down when done reading cell values gridread.EndRead();
}
1. Can be displayed as either grid or raster. The .TAB file determines whether the image should be drawn using the grid handler or the raster handler.
2. Not multi-thread safe.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
203
MapXtreme2004_DevGuide_A4.pdf
Using the Workspace
Manager
18
The Workspace Manager utility that comes with MapXtreme 2004 enables you to create and manage the new XML-based workspace files (.MWS format) much in the same way that the Geoset Manager in the MapX product allowed you to create and manage geoset files. The Workspace Manager’s convenient user interface allows you to easily assemble the tables that make up your map, apply many additional settings, and save the map as a workspace. Your completed workspace is then ready for use in your own applications, or for use in print or file output.
In this chapter:
!
!
!
!
Developer Guide
Features of the Workspace Manager
Chapter 18: Using the Workspace Manager
The Workspace Manager allows you to control most, but not all, of the settings that can be stored in a workspace file. For example, a workspace can contain information about cartographic legends and adornments; however, the Workspace Manager does not provide any options for creating cartographic legends or adornments. To create cartographic legends or adornments, use the API.
Through the Workspace Manager, you can:
•
Load XML workspaces, tables, geosets, and MapInfo workspaces (.mws not .wor files).
•
Save workspaces as .MWS.
•
Control which tables are opened as part of a workspace.
•
Create and load named connections using the Named Connection Manager.
•
Add/Remove maps and view one or more maps.
•
Set properties for map and layer visibility, layer and label styles, and themes with the built in layer control.
•
Add, remove, or alter custom labels.
•
Create group layers, which allow you to organize your layers into logical groupings, so that you can show or hide the entire group with a single click.
•
View multiple next and previous map views.
•
Use map tools for navigation and manual label placement, and use selection tools to verify that layer selectability settings are correct.
•
Preview and print maps.
•
Quickly open recent workspaces from the recent file list.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
205
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Workspace Format and Contents
Chapter 18: Using the Workspace Manager
The workspace file is an XML document (.MWS extension) that contains the locations of the descriptions and metadata of all the maps, tables, layers, and settings that make up the workspace. Because it is XML, the workspace is portable, which means that you can share the workspace with other users working on different computers, on different networks, across locales.
In MapXtreme 2004, the portability of the XML workspace is implemented with named connections. Named connections enable you to define alternative drive, path, and database connection information based on your own environment, so that you can use workspaces created by others. All paths and connection strings are resolved when the workspace is opened. You can set up named connections directly in the Workspace Manager (File > Manage
Named Connections). For more information on the XML workspace structure, please see
Appendix C: Understanding the New MapInfo Workspace
.
Workspace Manager Menu Commands
This section explains each menu command available in the Workspace Manager.
File Menu Commands
The commands in the File menu provide all the standard File menu capabilities, such as opening, saving and printing files, as well as some features unique to the Workspace manager.
Each command is described below.
New
Creates a new empty map to which you can then add tables using either the Add tool in layer control or the Open Tables command from the File menu. If changes have been made to the current workspace, you will be asked if you want to save the changes before the new workspace is created.
Open Workspace
Opens an existing workspace. If changes have been made to the current workspace, you will be asked if you want to save the changes before the existing workspace is opened.
Open Tables
The Open Tables command enables you to open one or more tables and add them to your map.
Save
Saves your map as a workspace.
Save As
Save a copy of the workspace to a new filename.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
206
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 18: Using the Workspace Manager
Close All Tables
The Close All Tables command closes all of the open tables.
Manage Tables
The Manage Tables command displays a dialog that lists the tables that make up the map and enables you to open additional tables for possible inclusion in the map. Click Open to display the Open dialog and open a table. The table you opened is added to the list of open tables in the Manage Tables dialog. Then you can add the table to the map using the Add tool, which is located over the Workspace Manager layer control window.
To close a table, click a table from the list to highlight it. The Close button is activated. Click
Close to close the table. Layers referencing the table you closed are removed from the map.
Manage Named Connections
A named connection describes a connection to a data source using an alias. You can create the following types of named connections: FilePath, DatabaseSource, ODBC, or Oracle OCI.
After you specify the connect string or file path, you can save it as XML for later retrieval. You can set a default connection so that when you run Workspace Manager, the connection to your data source is available. Named connections are also saved to the workspace.
Page Setup
The Page Setup command enables you to specify the paper size, orientation, and margins of the printed map. You can also use this option to access printer-specific settings.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
207
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 18: Using the Workspace Manager
The Print command enables you to print your map to paper or file output. In the Print dialog, specify the printer to use, the page range you want to print if your job is multiple pages, and the number of copies to print. Printer properties enable you to set layout and other options that are specific to the printer you are using. The Print to file check box enables you to print your output to a file.
Print Preview
Use the Print Preview command to see how your output is going to look before you print it.
Recent Workspaces
Recent Workspaces shows a list of recently opened workspaces.
Map Menu Commands
Use the commands in the Map menu to add and remove maps, manipulate the view of the map, and create thematic maps. The view commands are also available in a popup menu.
Right-click in the Workspace Manager map window to display the menu.
Add New Map
The Add New Map command enables you to create a new map window using the tables that are currently open.
Select Map
The Select Map command enables you to select which map to view in the Workspace
Manager.
Remove Current Map
Removes the current map from the Workspace Manager view and deletes it from the workspace.
Change View
The Change View command enables you to change the current view of the map—that is, what area of the map is currently displayed in the window. You can change the zoom and scale of the map to your own settings. You can also set the center of the map window, or change the rotation angle.
Note:
The Change View dialog allows you to choose the units (miles, kilometers, etc.) for the zoom width and for the center X/Y coordinates (meters, degrees, etc.). Whatever units you choose in the Change View dialog box are also used in the layer control. For example, if you want all distances in the layer control to be displayed in kilometers instead of miles, display the Change View dialog box and choose kilometers from the units list that appears next to the Zoom field.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
208
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 18: Using the Workspace Manager
View Entire Layer
Use the View Entire Layer command to see an entire layer, or all the layers in the map. The
View Entire Layer dialog shows a list of the layers that make up the map. Select the desired layer from the list, or choose All Layers so that all the layers are completely in view, and click
OK. The map redraws to display the entire layer.
Previous View
Use the Previous View command to return to the previous view of your map.
Next View
The Next View command is available after you have used Previous View. Use it to redisplay the view of the map that was on the screen before you used the Previous View command.
The Previous View and Next View commands can be used together to toggle back and forth between two views of your map. These commands are also available as tools on the toolbar.
Preserve Scale/Zoom
Use the Preserve Scale and Preserve Zoom commands to keep the zoom and/or the scale the same as you change the size and shape of the map.
Redraw
Use the Redraw command to redraw the map.
View Selection
Use the View Selection command to zoom in or out on a selected object or objects.
Create Thematic
You can create feature themes and label themes via the Map > Create Thematic menu.
Feature themes include ranged, individual value, dot density, graduated symbol, and pie and bar charts. Label themes include ranged and individual value.
If your map includes at least one set of labels (which are displayed in a label layer, you can create a label theme. A label theme assigns different label styles (different colors, etc.) to each label, based on the data in your table. For example, use a label theme to show the prominence of locations over others. A ranged label theme groups labels based on a similar data value, such as population. Cities that fall within a certain population range are labeled using one style, while cities in other ranges are labeled in another style, typically a less prominent style to indicate city size without having to label using the population value.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
209
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 18: Using the Workspace Manager
The Create Thematic command opens the Create Theme wizard where you can easily create a theme step by step.
To create a theme:
1.
Choose Map>Create Thematic.
The Create Theme: Step 1 of 3 dialog displays.
2.
Select either a Feature theme or a label theme, and choose the type of theme you want to create.
3.
Click Next.
The Create Theme: Step 2 of 3 dialog displays.
4.
Select the table you want to shade.
5.
Choose the data you want to use. Select either a column from the table that contains the data, or select Expression to use an expression to derive the data you want from the table.
6.
Click Next.
The Create Theme: Step 3 of 3 dialog displays. Here you can customize theme type settings, styles, and the legend.
7.
Click Apply to apply the customized settings.
8.
Click OK when you are finished.
Tools Menu Commands
The Workspace Manager’s Tools menu provides access to the map tools via menu commands.
These tools enable you to zoom in and out on the map, change the position of the map, and select map objects in various ways. These same tools are also available on the Workspace
Manager toolbar. Each tool is explained below.
Zoom In
Use the Zoom In tool to get a closer area view of your map. To zoom in on a map:
1.
Choose Tools>Zoom In to activate the tool.
Your cursor changes to a magnifying glass with a plus sign in it.
2.
Click on your map.
The map redraws at a closer area view, centering itself at the point you clicked.
Zoom Out
Use the Zoom Out tool to get a wider area view of your map. To zoom out on a map:
1.
Choose Tools>Zoom Out to activate the tool.
Your cursor changes to a magnifying glass with a minus sign in it.
2.
Click on your map.
The map redraws at a wider area view, centering itself at the point you clicked.
Pan
Use the Pan tool to reposition your map without changing the zoom level. For example, you might want to redirect the view of your map so that a certain country or city is in the center. To pan your map:
1.
Choose Tools>Pan to activate the tool.
Your cursor changes to a hand icon.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
210
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 18: Using the Workspace Manager
2.
Click on the map, and while holding down the mouse button, drag the map to the desired position.
The map redraws reflecting the new position.
Select
Use the Select tool to select objects one at a time or to select all objects that are generally in the same area.
To select an object using the Select tool:
1.
Choose Tools>Select to activate the tool.
The cursor changes to an arrow.
2.
Click the object on the map you want to select.
The selected object is highlighted.
Radius Select
Use the Radius Select tool to select all objects that fall within a given radius. For example, you have a table of blood donors and a table of blood donation sites. Using the Radius Select tool, you could create a temporary list of blood donors that live within a one-half-mile radius of each blood donation site.
Note that the Radius Select tool selects all objects whose centroid falls within the circle. The object does not have to be completely bounded by the circle.To select objects within a radius:
1.
Choose Tools>Radius Select to activate the tool.
The cursor becomes a hand when moved over the map.
2.
Click a place on the map that you would like to use as the center point of your radius search. For example, if you want to select all the fire hydrants that fall within two miles of a fire station, click the fire station and use that as the center point.
3.
Hold down the mouse button and drag the mouse away from the center point.
The Workspace Manager draws a circle around the point and reports the radius of the circle in the StatusBar (lower left corner of the screen).
4.
When you have the desired radius release the mouse button.
Workspace Manager highlights all map objects that fall within that circle.
Rectangle Select
Use the Rectangle Select tool to select objects within a rectangle. By clicking and dragging using the Rectangle Select tool, you create a dotted rectangle, or marquee box around objects you want to select.
Note that the Rectangle Select tool selects all objects whose centroid falls within the rectangle.
The object does not have to be completely bounded by the rectangle.To select objects within a rectangle:
1.
Choose Tools>Rectangle Select to activate the tool. The cursor becomes a hand when moved over the map.
2.
Click a place on the map outside of the area you want to include in the marquee box.
3.
Hold down the mouse button and drag the mouse to form a dotted rectangle around the points you want to select.
4.
When you have reached the desired rectangle size release the mouse button.
Workspace Manager highlights all map objects that fall within that rectangle.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
211
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 18: Using the Workspace Manager
Polygon Select
The Polygon Select tool selects map objects within a polygon that you draw on a map.
To select objects with the Polygon Select tool:
1.
Choose Tools>Polygon Select to activate the tool.
The cursor becomes a pointing hand when moved over the map.
2.
Click the map location at which you want to place the first end point of the polygon.
Move the cursor over your map in any direction.
Workspace Manager draws a line from the point where you clicked to the cursor.
3.
Click to create another endpoint. Continue to move the cursor and click until you have the desired number of sides to your polygon.
4.
To close the polygon, make your last click as close as possible to the first click.
Workspace Manager closes the polygon and selects the objects that are within it.
Layer Control
The Workspace Manager application window is divided into two main sections. The layer control window and commands are located on the left, and the map window is on the right. The layer control window displays the opened map(s) and all of its accompanying layers.
The layer control features of the Workspace Manager enable you to assemble the layers of your map and apply settings to individual layers or the entire map that govern how the layer(s) or map display.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
212
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 18: Using the Workspace Manager
Layer Control Tools
The tools across the top of the layer control window allow you to add, move, and remove layers from the layer control window easily:
•
The Add tools allows you to open tables, and insert group layers and label layers into your map.
•
The Remove Selected Item tool removes the selected layer from the map.
•
The Up and Down toolbar buttons enable you to move layers up and down the layer list, changing the order in which they display.
Layer Tree
The layer control displays a tree showing the map and all layers in the map, as well as other map elements such as themes. The layer tree allows you to perform these operations:
Changing the Layer Order
To change the order of the layers, you can select a layer and click the Up or Down toolbar button. Alternately, you can drag a layer up or down to change its position in the list.
There are two special cases that involve drag-and-drop actions:
To move a layer into a group layer, drag the layer onto the group.
To add a new label source to a label layer, drag a layer onto the label layer.
If you do not want to move a layer into a group—if, instead, you want to reposition the layer so that it is located above the group layer—hold down the SHIFT key before completing the dragand-drop action. Similarly, if you do not want to add a new label source to a label layer, hold down the SHIFT key.
Displaying Context Menus
Each item in the layer tree has a context menu. To display a layer’s context menu, right-click on the layer, or press SHIFT-F10 to display the menu for the currently-selected layer.
The items on the context menu depend on the type of layer specified. In particular, note the following:
To add a style override to a layer, display the context menu and choose Add Style Override.
Note that each layer can have multiple style overrides, each with a different zoom range; this allows you set up the map so that points appear to grow larger, and roads appear to grow wider, as you zoom in.
To rename any item in the layer tree, right-click the item and choose Rename. Alternately, you can pressF2 to rename the selected item. Note that renaming a layer in this manner does not rename the original table; the rename operation simply changes the text that is displayed in the layer tree.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
213
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 18: Using the Workspace Manager
Layer Control Tabs
The layer control tabs provide additional settings and controls that you can apply to the map and to each layer in the map. The tabs change depending on whether a layer or the map is highlighted in the layer control window. Sets of dialog tabs control the map, label layers, layers, and themes. The options in each of the tabs are explained below.
Map Settings
When you select a map in the layer control window, the following tabs are available: View,
Tools, Editing, Extents, and Coordinate System.
View
The View tab enables you to control the overall appearance of the map. You can set the zoom level, scale, a center point (in degrees), and a rotation angle. Click the Apply button to apply your settings.
Tools
The Tools tab enables you to control the display of InfoTips, activate Snap to Nodes and set a snap tolerance, and activate Dynamic Selection tools.
The Dynamic Selection Tools check box controls whether features are selected immediately
(while you are using the selection tool) or selected when you release the mouse button to finish using the selection tool:
If the Dynamic Selection Tools check box is not selected, selection tools do not actually select any features on the map until you finish using the tool. For example, the Radius Select tool will not select any features until you specify a radius and release the mouse button.
If the Dynamic Selection Tools check box is selected, features become selected or de-selected dynamically as you drag the mouse. For example, if you use the Radius Select tool, you will see more features become selected as you drag the mouse to enlarge the radius.
If the Snap To Nodes check box is selected, map tools such as the Select tool will automatically search for nodes that are nearby. If a node is nearby, a crosshair will appear to indicate the position of the nearest node. For example, you might want to select the Snap To Node check box if you are using the Radius Search tool, and you want to make sure that the search is centered at the exact location of a point feature on your map. The Snap To Node feature is particularly important in applications that provide drawing tools, because users often need to draw features at the exact location of existing features.
The Snap Tolerance setting specifies how far the tools will search for “snappable” nodes. You can choose which layers use the Snap to Node feature. For example, you might want to turn on
Snap To Node, but only have the snap crosshair appear when the cursor is near a feature in a particular layer. To turn the Snap To Node feature on or off for a specific layer, select the layer in the layer tree, then select or clear the Snap To Node check box in the Options tab.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
214
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 18: Using the Workspace Manager
Editing
The options in the Editing tab enable you to control certain map editing tasks such as the styles used for drawing objects, if your application uses drawing tools, resizing objects, and moving and deleting object nodes.
The style boxes enable you to specify the default styles of any drawing tools that your application uses. Click on a box to open the corresponding style dialog. The settings you select are saved in the workspace. When a user opens the workspace in an application that uses drawing tools, the application uses these style settings when the user draws objects on the map.
You can also specify whether you want to delete or move duplicate an object’s nodes,
Finally, you can specify an Edit mode for the map:
•
None–No editing can be done on the map.
•
Allow moving and resizing–Objects can be moved and resized.
•
Allow node editing–Nodes can be moved or deleted.
•
Allow node adding–You can add nodes to objects.
The Edit mode you select applies to all editable layers in the map.
Extents
In the map, the Extents tab shows the extents of the current map view. Click the View Entire
Map button to see all of the map.
Coordinate System
The Coordinate System tab indicates the coordinate system of the map, and enables you to change the coordinate system.
To do this:
1.
Click the Coordinate System button to display the Choose Coordinate System dialog.
2.
Select a coordinate system from the list, and click OK.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
215
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 18: Using the Workspace Manager
Layer Settings
When you highlight one of the layers that make up the map, four tabs display: Visibility,
Options, Extents, and Information.
Visibility
Select the Display Within Range check box to specify either a zoom range or scale range in which the layer displays. If you select a zoom range, specify the minimum and maximum zoom in miles. The layer displays within this range. If you select a scale range, specify the closest and farthest scale. The layer displays within this scale range.
Options
The Options tab check boxes facilitate editing and customizing your map layer:
•
Selectable–When the Selectable check box is selected, objects in the layer can be selected using either the Tool menu commands or the Selecting tools in the toolbar.
Clear the Selectable check box for any layer you do not want to select from.
•
Editable–Select the check box to make the layer editable.
•
Drawing Tools can add features to this layer–Select this check box if you are preparing this workspace for use in an application that provides drawing tools, and you want the drawing tools to create new features in this layer.
•
Show InfoTips–Select the Show InfoTips check box to display InfoTips on map objects in the selected layer. The InfoTip text consists of the result of the expression in the
InfoTip Expression field. For example, if the expression is a column in your table, the
InfoTips comprise the values from that column. If the expression is a calculation that uses column information in your table, the InfoTips comprise the results of that calculation.
•
Snap to Nodes–Select to turn the Snap To Node feature on or off for a specific layer, select the layer in the layer tree, then select or clear the Snap To Node check box.
Extents
For a layer, the Extents tab shows the extents of the selected layer. Click the View Entire Layer button to see all of the layer, or click View Default Area to see the default view of the layer.
Information
The Information tab provides information about the selected layer. It gives the name of the table and its path, the type of table, e.g., MapInfo table, and its coordinate system.
Theme Settings
Visibility
When a theme layer is selected, the Visibility tab options control the display of the selected theme. Select the Visible check box to display the theme layer; clear the check box to turn off the theme display.
Select the Display Within Range check box to specify either a zoom range or scale range in which the theme displays. If you select a zoom range, specify the minimum and maximum zoom distance. Your theme displays within this range. If you select a scale range, specify the closest and farthest scale. Your theme displays within this scale range.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
216
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 18: Using the Workspace Manager
Theme
The Theme tab indicates the type of thematic map and the expression used to obtain the values. The Theme tab also enables you to modify your thematic map. Click Modify Theme to change the styles or legend.
Label Settings
When you select a label layer in the layer control window, the Visibility tab is available. When you expand the label layer to see the label sources, additional tabs display that control the appearance and content of labels in label sources: Autolabel, Style, Expression, Position, and
Rules.
Visibility
When a label layer is selected, the options in the Visibility tab control the display of labels.
Select the Visible check box to display labels; clear the check box to turn off label display.
Select the Display Within Range check box to specify either a zoom range or scale range in which the labels display. If you select a zoom range, specify the minimum and maximum zoom distance. Your labels display within this range. If you select a scale range, specify the closest and farthest scale. Your labels display within this scale range.
AutoLabel
The AutoLabel tab enables you to create and manage the display of autolabels. Select the
Create labels automatically check box to generate autolabels for your map. Select the Display within Range check box to specify either a zoom range or scale range in which the autolabels display. If you select a zoom range, specify the minimum and maximum zoom distance. If you select a scale range, specify the closest and farthest scale. Your autolabels display within this scale range.
Style
The Styles tab controls the style of label text and label lines. For label text, use the Text style box to access the Text Style dialog. You can specify the font, color, background, and other text effects for the labels. For label lines, use the Line style box to access the Line Style dialog, where you set the style of the label lines. In the Label Lines group, choose whether you want no label lines, simple lines, or lines with an arrow.
Text
The Text tab enables you to specify an expression that produces the label text from a column or derived information in the table.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
217
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 18: Using the Workspace Manager
Position
Use the settings in the Position tab to set the orientation, offset, and rotation of the labels.
The label’s orientation is the label’s position relative to its anchor point. Click one of the buttons to select an orientation.
Label offset is how far away a label is from its anchor point in pixels.
The label rotation is the angle at which the label is drawn. There are three Rotation settings:
•
Parallel to one segment–Select this option if you are labeling line features such as highways, and you want each label to be drawn at an angle that will make the label run parallel to the nearest segment of the highway.
•
Parallel to multiple segments–Select this option if you are labeling line features such as highways, and you want the label text to follow the shape of the highways.
•
Specific angle–Specify an angle in degrees, such as zero degrees to make all labels horizontal.
Rules
The Rules tab enables you to set certain conditions for displaying labels on your map:
1.
Allow Duplicate Text–Select the Allow Duplicate Text check box to allow duplicate labels for different objects to display, e.g., Portland, OR and Portland, ME. This option is also used with street maps to label street segments individually.
2.
Allow Overlapping Text–Select the Allow Overlapping Text check box to allow labels to be drawn on top of each other. Some labels do not display because they overlap labels that have been given higher priority on the map.
3.
Label Partial Objects–Select the Label Partial Objects check box to label polylines and objects whose centroids are not visible in the Map window.
Per-Label Priority Expression
This expression field is optional. If you leave this expression field blank, features within a single label source are labeled in an unpredictable manner. For example, you might find that some small cities are labeled, while some major cities are not labeled because there is not enough room. If you specify an expression (which must be numeric), then the expression will be calculated for each feature on the visible portion of the map, and features that have a larger value will be given a higher labeling priority. To specify an expression, click the Set button.
For example, suppose you are configuring the labels for the WorldCapitals layer, which contains point features that represent cities. You probably want the cities with the largest population to have the highest labeling priority. In this case, you would specify a labeling expression such as: cap_pop
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
218
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 18: Using the Workspace Manager
The cap_pop column represents the population of each Capital city. When you specify a Per-
Label Priority Expression of cap_pop, you are specifying that the cities with the largest population should have the highest labeling priority. As a result, the most populous cities will be labeled first, while other cities will be labeled only if there is enough room left over.
Per-Table Priority Expression
This expression field is optional. A label layer can contain multiple label sources; for example, you might have one label source representing a set of labels for World Countries, and another label source representing a set of labels for World Capitals (cities). By default, the label source at the top of the list has the highest priority. If you want to assign a higher priority to a label source, you can either move that label source up (in the layer control’s list of label sources), or you can specify a Per-Table Priority Expression for each label source.
For example, if you give the World Countries label source a per-table priority expression of 10, and give the World Capitals label source a per-table priority expression of 5, country labels will have priority over capital city labels.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
219
MapXtreme2004_DevGuide_A4.pdf
Geocoding and Routing
19
This chapter covers the MapXtreme 2004 namespaces for Geocoding and Routing. Each namespace contains interfaces and classes that allow you to use a .NET client to send geocoding or routing requests to a server and get responses back.
In this chapter:
!
!
!
!
!
!
Developer Guide
Overview of the MapInfo.Geocoding Namespace
Chapter 19: Geocoding and Routing
The MapInfo.Geocoding namespace provides interfaces and classes for geocoding address records. Geocoding is the process of determining the geographic location of a street address, intersection, place or postal code in order to pinpoint the location on a map.
Perhaps you are building a find the nearest application in which your users provide their location in order to see where they are in relation to your ATM machines. Since you won’t know where the user is until she supplies the address, you cannot spot her location on the map. To do so, you must geocode her address to get the geographic information (coordinates) related to that address.
You get those coordinates by matching the input address to one that already has the coordinates. In MapXtreme 2004 you use one of two supplied geocoding clients to send the address in the form of an HTTP request to either a MapInfo geocoding server or an miAware
3.0 geocoding service. Note that the server and the miAware service are not included in the purchase of MapXtreme 2004.
You supply one or more addresses in a single request document. Incomplete addresses can be processed as well. The server returns a complete address that you can use to clean up your input addresses.
The server returns zero, one or more responses to a service request, depending on the quality of the data and the request preferences. Responses typically include a list of one or more potential matches, called candidates, and result codes that indicate the positional accuracy of the candidates. Your application will then need to resolve the response by choosing the appropriate address candidate to retrieve the coordinates.
The main interface for using the geocoding clients is called
MapInfo.Geocoding.IGeocodeClient. Classes include GeocodeRequest, GeocodeResponse,
GeocodeClientFactory, GeocodingConstraints, AddressCandidates, GeocodeMatchCode, and
CandidateAddress. The interface of both clients is similar as they both use the same classes for geocode requests, constraints, responses, result codes, and input and candidate addresses. Each is discussed below.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
221
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 19: Geocoding and Routing
IGeocodeClient
This interface defines a geocoding client object. It has a single method, Geocode, that takes a request as input and returns a response containing candidate addresses (addresses that are a potential match for the input address).
GeocodeRequest
This is the object that is sent to the geocoding server or service. Its properties include
AddressList, a list of addresses to be geocoded, and Length, the number of items in the address list. Input addresses can include a variety of information, including street address or intersection, primary and secondary postal code, and country code.
GeocodeResponse
This is the returned object that contains a response for each address in the GeocodeRequest.
The response contains address candidates, which are those addresses considered to be possible matches for the input address. Note that a GeocodeRequest that contains multiple addresses will yield a GeocodeResponse object that includes a list of candidate addresses for each input address.
GeocodeClientFactory
This class returns an IGeocodeClient which you use to send a GeocodeRequest and receive a
GeocodeResponse. The method GetMmjHttpClient uses the geocoding client that speaks to an instance of the MapInfo MapMarker Java servlet. Use the method GetMiAwareGeocodeClient to send requests to the Location Utility Service in MapInfo miAware 3.0.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
222
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 19: Geocoding and Routing
GeocodingConstraints
This class contains the preferences that can be set when geocoding. All are set/get properties that return true or false (default). They include:
Property
CloseMatchesOnly
MustMatchAddressNumber
MustMatchMainAddress
*
*
Description
Indicates whether or not to return only close matches.
Indicates whether or not an exact match on the address number is required.
Indicates whether or not an exact match on the street address is required.
MustMatchCountrySubdivision
*
MustMatchCountrySecondarySubdivision
* Indicates whether or not an exact match on the secondary country subdivision is required (e.g., county)
MustMatchMunicipality
*
Indicates whether or not an exact match on the country subdivision is required.(e.g., state or province).
Indicates whether or not an exact match on the municipality is required (e.g., city, town.
MustMatchMunicipalitySubdivision
MustMatchCountry
*
MustMatchPostalCode
MustMatchInput
*
FallbackToGeographic
*
* Indicates whether or not an exact match on the municipality subdivision is required (e.g., urbanization in Puerto
Rico)
Indicates whether or not an exact match on the country is required.
Indicates whether or not an exact match on the postal code is required.
Indicates whether or not an exact match on the entire input address is required.
Indicates whether or not to geocode to the geographic centroid for the address if a street level geocode cannot be performed.
FallbackToPostal Indicates whether or not to geocode to the postal centroid if a street level geocode cannot be performed.
* When this property is set to true and CloseMatchesOnly is set to false, some non-close candidates could be returned.
AddressCandidates
This class is a list of possible address matches that is returned in a GeocodeResponse.
BaseGeocodeMatchCode and GeocodeMatchCode
These are classes that implement the IGeocodeMatchCode interface. The interface exposes a
ResultCode property that is a string that describes how well the match was made.
BaseGeocodeMatchCode is returned when a request is sent to the miAware 3.0 Location Utility service. GeocodeMatchCode extends BaseGeocodeMatchCode. It is returned when a geocode request is sent to a MapMarker server. GeocodeMatchCode includes additional convenience properties to determine which parts of the address matched. Among them,
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
223
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 19: Geocoding and Routing
StreetAddressMatch and MunicipalityMatch return a value of true if the candidate matched the street and municipality. For details on result codes see
Geocoding Result Codes on page 224
CandidateAddress
This class defines an address that was geocoded. Its properties include Address, the address for the geocoded address, GeocodeMatchCode, which explains how well the address was geocoded, and Point, the geometry that represents the candidate address.
Geocoding Result Codes
Address candidates are assigned a result code that indicates the type of match and how accurate it is to the request address. These are the categories.
•
Single Close Address Match (S Category)
•
Best Match from Multiple Candidates (M Category)
•
Postal Centroid Match (Z Category)
•
Non-match Codes
Single Close Address Matches (S Category)
Matches in the S category indicate that the record was matched to an address candidate. The first character (S) reflects that the geocoding server found a street address that matches the record. The second position in the code reflects the positional accuracy of the resulting point for the geocoded record.
S1 - single close match, point located at postal code centroid.
S4 - point located at the center of a shape point path (shape points define the shape of the street polyline).
S5 - point located at a street address position.
S6 - point located at centroid of geometry ZIP. (e.g., large buildings having their own ZIP
Codes). This represents the highest accuracy available.
SX - point located at street intersection.
SO - no coordinates available (very rare occurrence).
Best Match from Multiple Candidates (M Category)
Matches in the M category indicate that there is more than one close match candidate for the record and the geocoder has chosen the best one of those candidates.
As in the S category, the second position in the code of M category matches indicate the positional accuracy of the resulting point object.
M1 – multiple close matches, point located at ZIP Code centroid
M2 – multiple close matches, point located at ZIP+2 centroid
M3 – multiple close matches, point located at ZIP+4 centroid
M4 – multiple close matches, point located at the center of a shape point path (shape points define the shape of the street polyline)
M5 – multiple close matches, point located at a street address position (highest accuracy available)
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
224
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 19: Geocoding and Routing
M6 – multiple close matches, point located at Point ZIP location
MX – multiple close matches, point located at street intersection
M0 – multiple close matches, no coordinates available
Address Component Accuracy
For either S or M category result codes, eight additional characters describe how closely the address matches an address in the Address Dictionary. The characters appear in the order given. Any non-matched components are represented by a dash.
H - House number (e.g., 115)
P - Street prefix direction (e.g., North)
N - Street name (e.g., Main)
T - Street type (e.g., Place)
S - Street suffix direction (e.g., SE)
C - City name (e.g., New York)
Z - Postal code (e.g., 80302)
A - Address Dictionary (e.g., A)
For example, the result code S5- -N-SCZA represents a single close match that matched the street name, street suffix direction, city and ZIP Code exactly, but could not match the house number, street prefix direction, or the street type. This match candidate would spot at the street address position of the match candidate.
Postal Centroid Matches (Z Category)
Matches in the Z category indicate that no street match was made, either because:
1) there is no close match and you set a constraint to fall back to the postal centroid.
2) the address is a P.O. Box or rural address;
3) you set a constraint to geocode to the postal code.
The resulting point is located at the ZIP Code centroid with five possible accuracy levels.
Z1 – ZIP Code centroid match
Z2 – ZIP+2 centroid match
Z3 – ZIP+4 centroid match (highest accuracy available)
Z6 – ZIP Code centroid match for point ZIP
Z0 – ZIP Code match, no coordinates available (very rare)
Point ZIPs are ZIP Codes are without an area. These include P.O. Box ZIPs and Unique ZIPs
(single site, building, or organization).
Note when using a non-U.S. address dictionary, the results in this category will still be a “Z”.
Non-Match Codes
The following result codes indicate no match was made:
N – No close match. These records can be re-geocoded interactively or during subsequent automatic passes under different matching conditions.
NX – No close match for street intersections.
ND – MapMarker could not find the Address Dictionary for the given ZIP Code or city/state.
These records can also be re-geocoded once the Address Dictionary is available.
NG – The user marks these records during interactive geocoding as non-geocodable.
MapMarker does not attempt to match these records again until the code is removed.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
225
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
A Few Words About Addresses
Chapter 19: Geocoding and Routing
The quality of the address data is of utmost importance in geocoding. A clean input address that follows standard address conventions for the locale, will yield better results than incomplete or poorly formed addresses.
This section is an overview of address quality for both the input addresses as well as the matching reference address. To get the most out of geocoding, it’s important to understand the address structure of your data and the data to which you are matching.
Input Addresses
Input addresses are those addresses you wish to geocode. These are addresses that do not contain geographic coordinates and thus cannot be located on a map.
Input addresses are made up of several components that the geocode server examines to determine a match. Address number, street name and street prefixes and suffixes can be contained in an input address. Prefixes are commonly directional in nature, such as North or
South and exist only for some addresses. Suffixes are typically the type of street, Street, Road,
Avenue Other information you might find in an input address is an apartment or route number.
Input addresses can contain a full or partial address and can contain spelling variations. For example, LaSalle Street as input will match to LaSalle St. However LaSalle without a street suffix may not because the address could really be LaSalle Ave.
The MapXtreme 2004 geocoding client can use so-called “dirty” data and incomplete addresses. This client accommodates both U.S. and non-U.S. addresses, provided the server contains the appropriate reference addresses.
Reference Addresses
Reference addresses are those that the server matches against the input addresses. These records contain the geographic coordinates required to locate the address on a map.
Reference addresses are maintained on the server and are updated regularly through maintenance programs to accommodate new addresses. They have been standardized based on conventions of the locale. For example, in the North America, street numbers precede the street name. In other parts of the world, the street number may follow the street name.
Typically the reference address contains the essential components: address number, street name and prefix, if one exists, and suffix. For non-U.S. locales, additional information such as apartment number, may not be contained in the reference address and thus, ignored in the input address.
Code Sample: Geocoding Client
The following sample code shows how to use the geocoding client in C#. The steps are summarized at the top (set up the address, set up the request, set the geocoding constraints, geocode, and process the result) and demonstrated in appropriate sections below.
private void PerformGeocode()
{
Address[] addrList = new Address[1];
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
226
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 19: Geocoding and Routing
// set up the address addrList[0] = BuildAddress();
// set up the request
GeocodeRequest req = new GeocodeRequest(addrList);
// set the geocoding constraints req.GeocodeConstraints = BuildConstraints();
// geocode
GeocodeResponse res = _geocodeClient.Geocode(req);
//process the result
ProcessResponse(res);
} private Address BuildAddress()
{
Street street = new Street("", "",tbStreet.Text,"","");
Address result = new Address(new StreetAddress(street), tbCountry.Text);
Place[] cityState = new Place[2]; cityState[0] = new Place(tbCity.Text,
NamedPlaceClassification.Municipality); cityState[1] = new Place(tbState.Text,
NamedPlaceClassification.CountrySubdivision); result.PlaceList = cityState; result.PrimaryPostalCode = tbPostalCode.Text; return result;
} private GeocodeConstraints BuildConstraints()
{
GeocodeConstraints result = new GeocodeConstraints(); result.CloseMatchesOnly = cbCloseMatchesOnly.Checked; result.FallbackToPostal = cbFallbackPostal.Checked; result.FallbackToGeographic = cbFallbackGeographic.Checked; result.MustMatchAddressNumber = cbMatchAddrNumber.Checked; result.MustMatchMainAddress = cbMatchMainAddr.Checked; result.MustMatchInput = cbMatchInput.Checked; result.MustMatchMunicipality = cbMatchCity.Checked; result.MustMatchCountrySubdivision = cbMatchState.Checked; result.MustMatchPostalCode = cbMatchPostal.Checked; return result;
} private void ProcessResponse(GeocodeResponse res)
{
StringBuilder buffer = new StringBuilder(); int i = 0;
IEnumerator enumer = res.GetEnumerator(); while (enumer.MoveNext())
{
AddressCandidates responses =
(AddressCandidates)enumer.Current;
System.Collections.IEnumerator respEnumer = responses.GetEnumerator(); while (respEnumer.MoveNext())
{ i +=1; buffer.Append("**** Candidate " + i + " ****\n");
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
227
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 19: Geocoding and Routing
CandidateAddress geoAddr =
(CandidateAddress)respEnumer.Current;
Address addr = geoAddr.Address;
StreetAddress streetAddress = addr.StreetAddress; if (streetAddress != null)
{
Building outBuilding = streetAddress.Building; if (outBuilding != null)
{
AddInfoToResults("Building Name", outBuilding.BuildingName, buffer, "\t\t");
AddInfoToResults("Building Number", outBuilding.Number, buffer, "\t");
}
Street returnedStreet = streetAddress.Street;
AddInfoToResults("Street Type Prefix: ", returnedStreet.TypeSuffix, buffer, "\t");
AddInfoToResults("Street Directional Prefix: ", returnedStreet.DirectionalPrefix, buffer, "\t"); buffer.Append("\n");
AddInfoToResults("Street Official Name", returnedStreet.OfficialName, buffer, "\t"); buffer.Append("\n");
AddInfoToResults("Street Type Suffix: ", returnedStreet.TypeSuffix, buffer,"\t");
AddInfoToResults("Street Directional Suffix: ", returnedStreet.TypeSuffix, buffer, ""); buffer.Append("\n");
}
// placelist can be null when postal code geocoding in
// the US.
if (addr.PlaceList!= null)
{
System.Collections.IEnumerator placeList = addr.PlaceList.GetEnumerator(); while (placeList.MoveNext())
{
Place place = (Place)placeList.Current; buffer.Append(place.Type + ": " + place.Name); buffer.Append("\n");
}
} buffer.Append("PostalCode :" + addr.PrimaryPostalCode); buffer.Append("\n"); buffer.Append("Coordinates: " + geoAddr.Point.X +
", " + geoAddr.Point.Y); buffer.Append("\n"); buffer.Append("ResponseCode/Match Type :" + geoAddr.GeocodeMatchCode.ResultCode); buffer.Append("\n\n");
}
} if (buffer.Length != 0) rtbResults.Text = buffer.ToString(); else rtbResults.Text = "No candidates returned";
}
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
228
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 19: Geocoding and Routing
private void AddInfoToResults(String description, String info,
StringBuilder buffer, String spacer)
{ if ((info != null) && (info.Length != 0))
{ buffer.Append(description + ": " + info); buffer.Append(spacer);
}
}
}
}
Additionally, a sample application that uses the above code ships with MapXtreme 2004.To run it, open it in VisualStudio.NET and provide a URL to the geocoding server (MapMarker or miAware 3.0 service). The sample looks like the following:
Overview of MapInfo.Routing Namespace
The MapInfo.Routing namespace provides an interface and classes for incorporating a
MapXtreme 2004 routing client into your application, in a similar fashion to the geocoding client outlined earlier. The routing client sends requests via HTTP to MapInfo’s routing server or routing web service product. The server and web service are not included in the purchase of
MapXtreme 2004.
Routing is the process of finding a route between two points. The routing server can determine the route and is optimized for returning a route with the shortest distance or shortest travel time. It can return the route geometry (layout of the route for map display), turn-by-turn directions, and a route summary of total distance and time. Additionally it can service requests that include intermediate points along the route and preferences that avoid certain road features, such as highways or certain locations.
The following interfaces and classes make up the Routing namespace: IRouteClient,
RouteRequest, RouteResponse, RouteClientFactory, RoutePlan, RouteGeometryRequest,
RouteInstructionRequest and RouteSummary.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
229
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 19: Geocoding and Routing
IRouteClient
This interface defines a routing client object. It has a single method, Route, that takes a routing plan as input and returns a route.
RouteRequest
This class contains properties that define the route plan (route start and end points), and optionally, whether or not to return the route geometry (for map display) and driving directions.
RouteResponse
This class contains the result of the route computation, including a route summary that provides the total time and distance required to travel the route. If requested, it will also contain driving directions and the route geometry.
RouteClientFactory
This class returns an IRouteClient which you then use to send a RouteRequest and receive a
RouteResponse. This class uses the routing client, either with the method GetRjsHttpClient for direct access to Routing J Server, or GetMiAwareRouteClient for access via the miAware 3.0 route web service.
RoutePlan
This class specifies the requested route. Its members include AvoidList, RoutePreference,
WayPointList. AvoidList allows you to specify either points or features along the route that you wish to skip. RoutePreference controls whether the request is for a route with the shortest
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
230
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 19: Geocoding and Routing
distance or shortest travel time. WayPointList property indicates the start and end points for the route plan, and intermediate points, if any. The number of intermediate points is dependent on the capabilities of the server.
RouteGeometryRequest
This class requests the geometry of the route returned. Its property, ReturnGeometry, is a boolean flag to indicate whether you wish the geometry to be returned. By default, it is not returned. When it is returned, the geometry is a MapInfo.Geometry.LineString object.
RouteInstructionRequest
This class requests that turn-by-turn directions be returned. By default the directions are not returned.
RouteSummary
This class refers to the total time and distance of the route. It is one of the properties returned in a RouteResponse.
Code Sample: Routing Client
This portion of the Routing sample application illustrates how to request a route from a routing server given previously geocoded points that represent the start and end points of the route.
include MapInfo.Routing
Dim wpl As WayPointList = New WayPointList( _
GeocodeResp.Item(0).Item(0).Point.Centroid, _
GeocodeResp.Item(1).Item(0).Point.Centroid)
' first candidate for each address
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
231
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 19: Geocoding and Routing
Dim rp As RoutePlan = New RoutePlan(wpl)
Dim RouteReq As RouteRequest = New RouteRequest( rp, _
DistanceUnit.Mile)
Dim RoutingClient As Object
' may be IRouteClient or miAwareRouteClient
If radioUseJServers.Checked Then
RoutingClient = _
RouteClientFactory.GetRjsHttpClient(strRjUrl)
Else
RoutingClient = _
RouteClientFactory.GetMiAwareRouteClient( _ strRjUrl, "demo", "demo")
End If
Dim rgr As RouteGeometryRequest = New RouteGeometryRequest rgr.ReturnGeometry = True
Dim rir As RouteInstructionsRequest = _
New RouteInstructionsRequest rir.ReturnDirections = True
RouteReq.RouteGeometryRequest = rgr
RouteReq.RouteInstructionsRequest = rir
Call LogProgress( _
"RouteRequest object created.", _
"Getting route from " & strRjUrl & "...")
Application.DoEvents()
Dim RouteResp As RouteResponse
Try
RouteResp = RoutingClient.Route(RouteReq)
Catch ex As Exception
Call LogProgress( _
"Routing call failed with error:", _ ex.ToString())
Exit Function
End Try
SendRouteRequest = RouteResp
End Function
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
232
MapXtreme2004_DevGuide_A4.pdf
WMS and WFS
20
MapXtreme 2004 provides the ability to deploy Web Map Services (WMS) and Web Feature Services
(WFS) on a server and allows you to use either of these services in your mapping applications from a variety of vendors.
In this chapter:
!
!
!
Developer Guide
Web Map Service
Chapter 20: WMS and WFS
The MapXtreme 2004 Web Map Service (WMS) allows clients to request and servers to deliver spatially referenced map images over the Internet or private intranet. MapXtreme 2004 gives you the tools to both deploy a WMS Server for others to query, and supports the incorporation of WMS Client capabilities into your application to request images from a WMS Server. The
WMS Server and Client implementations are based on the 1.1.1 OpenGIS® Web Map Service
Implementation Specification, which can be found at
http://www.opengis.org/docs/01-
068r2.pdf
. The WMS Client has been built based on the WMS 1.0.0, 1.1.0, and 1.1.1 OGC specifications and has been successfully tested on servers claiming to implement these specification versions as well as some supporting minor revisions (for example, 1.0.5).
A basic WMS classifies its geo-referenced information holdings into layers and offers predefined styles in which to display those layers. A WMS that conforms to the OGC specification may support the transparent pixel definition for some image formats as well.
Transparent pixels allow you to use retrieved WMS images as raster overlays and not solely as the background layer for a map. The quantity and quality of data available is determined by the
WMS Server.
To use the WMS Server, you must integrate it into Microsoft Internet Information Service (IIS) and create a configuration file appropriately. See
Setting up a WMS Server on page 234
for more information about this process. You should have a working knowledge of WMS in general, and the MapXtreme 2004 workspace schema in particular to use the WMS Server implementation. The Workspace schema is discussed in detail in
MapInfo Workspace in Appendix C on page 296
You can add a WMS Client programmatically to your application and run it by specifying the
URL of the WMS Server and the layers you want to return. A WMS map request must contain the following elements:
1.
The layers that should be used in rendering the image.
2.
The style that each layer should be rendered with.
3.
The coordinate system that should be used for rendering.
4.
The geographic area or bounds that the map should represent.
5.
The image format to be used. The image may have a specified background color or have a transparent background color. Transparency, when available, is useful for overlaying images in a map. An opaque image may only be useful as the bottom most layer in your map.
See
Using the MapXtreme 2004 WMS Client on page 240
for more information.
Setting up a WMS Server
This section describes how to configure a WMS Server connection to IIS and create the XML file necessary for providing the data connection required to host a Web Map Service. We assume you have a working knowledge of WMS and the MapXtreme 2004 workspace schema in this section. Information on the workspace schema is located in
Understanding the New MapInfo Workspace
. If you are only interesting in running the WMS
Client to access data from other services, see
Using the MapXtreme 2004 WMS Client on page 240
. You do not have to create a WMS Server to use the WMS Client implementation.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
234
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 20: WMS and WFS
The WMS Server runs inside of Microsoft Internet Information Services (IIS). You must configure your host machine to work with the appropriate version of ASP.NET (v 1.1.4322).
Then, to run the service you must first modify the configuration file to include the MapXtreme
2004-specific WMS information. Additionally, you need to create a valid configuration file that contains information about the data you are hosting.
Note:
When you create an XML configuration file, it must validate against the WMS schema file (MXP_WMSConfiguration_1_0.xsd) or you will get errors when you try to run the
WMS Server.
Configuring the WMS Server and IIS Using Visual Studio .NET
Use this method if you are using Visual Studio .NET to configure the WMS Server and IIS:
1.
On the host machine, check the version of ASP.NET. It must be version 1.1.4322.
2.
To register this version of ASP.NET, issue the following commands:
%windir%\Microsoft.NET\Framework\v1.1.4322\aspnet_regiis.exe -i and regsvr32\%windir%\Microsoft.NET\Framework\v1.1.4322
\aspnet_isapi.dll
3.
Create an ASP.NET Web Application in Visual Studio .NET. For this example, assume the project is called WMS.
4.
To run and test this project from Visual Studio, add references in the project to:
•
MapInfo.CoreEngine.dll
•
MapInfo.CoreTypes.dll
•
MapInfo.Wms.Server.dll
•
MapInfo.Wms.Client.dll
5.
Open the Web.config file created for the project and add the following entry before the
<system.web>
opening tag:
<appSettings>
<add key="configFile" value="YOURWMSCONFIG.XML FILENAME"/>
</appSettings>
6.
Change the path to match the location of your configuration XML file, if necessary.
7.
Add the following tags just after the
<system.web>
opening tag:
<httpHandlers>
<add verb="*" path="GetMap.ashx"
type="MapInfo.Wms.WmsHttpHandler, MapInfo.Wms.Server,
Version=1.0.0.75, Culture=neutral,
PublicKeyToken=4ac3224575145b20"/>
</httpHandlers> and
<httpModules>
<add type="MapInfo.Engine.WebSessionActivator,
MapInfo.CoreEngine, Version=1.0.0.75, Culture=neutral,
PublicKeyToken=93e298a0f6b95eb1" name="WebSessionActivator"/>
</httpModules>
8.
Save the Web.config file.
Note:
The Version=1.0.0.75 and the PublicKeyTokens attributes may change, depending upon the build of MapXtreme 2004 you have installed. To ensure that these values are correct, select Start > Run and type in
%windir%\assembly
to open the assembly directory. Then find the MapInfo.WMS.Server assembly and check the version and
Public Key Token attributes to ensure that they match the entries in this code.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
235
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 20: WMS and WFS
Configuring the WMS Server and IIS without Visual Studio .NET
Use this method if you do not need Visual Studio .NET to configure your WMS Server and IIS.
Note:
The Version=1.0.0.75 and the PublicKeyTokens attributes mentioned in the code in this example may change, depending upon the build of MapXtreme 2004 you have installed. To ensure that these values are correct, select Start > Run and type in
%windir%\assembly
to open the assembly directory. Then find the
MapInfo.WMS.Server entry and check the version and Public Key Token attributes to ensure that they match these code entries.
1.
Create a folder on the C drive and name it wms. For example: mkdir c:\wms
.
2.
Create a file called Web.config inside the wms folder. This file should contain at a minimum the steps from above. For example:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="configFile" value="YOURWMSCONFIG FILENAME"/>
<add key="MapInfo.Engine.Session.ExitProcess" value="true"/>
</appSettings>
<system.web>
<Create a filter and associate it with a specific handler.>
<httpHandlers>
<add verb="*" path="GetMap.ashx" type="MapInfo.Wms.WmsHttpHandler,MapInfo.Wms.Server,
Version=1.0.0.75, Culture=neutral,
PublicKeyToken=4ac3224575145b20"/>
</httpHandlers>
<httpModules>
<add type="MapInfo.Engine.WebSessionActivator,
MapInfo.CoreEngine, Version=1.0.0.75, Culture=neutral,
PublicKeyToken=93e298a0f6b95eb1" name="WebSessionActivator" />
</httpModules>
</system.web>
</configuration>
3.
Right-click the wms folder and web share it as wms.
4.
Open IIS Manager, expand the trees and right-click the wms virtual directory.
5.
Open the Properties dialog, click the Directory Security tab and click the Edit button for
Anonymous Access. Select the Anonymous Access check box. Use this step to avoid username/password requirements.
Configuring the Server with the Data
Once your IIS connection is configured, you are ready to configure the server with the data to be shared. To do this, create a WMS configuration XML file following the conventions in the schema (MXP_WMS_Configuration_1_0.xsd). The schema file is available in the \schema directory under your program directory.
A valid sample WMS configuration XML file is in the \WMS Config Files directory on the
MapXtreme 2004 CD. To use this file, open it in an XML editor and change the entries listed below. Many of the path names and connection names are in all CAPITAL letters to make them easy to find. This file is also available on the MapXtreme 2004 Web page on the
http:// www.mapinfo.com
web site in the Developers > Downloads section. When modifying the sample WMSSample.xml file, include these entries:
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
236
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 20: WMS and WFS
1.
Enter the name, title, abstract, keywords, and the URL of your server in the
Service section of this file.
<mxp-wms:Service>
<mxp-wms:Name>Sample WMS Server</mxp-wms:Name>
<mxp-wms:Title>Sample WMS Server</mxp-wms:Title>
<mxp-wms:Abstract>This is a sample WMS server
</mxp-wms:Abstract>
<mxp-wms:KeywordList/>
<!-- The following is the URL of the WMS server -->
<mxp-wms:OnlineResource>http://localhost/WMS/GetMap.ashx
</mxp-wms:OnlineResource>
<mxp-wms:Fees>$10</mxp-wms:Fees>
<mxp-wms:AccessConstraints>none</mxp-wms:AccessConstraints>
</mxp-wms:Service>
2.
List the MIME types to be excluded by the server in the
<mxpwms:WmsRasterFormatExcludeSet>
section. The configuration file allows for a list of
MIME types to be excluded from those supported by default.
<mxp-wms:WmsRasterFormatExcludeSet>
<mxp-wms:Format>image/jpeg2000</mxp-wms:Format>
<mxp-wms:Format>image/photoshop</mxp-wms:Format>
<mxp-wms:Format>image/jp2</mxp-wms:Format>
</mxp-wms:WmsRasterFormatExcludeSet>
3.
Add the connections required by the data (i.e., Oracle database, SQLServer).
<ConnectionSet xmlns="http://www.mapinfo.com/mxp">
<DBConnection dbType="MYSERVER">
<ConnectionName>DBConnection</ConnectionName>
<ODBCConnectionString>Driver=
{INFORMIX 3.81 32 BIT};
UID=MYUID;PWD=MYPASSWD;DATABASE=MYDB;
HOST=MYSERVER;SRVR=MYSERVER;SERV=1800;
PRO=onsoctcp;CLOC=en_US.CP1252;DLOC=en_US.CP1252;
VMB=0;CURB=0;OPT=;SCUR=0;ICUR=0;OAC=1;OPTOFC=0;
RKC=0;ODTYP=0;DDFP=0;DNL=0;RCWC=0</ODBCConnectionString>
</DBConnection>
</ConnectionSet>
4.
Include the data sources to be used by the server (i.e., local MapInfo tables, database tables). Create one entry here for each table you want to share.
<DataSourceDefinitionSet xmlns="http://www.mapinfo.com/mxp/wms">
<!-- The following data sources reference local TAB files -->
<TABFileDataSourceDefinition id="id1" readOnly="false" xmlns="http://www.mapinfo.com/mxp">
<DataSourceName>STATES</DataSourceName>
<FileName>MYPATH\STATES.TAB</FileName>
</TABFileDataSourceDefinition>
<TABFileDataSourceDefinition id="id2" readOnly="false" xmlns="http://www.mapinfo.com/mxp">
<DataSourceName>US_HIWAY</DataSourceName>
<FileName>MYPATH\US_HIWAY.TAB</FileName>
</TABFileDataSourceDefinition>
<TABFileDataSourceDefinition id="id4" readOnly="false" xmlns="http://www.mapinfo.com/mxp">
<DataSourceName>CANHIWAY</DataSourceName>
<FileName>MYPATH\CANHIWAY.TAB</FileName>
</TABFileDataSourceDefinition>
<TABFileDataSourceDefinition id="id5" readOnly="false" xmlns="http://www.mapinfo.com/mxp">
<DataSourceName>OCEAN</DataSourceName>
<FileName>MYPATH\OCEAN.TAB</FileName>
</TABFileDataSourceDefinition>
<!-- This data source references a local named connection-->
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
237
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 20: WMS and WFS
<DBDataSourceDefinition id="id3" readOnly="false" xmlns="http://www.mapinfo.com/mxp">
<DataSourceName>alias_Line_spyro</DataSourceName>
<ConnectionMember>
<ConnectionName>spyro</ConnectionName>
</ConnectionMember>
<DBQuery>
<Query>select * from usa_caps_extra</Query>
</DBQuery>
<DBDataSourceMetadata>
<FeatureGeometryAttribute srsName="mapinfo:coordsys 1,62"> sw_geometry</FeatureGeometryAttribute>
<KeyAttributes/>
</DBDataSourceMetadata>
</DBDataSourceDefinition>
<!-- This data source uses an inline connection to an
Oracle server -->
<DBDataSourceDefinition id="id6" readOnly="false" xmlns="http://www.mapinfo.com/mxp">
<DataSourceName>ASIA</DataSourceName>
<ConnectionMember>
<InlineDBConnection>
<OCIConnectionString>SRVR=ontario;UID=myuid;PWD=mypasswd
</OCIConnectionString>
</InlineDBConnection>
</ConnectionMember>
<DBQuery>
<Query>select * from "ATSJAVA"."ASIA"</Query>
</DBQuery>
<DBDataSourceMetadata>
<FeatureGeometryAttribute srsName="mapinfo:coordsys 1,0">
OBJECT
</FeatureGeometryAttribute>
<KeyAttributes/>
</DBDataSourceMetadata>
</DBDataSourceDefinition>
</DataSourceDefinitionSet>
5.
Indicate the shared layers. Include the name and title of each layer, the coordinate systems, and styles supported. See the
<mxp-wms:WmsLayer queryable="false"> element for details.
When this file is complete, the Web.config file must contain the location of the WMSConfig.xml file so the WMS can retrieve data as requested. A copy of the Web.config file is in the \WMS
Config Files directory on the installation CD. This Web.config file is different than the one needed for WFS.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
238
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 20: WMS and WFS
WMS Server Schemas
The figures below contain the WMS Server configuration schemas for the WMS Server. The schemas for this product can be found in the \schemas directory under the program directory into which you have installed the MapXtreme 2004.
WMS Server Configuration Schema Diagram
The next figure displays the detail of the Services element of the schema.
WMS Server Configuration Services Schema Diagram
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
239
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 20: WMS and WFS
Understanding the WMS Server-Specific Operations
There are three WMS Server specific operations that provide the basis for the Server implementation.
•
GetCapabilities -- retrieves service-level metadata over the Internet or intranet, including the server name, the layer names, abstracts about the data, and the acceptable request parameters.
•
GetMap -- retrieves the geo-spatial information over the Internet or intranet pertaining to the requested layer, styles, boundaries, the spatial reference system (coordinate system of the data being retrieved) the data including to request a map image of the data you want. You can also specific the image format (JPEG, GIF, etc.) and styles.
•
GetFeatureInfo -- Use to request information for a feature at a given point on the map after a GetMap has been called (optional).
Each of these methods are discussed in more detail below.
Note:
A basic WMS classifies its geo-referenced information holdings into “Layers” and offers a finite number of predefined “Styles” in which to display those layers. The behavior of a WMS can be extended to allow user-defined symbolization of feature data instead of named Layers and Styles.
Understanding the WMS Server GetCapabilities Operations
GetCapabilities retrieves service-level metadata over the Internet or intranet, including the server name, the layer names, abstracts about the data, and the acceptable request parameters.
Understanding the WMS Server GetMap Operations
GetMap retrieves the geo-spatial information over the Internet, including to request a map image of the data you want. You can also specific the image format (JPEG, GIF, etc.), styles and coordinate system. When invoking GetMap a WMS Client can specify:
•
Layers
•
Styles
•
A bounding box (the area to be mapped)
•
A Coordinate reference system (numeric representation of the map, also known as the spatial reference system)
•
Output format
•
Output size (height and width)
•
Background transparency and color
Understanding the WMS Server GetFeature Operations
GetFeatureInfo returns request information for a feature at a given point on the map after a
GetMap has been called. This is a search at point operation, in which, a GetMap request, the
GetFeatureInfo request supplies the X and Y coordinates of the location you want more information about.
Using the MapXtreme 2004 WMS Client
MapXtreme 2004 comes with a WMS Client that you can use programmatically to access data from OGC-compliant Web Map Services.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
240
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 20: WMS and WFS
To get to the server, in your application provide a URL to the WMS and call one of these supported methods in the Wms.ClientUtilities:
•
GetCapabilities — retrieves service-level metadata over the Internet or intranet, which is a description of the service's content and acceptable request parameters.
•
GetMap — retrieves a map image whose geospatial and dimensional parameters are well-defined. When invoking the GetMap operation, a WMS Client can specify the information to be shown on the map (one or more “Layers”), possibly the “Styles” of those Layers, what portion of the Earth is to be mapped (a “Bounding Box”), the projected or geographic coordinate reference system to be used (the “Spatial
Reference System”), the desired output format. You can also specific the image format
(JPEG, GIF, etc.), styles and coordinate system.
•
GetFeatureInfo — retrieves information about specific features on the map you requested (optional).
Each of these methods is discussed in more detail in the following sections.
Understanding the WMS Client GetCapabilities Operations
In the ClientUtilities, the GetCapabilities retrieves service-level metadata over the Internet or intranet, including the server name, the layer names, abstracts about the data, and the acceptable request parameters.
Understanding the WMS Client GetMap Operations
GetMap retrieves the geo-spatial information over the Internet, including to request a map image of the data you want. You can also specific the image format (image\jpeg, image\gif, etc.), styles and coordinate system. When invoking GetMap, a WMS Client can specify:
•
Layers
•
Styles
•
A bounding box (the area to be mapped)
•
Coordinate reference system (numerical representation of the map, also known as the spatial reference system)
•
Output format
•
Output size (height and width)
•
Background transparency and color
Understanding the WMS Client GetFeatureInfo Operations
GetFeatureInfo returns request information for a feature at a given point on the map after a
GetMap has been called. (The use of this operation is optional). This is a search at point operation, in which, following a GetMap request, the GetFeatureInfo request supplies the X and
Y coordinates of the location you want more information about.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
241
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Using the WMS Map Image
Chapter 20: WMS and WFS
There is a growing amount of geo-spatial data available, provided by governments, corporations, and civic groups, that users can retrieve to enhance the accuracy and completeness of their maps. Companies with land use and water use data can add elevation and population information from the U.S. Census Bureau, or from a local data provider.
Combining traffic pattern data with store location information can provide insight into establishing additional store locations or can optimize marketing and product placement efforts.
As a developer, you can customize routing requests to include particular hotel, attraction, or vacation destinations by extending the WMS code. The possibilities are limited only by your need and your imagination.
Further, since WMS information is returned as its own raster image it can be manipulated using style and transparency settings. This gives you many opportunities to customize the user’s
view of the data they are retrieving. See
Chapter 6: Adding Mapping Capability to your
Once you retrieve a WMS image using the MapXtreme Client capabilities, you may want to create a .tab file of it so MapXtreme can manage the display of the image. Keep in mind that what you are retrieving is a static image that has strict boundaries. If you then need to pan and zoom this raster image in your application, a .tab file allows you to use the mapping and data capabilities in MapXtreme 2004 to manipulate the data and the display.
There are two ways you can create a .tab file from a WMS raster image. You can open the image in MapInfo Professional and save it as a .tab file, or you can create the .tab file programmatically using the TableInfo.WMS.
The code sample below creates a .tab file from a retrieved WMS raster image.
// build the capabilities
ICapabilities capabilities = WmsClientUtilities.GetCapabilities
(url, "1.1.1");
// create the WMS client
WmsClient wmsClient = new WmsClient(capabilities); wmsClient.AddLayer("WORLD"); wmsClient.Srs = "EPSG:4326"; wmsClient.BGColor = Color.Blue; wmsClient.MimeType = "image/gif";
// create the table info
TableInfoWms wmsTableInfo= new TableInfoWms
("MyWmsTable", wmsClient);
// create the table
Table wmsTable = Session.Current.Catalog.OpenTable(wmsTableInfo);
// creates a FeatureLayer from the table entry
FeatureLayer featLyr = new FeatureLayer(wmsTable);
Note:
MapXtreme 2004’s implementation of WMS limits the size of the returned image to
2000 pixels each for width and height.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
242
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Web Feature Service
Chapter 20: WMS and WFS
MapXtreme 2004 provides a Web Feature Service (WFS) implementation to return geo-spatial
GML (Geography Markup Language)2 and GML3 data and HTTP GET and HTTP POST requests over the Internet or through a private intranet. WFS in MapXtreme 2004 was developed in accordance with the 1.0.0 OpenGIS® Web Feature Service Implementation
Specification. This document can be found at
http: //www.opengis.org/docs/02-058.pdf
.
The WFS specification has required and optional implementations. The required section, called
WFS Basic, is essentially a read-only service. The optional section is called WFS Transaction and allows for the addition, modification, and deletion of features in a feature type. The WFS implementation in MapXtreme 2004 implements WFS Basic only at this time.
Understanding the WFS Server
WFS Basic is composed of three services or operations provided by the WFS Server:
GetCapabilities, DescribeFeatureType, and GetFeature.
•
GetCapabilities returns the capabilities of the WFS server. Capabilities include the list of feature types, spatial query capabilities, non-spatial query capabilities, etc.
•
DescribeFeatureType returns an XML Schema document representing the format of all queries against a specific feature type. The format of the Schema is not defined by the WFS specification and is completely implementation dependent.
•
GetFeature allows querying the WFS server for one or more feature types with filters and property names.
Understanding the WFS Server GetCapabilities Operation
GetCapabilities returns service-level metadata. This metadata is a description of the information content and acceptable request parameters of the service. GetCapabilities is supported via HTTP GET and HTTP POST. The VendorSpecificCapabilities element is optional and will not be returned. The Operations element is optional but MapXtreme 2004 supports queries only.
MapXtreme 2004 supports the following spatial operators:
•
BBox
•
Equals
•
Disjoint
•
Intersects
•
Within
•
Contains
MapXtreme 2004 supports the following non-spatial operators:
•
Logical operators: AND, OR, and NOT
•
PropertyIsEqualTo
•
PropertyIsGreaterThan
•
PropertyIsGreaterThanOrEqualTo
•
PropertyIsLessThan
•
PropertyIsLessThanOrEqualTo
•
PropertyIsNotEqualTo
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
243
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
MapXtreme 2004 supports the following simple arithmetic operators:
•
Add
•
Div
•
Mul
•
Sub
Chapter 20: WMS and WFS
Understanding the WFS Server DescribeFeatureType Operation
DescribeFeatureType returns an XML schema document representing what the response to a
GetFeature request will look like. A feature type is a FeatureLayer in MapXtreme 2004. The schema returned will be of the same form as described in the examples in the WFS 1.0.0 specification.
DescribeFeatureType is supported via HTTP GET and HTTP POST. A feature type is a
FeatureLayer in MapXtreme 2004. The Schema returned will be of the same form as described in the examples in the WFS 1.0.0 specification. As stated in the specification, the schema can take any form as long as it is GML2. The schema will have the form whereby each column in the layer becomes an element.
MapXtreme 2004 does not return the following column types:
•
MIDbType.Binary
•
MIDbType.CoordSys
•
MIDbType.Date
•
MIDbType.Grid
•
MIDbType.Key
•
MIDbType.Raster
•
MIDbType.Style
Understanding the WFS Server GetFeature Operation
GetFeature allows querying the WFS Server for one or more feature types with optional filters and property names. It returns an instance document that can be validated against the schema returned via a call to the DescribeFeatureType method.
GetFeature is supported via HTTP GET and HTTP POST. It can read GML2 geometries and return either GML2 or GML3 geometries. In an HTTP GET request, filters are not supported.
Handling the WFS Server Configuration
The instructions for setting up the WFS Server are fairly similar to the WMS Server instructions.
Please use the IIS Configuration instructions from the WMS section before trying to configure your data using the instructions below. Once your IIS connection is configured, you are ready to configure the server with the data to be shared. To do this, create a WFS configuration XML file following the conventions in the schema (MXP_WMS_Configuration_1_0.xsd).
Note:
The schema file is available in the \schema directory under your program directory.
There are two files in the \WFS Config Files directory on the installation CD that you use to configure the WFS Server. The first file is the WFSSample.xml file which you will use to create the WFS configuration XML file to connect your WFS Server to your feature data. This configuration file needs to contain a list of layers and any information that the GetCapabilities response needs. When you have completed your changes to this file, rename it
WFSConfig.xml.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
244
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
The following changes need to be made to the WFSSample file:
Chapter 20: WMS and WFS
1.
In the
Service
section, the name, title, and URL of the WFS Server need to be changed to reflect your environment. This is a snippet from the sample XML file:
<mxp-wfs:Service>
<mxp-wfs:Name>Sample WFS Server</mxp-wfs:Name>
<mxp-wfs:Title>Sample WFS Server</mxp-wfs:Title>
<!-- The following is the URL of the WFS server -->
<mxp-wfs:OnlineResource> http://Host/virtualdirectory/GetMap.ashx
</mxp-wfs:OnlineResource>
</mxp-wfs:Service>
Note:
Once your server is configured, you can add your URL information in the
<mxp-wfs:OnlineResource>
entry using this convention: http://<host>/
<virtual directory name>/GetFeature.ashx
. Your users then can perform a GetCapabilities request by following this URL: http://<host>/<virtual directory name>/
GetFeature.ashx?service=WFS&request=GetCapabilities
.
2.
In the mxp:ConnectionSet
section, complete the database connection information required for your data (such as Oracle database, SQLServer).
<mxp:ConnectionSet>
<mxp:DBConnection dbType="MYSERVER">
<mxp:ConnectionName>MYCONNECTION</mxp:ConnectionName>
<mxp:ODBCConnectionString>
DRIVER={SQL Server};DATABASE=MYDB;
Server=MYDATABASE;UID=MYUID;PWD=MYPASSWORD;
QuotedID=No;Trusted_Connection=No;Network=DBMSSOCN;
Address=MYSERVER,1433</mxp:ODBCConnectionString>
</mxp:DBConnection>
</mxp:ConnectionSet>
3.
For each table or layer you are sharing, you need to complete a mxp-wfs:Table
entry to include the name, title, abstract, keywords, and datasourcedefinitionset information as in the example below.
<mxp-wfs:Table>
<mxp-wfs:Name>usa</mxp-wfs:Name>
<mxp-wfs:Title>Title for usa</mxp-wfs:Title>
<mxp-wfs:Abstract>Abstract for usa</mxp-wfs:Abstract>
<mxp-wfs:Keywords>Keywords for usa</mxp-wfs:Keywords>
<mxp:DataSourceDefinitionSet>
<mxp:TABFileDataSourceDefinition id="usa">
<mxp:DataSourceName>usa</mxp:DataSourceName>
<mxp:FileName>MYPATH\usa.tab</mxp:FileName>
</mxp:TABFileDataSourceDefinition>
</mxp:DataSourceDefinitionSet>
</mxp-wfs:Table>
Note:
The
<mxp-wfs:Name>
entry and the
<mxp:DataSourceName>
entry must be identical for these files to be valid.
Once you have completed and saved your entries to the WFSConfig.XML file, you can complete the Web.config file. A sample of the Web.config file is also in the \WFS Config Files directory on the installation CD.
Note:
This version of the Web.config file contains different entries than the file used in the
WMS Server configuration process of the same name.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
245
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 20: WMS and WFS
Edit the Web.config file by entering the path to the WFSConfig.xml file you just created in the
<appSettings>
section that specifies the location of the WFS Server configuration file. This entry is shown in the following example.
<appSettings>
<!-- Use this setting to specify the location of the WFS configuration file -->
<add key="configFile" value="C:\Wfs\WfsServer\WfsConfig.xml"/>
.
.
.
</appSettings>
As you can see in the code above, the key called configFile
points to the location of the WFS
Server's configuration file, which is the WFSConfig.xml file. The WFS configuration file contains a
Service
element that is used in the GetCapabilities response.
These sample files, the WFSSample.xml file and the Web.config.xml file are also available on the MapXtreme 2004 Web page on the
http://www.mapinfo.com
web site in the Developers >
Downloads section.
Understanding the WFS Client
The MapXtreme 2004 Web Feature Service (WFS) Client provides the ability to interact with any WFS 1.0.0 compliant Server at the API level. The WfsClient and related classes are located in the MapInfo.Wfs.Client namespace and uses the WFS Basic portion of the OGC specification. The WFS Client can call the following methods on any WFS 1.0.0 compliant server: GetCapabilities, DescribeFeatureType, and GetFeature.
Using the WFS Client GetCapabilities Method
The WFS Client can invoke the GetCapabilities method either via HTTP GET or HTTP POST.
The response to the request is either a MapInfo.Wfs.Client.WfsCapabilities object or a
ServiceExceptionReport, if the WFS Server returned a ServiceExceptionReport XML document. The WfsCapabilities object directly matches up with the wfs:WFS_Capabilities element in the WFS 1.0.0 XML schema. Using the Wfs_Capabilities object, you can learn more about a specific WFS 1.0.0 server.
Using the WFS Client DescribeFeatureType Method
The WFS Client can invoke the DescribeFeatureType method either via HTTP GET or HTTP
POST. The response is a System.Xml.Schema.XmlSchema object or a
ServiceExceptionReport, if the WFS Server returned a ServiceExceptionReport XML document.
Using the WFS Client GetFeature Method
The WFS Client can invoke the GetFeature method either via HTTP GET or HTTP POST. This method allows a user to perform spatial and non-spatial (scalar) queries against one or more feature types. The GetFeature method returns the results in a GML2 format in a
MapInfo.Data.MultiFeatureCollection or a ServiceExceptionReport if the WFS Server returned a ServiceExceptionReport XML document.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
246
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Chapter 20: WMS and WFS
Using the WFS Client GetFeature Filters
Filters can be applied to a GetFeature request. A filter may either be spatial or non-spatial
(scalar). Spatial queries like Bbox (which refers to the bounding box), Within, and Intersects are fully supported by the WFS Client in both HTTP GET and HTTP POST requests. Scalar filters allow queries to be conducted against specific properties of a feature type. Scalar queries like
PropertyIsEqualTo, PropertyIsGreaterThan, and others are fully supported in both HTTP GET and HTTP POST requests. Compound filters like AND and OR may also be used. See the
WFS schema and the WFS specification (http://www.opengis.org/docs/02-058.pdf), as well as the Filter Encoding specification (http://www.opengis.org/docs/02-059.pdf) for further details.
Parsing the Response
Parsing the Response is not specified in the WFS specification, nor does the specification describe an exact format for the results of a GetFeature request. The WFS specification only states that the request must be at least GML2. Since there are many versions of GML2 and in order for the WFS Client to be able to correctly convert the GML2 response from a WFS
Server, the developer must create a parser to convert the GML2 GetFeature response to a
MapXtreme 2004 MapInfo.Data.MultiFeatureCollection. This is done by implementing the
IWfsReader interface and registering that implementation with the
MapInfo.Wfs.Client.WfsReaderFactory class. Registration must occur on a per URL basis, that is, if the user wants to interact with two WFS Servers that have the same GetFeature response, the specific IWfsReader implementation must be registered twice for each server URL. The developer need not implement the entire interface. The MapInfo.Wfs.Client.WfsReader class may be extended to override the ReadGetFeature(XmlReader) method. Any of the other methods may be overridden when interacting with a non-compliant WFS Server.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
247
MapXtreme2004_DevGuide_A4.pdf
MapInfo SQL Reference
A
This reference defines the functions and operators that make up the MapInfo SQL Language.
In this appendix:
!
!
!
!
!
!
Developer Guide
Overview of the MapInfo SQL Language
Appendix A: MapInfo SQL Reference
The new MapXtreme 2004 object exposes SQL processing to the users via the MapInfo
ADO.NET Data Provider for accessing data (specifically the MICommand object). Expressions are also used for labeling, thematics, legends, AddColumns, Feature searching, and Selection processing. The new .NET-based products, beginning with MapXtreme 2004, use a newly created SQL language developed by MapInfo Corporation.
See
for more information on the tables, features and the
MapInfo Data Provider.
Previous versions of MapX and MapXtreme use an SQL syntax that is a subset of MapBasic. It is exposed to MapX and MapXtreme for Windows developers via the Layer.Search method.
MapX also has the ability to open view TAB files (TAB files which contain a Create View statement). The syntax for the Select statement contained within the TAB file is also in terms of this syntax.
The differences between MapBasic SQL (and MapX Layer.Search syntax) and the new
MapInfo SQL cover these areas:
•
Spatial Operators
•
String constants
•
Quoted identifiers
•
Functions
Spatial Operators
While both languages include the operators within and contains, their meaning is very different and affect results as well as performance. MapBasic's within operator returns true if the centroid of the geometry on the left hand side (lhs) of the operator is within the geometry on the right hand side (rhs) of the operator.
The new SQL (MapInfo SQL) does not use the centroid of the lhs geometry; rather, it tests to see if the entire lhs geometry is within the rhs geometry. This is equivalent to the “Entirely
Within” operator in MapBasic. Similarly, the contains operator in MapBasic tests to see if the lhs geometry contains the centroid of the rhs geometry. MapInfo SQL, again, does not use the centroid; rather, the contains operator applies to the geometries on the rhs and lhs (and performs a test equivalent to the MapBasic “Contains Entire” operator). MapInfo SQL exposes the CentroidWithin and ContainsCentroid operators which perform the centroid-based tests.
String Constants
MapBasic used double quotation marks to identify string constants. Standard SQL (as specified by the SQL-3 specification) uses single quotation marks for string constants. Double quotation marks are used to quote identifier names (see Quoted Identifiers below).
Quoted Identifiers
The new MapInfo SQL follows standard SQL conventions and uses double quotation marks to delineate an identifier which cannot be accurately parsed without the quotation marks. For example, a table name with a space in the name such as “United States” would not parse correctly without the quotation marks. MapBasic did not allow for quoted identifiers. As such, table names, columns, etc., were modified by MapInfo Professional to be parseable by
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
249
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix A: MapInfo SQL Reference
replacing spaces and other delineating characters with an underscore. Thus, when opening the table “United States.TAB”, the table name would be United_States. MapXtreme 2004 will no longer modify the names of the table for these purposes.
Functions
Most of the functions that were supported by MapX (in the subset of MapBasic) have changed.
Many have changed in name only while others have changed in argument signature.
TAB files that represent a view (e.g., contain the Create View statement) use SQL syntax to define the view. This SQL may be either MapBasic SQL or MapInfo SQL, depending on the version of the TAB file (another explicit property set inside the TAB file). For TAB files with a version number less than 800, the view syntax must be MapBasic syntax so that the file remains compatible with older version of MapInfo Professional. TAB files with a version number of 800 or higher must contain the new MapInfo SQL. These TAB files will not be compatible with older versions of MapInfo Professional.
MapInfo SQL Commands
The commands that comprise the MapInfo SQL Language are Select, Insert, Update, and
Delete.
Select
SELECT < select_list >
FROM { < table_source > } [ ,...n ]
[ WHERE < search_condition > ]
[ GROUP BY expression [ ,...n ] ]
[ ORDER BY {expression | column_position [ ASC | DESC ] } [ ,...n ]]
< select_list > ::=
{
*
| { table_name | table_alias }.*
| { expression } [ [ AS ] column_alias ]
} [ ,...n ]
< table_source > ::= table_name [ [ AS ] table_alias ]
Insert
INSERT [INTO] { table_name } [ ( column_list ) ]
{ VALUES ({expression | NULL}[, ...n]) | query_specification
Update
UPDATE { table_name }
SET {{ column_name } = { expression | NULL }} [, ...n]
[WHERE < search_condition > ]
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
250
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix A: MapInfo SQL Reference
Delete
DELETE [FROM] { table_name } [ WHERE < search_condition > ]
< search_condition > ::=
{ [ NOT ] < predicate > | ( < search_condition > ) }
[ { AND | OR } [ NOT ] { < predicate > | ( < search_condition > )
} [ ,...n ] ]
< predicate > ::=
{ expression [ { = | < > | != | > | >= | < | <= } expression ]
| string_expression [ NOT ] LIKE string_expression [ ESCAPE
'escape_character' ]
| expression [ NOT ] BETWEEN expression AND expression
| expression IS [ NOT ] NULL
}
Expression
Expression is a column name, pseudo column, column alias, constant, function, or any combination of column names, column aliases, constants, and functions connected by an operator(s). Column names and pseudo columns may be prefixed with a table name or a table alias followed by the dot (“.”) character.
Note:
Subqueries and the associated operators IN, ANY, SOME, and ALL are currently not supported by the MapInfo Data Provider.
GROUP BY
GROUP_BY_expression is a reference to a column in the select list — either an exact copy of the select list expression, the alias, a 1-based number indicating the position of the column, or coln where n is a number representing a column.
ORDER BY
ORDER_BY_expression is a reference to a column in the select list - either an exact copy of the select list expression, the alias, a 1-based number indicating the position of the column, or coln where n is a number representing a column.
The MapInfo SQL Language is based on the SQL-3 and SQL/MM standards. String literals must be enclosed in single quotation marks ('example') while identifiers (column names, table names, aliases, etc.) should be enclosed in double quotation marks (“example identifier”) if necessary. Identifiers only need to be quoted if the parsing logic is unable to correctly parse the identifier. This would include identifiers that have spaces in their names or other special characters.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
251
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Operators
Appendix A: MapInfo SQL Reference
MapInfo SQL supports the following operators:
/
^
-
*
=
+
)
(
<=
>=
<
>
<>
!=
,
%
@ or :
Symbol Usage
Addition operator; also concatenation operator.
Note:
MapBasic uses “&”
Subtraction operator; also unary negation
Multiplication operator
Division operator
Exponentiation operator
Equality operator (case sensitive for strings) (unless the platform forces us to be case insensitive, like in SQL Server default case)
Inequality operator
Inequality operator
Less-than operator
Greater-than operator
Less-than or equal-to operator
Greater-than or equal-to operator
Expression delimiter
Expression delimiter
''
""
Within
Contains
Wildcard symbol
List item and function argument separator
Parameter names - parameter names will be required to start with a @ or : symbol.
String constant delimiter
Quoted identifier delimiter
The first object is entirely inside the second object. (equivalent to MapBasic's
Entirely Within)
The second object is entirely inside the first object. (equivalent to MapBasic's
Contains Entire)
Intersects
CentroidWithin
The first object touches the second object (equivalent to MapBasic's Intersects,
Partly Within, and Partly Contains)
Centroid of the first object is within the second object (equivalent to MapBasic's
Within)
ContainsCentroid Centroid of second object is within the first object (equivalent to MapBasic's
Contains)
EnvelopesIntersect Tests if the envelopes (MBRs) of the operands intersect.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
252
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix A: MapInfo SQL Reference
Operator Precedence
When MapXtreme 2004 evaluates SQL expressions it needs to know which components of an expression to evaluate first. This is called precedence. By convention, certain operators are assigned different levels of precedence. Those with the highest level are evaluated first. The following table lists MI SQL operators in the order in which they are evaluated. Operators at the same level of precedence are evaluated from left to right, except for exponentiation, which evaluates from the right.
Highest Priority: parenthesis exponentiation negation multiplication, division addition, subtraction geographic operators comparison operators
Not
And
Lowest Priority:
Or
For example, the expression 3+4*2 produces a result of 11. That is because multiplication has a higher precedence than addition and is performed first. Parenthesis must be used to force MI
SQL to do the addition first: (3+4)*2.
Now consider this expression, which is intended to select all records July or September of
1999.
Year(RECEIVED)=99 and Month(RECEIVED)=7 or Month(RECEIVED)=9
Because “ and
” has higher precedence than “ or
”, MapXtreme 2004 treats this expression as though “ year(RECEIVED)=99 and month(RECEIVED)=7
” were enclosed in parentheses. In this case, any record for July 1999 or for September of any year would be selected. That's probably not what you want. However, by adding parentheses to the second expression, you can get the result you expect.
(RECEIVED)=99 and (month(RECEIVED)=7 or month(RECEIVED)=9)
When you are not sure how MapXtreme 2004 evaluates an expression with several operators, you should use parentheses to group elements as you want them.
Listing of Functions
The table below defines all the supported functions in MapInfo SQL under these headings.
•
Numeric Functions
•
String Functions
•
Date Functions
•
Conversion Functions
•
Geometry Constructor Functions
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
253
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix A: MapInfo SQL Reference
•
Geometry Predicate Functions (boolean)
•
Geometry Observer Functions (functions that return a scalar value)
•
Geometry Measurement Functions
•
Geometry Functions (functions that return a geometry)
•
Aggregation Functions
•
Geometry Aggregation Functions
•
Raster/Grid Functions
•
Other Functions
For the syntax of these functions, see
Alphabetic Listing of Functions on page 258
Description
Floor
Log
Mod
Round
Sign
Function Name
Numeric Functions
Abs
Acos
Asin
Atan
Ceil
Cos
Exp
Sin
Sqrt
Tan
Trunc
String Functions
Char_Length
InStr
Left
Lower
Calculates the absolute value
Calculates the arccosine
Calculates the arcsine
Calculates the arctangent
Always returns the smallest integer value not less than the argument
Calculates the cosine
Returns the value of e (the base of natural logarithms) raised to the power of the argument.
Always returns the highest integer value that is not greater than the argument
Calculates the natural logarithm
Modulo division
Rounds X to the nearest multiple of m. Argument m is optional and if missing rounds to the nearest integer.
Returns the sign of the argument as -1, 0, or 1 if the argument is negative, zero, or positive, respectively.
Calculates the sine
Calculates the square root
Calculates the tangent
Truncates a number to the specified number of decimal places
Returns the number of characters in the string argument.
Searches one character string for another character string
Returns a specified number of leftmost characters from a string
Converts a string to lower case
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
254
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix A: MapInfo SQL Reference
Ltrim
Right
Rtrim
Space
Substring
Trim
Function Name Description
Removes leading space characters from a string and returns the resulting string
Returns a specified number of rightmost characters from a string
Removes trailing space characters from a string and returns the resulting string
Returns a string consisting of a specified number of space characters
Extracts a portion of a string to form a new string
Removes leading and trailing space characters from a string and returns the resulting string
Converts a string to upper case Upper
Date Functions
Current_Date
Day
Returns the current date. Note: Non-deterministic
Returns the day portion of a date as an integer
Month
Weekday
Returns the month portion of a date as an integer
Returns an integer from 1 to 7, indicating the weekday of the specified date
Returns the year portion of a date as an integer Year
Conversion Functions
Ascii
Char
NumberToDate
StringToDate
DateToNumber
StringToNumber
DateToString
Returns the character code for the first character in a string
Returns a string of length 1 corresponding to a specified character code
Creates a Date from a number
Creates a Date from a character string
Converts a date into a number
Converts a string into a number
Converts a Date into a string
NumberToString Converts a number into a string
Geometry Constructor Functions
MI_Box Creates a new Feature Geometry object which represents a rectangular box
MI_Point Creates a new Feature Geometry object represents a point
Geometry Predicate Functions (boolean functions)
MI_Contains
MI_Intersects
Determines if one geometry object entirely contains another geometry object.
Determines if one geometry object intersects another geometry object
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
255
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix A: MapInfo SQL Reference
Function Name
MI_Within
MI_CentroidWithin
MI_ContainsCentroid
Description
Determines if one geometry object is entirely within another geometry object
Determines if the centroid of a geometry object lies within another geometry object
Determines if the centroid of a geometry object lies within another geometry object
MI_EnvelopesIntersect Determines if the minimum bounding rectangles (MBR) of two geometry objects intersect
Geometry Observer Functions (functions which return a scalar value)
MI_CentroidX
MI_CentroidY
MI_MinX
MI_MinY
Returns the x-coordinate of the centroid of a geometry object
Returns the y-coordinate of the centroid of a geometry object
Returns the minimum x value of the MBR of a geometry
Returns the minimum y value of the MBR of a geometry
MI_MaxX
MI_MaxY
MI_GeometryType
MI_X
Returns the maximum x value of the MBR of a geometry
Returns the maximum y value of the MBR of a geometry
Returns a string indicating the type of a geometry object
Returns the x coordinate of a Point geometry
MI_Y Returns the y coordinate of a Point geometry
Geometry Measurement Functions
MI_Area
MI_CentroidDistance
MI_Length
Returns the geographical area of a geometry object
Returns the geographic distance between the centroids of two geometry objects
Returns the geographic length of a line or polyline geometry object
MI_Perimeter Returns the geographic perimeter of a geometry object
Geometry Functions (functions which return a geometry)
MI_Buffer Returns a MultiPolygon geometry object which represents a buffered distance around another geometry object
MI_Centroid
MI_Envelope
MI_Union
MI_Intersection
MI_ConvexHull
MI_Transform
Returns the centroid of a geometry object as a Point geometry object
Returns an Envelope geometry object representing the minimum bounding rectangle (MBR) of the input geometry
Returns a geometry object which represents the union of two input geometry objects
Returns a geometry object which represents the intersection between two input geometry objects
Returns a MultiPolygon geometry object which represents a convex hull around the set of points contained in the input geometry
Transforms a geometry from one coordinate system to another
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
256
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix A: MapInfo SQL Reference
Function Name
Aggregation Functions
Avg
Count
Sum
Min
Description
Computes the average value of an aggregation of values
Counts the number of values in an aggregation of values
Computes the sum of an aggregation of values
Computes the minimum value of an aggregation of values
Max
WtAvg
ProportionSum
ProportionAvg
ProportionWtAvg
Computes the maximum value of an aggregation of values
Computes the weighted average value of an aggregation of values and weights
Computes the sum of an aggregation of values which are adjusted based on the proportion of two geometry objects
Computes the average of an aggregation of values which are adjusted based on the proportion of two geometry objects
Computes the weighted average of an aggregation of values which are adjusted based on the proportion of two geometry objects
Returns any individual value from the aggregation.
MI_AggregateIndividual
Geometry Aggregation Functions
MI_AggregateBuffer Returns a MultiPolygon geometry object which represents a buffered distance around the aggregated geometry objects
MI_AggregateConvexHull Returns a MultiPolygon geometry object which represents a convex hull around the set of points contained within an aggregated set of geometry objects
MI_AggregateEnvelope Returns an Envelope geometry object representing the minimum bounding rectangle (MBR) of an aggregated set of geometry objects
MI_AggregateIntersection Returns a geometry object which represents the intersection of an aggregated set of geometry objects
MI_AggregateUnion Returns a geometry object which represents the union of an aggregated set of geometry objects
Raster/Grid Functions
MI_ImageFile
MI_ImagePixelWidth
MI_ImagePixelHeight
Returns the filename from an ImageInfo (Raster or Grid)
Returns the width of a raster or grid image in pixels
Returns the height of a raster or grid image in pixels
MI_GridValueAtPixel
MI_GridMinValue
Returns the value of a Grid at the specified pixel location
Returns the minimum grid value
MI_GridMaxValue Returns the maximum grid value
Miscellaneous Other Functions
MI_EngineVersion
MI_SQLVersion
Indicates the version of the engine
Indicates the version of the SQL language the engine currently supports
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
257
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Alphabetic Listing of Functions
Abs
Calculates the absolute value
Syntax
Abs ( d )
Arguments
d is a double
Appendix A: MapInfo SQL Reference
Acos
Calculates the arccosine
Syntax
Acos ( d )
Arguments
d is a double value between –1 and 1 whose arccosine is to be calculated.
Ascii
Returns the character code for the first character in a string.
Syntax
Ascii ( str )
Arguments
str is a string.
Remarks
Ascii returns the character code for the first character in str. If str is an empty string, Ascii returns zero. If str is null, Ascii returns null.
Asin
Calculates the arcsine
Syntax
Asin ( d )
Arguments
d is a double value whose arcsine is to be calculated.
Atan
Calculates the arctangent
Syntax
Atan ( d )
Arguments
d is a double value whose arctangent is to be calculated.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
258
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix A: MapInfo SQL Reference
Avg
Computes the average value of an aggregation of values.
Syntax
Avg ( n )
Arguments
n is a numeric expression.
Remarks
Avg is an aggregation function which can only be used in an aggregating Select statement. Null values are ignored. If there are only null values supplied in the aggregation, then a null value is returned.
Ceil
Ceiling – Always returns the smallest integer value not less than the argument
Syntax
Ceil ( d )
Arguments
d is a double
Char
Returns a string of length 1 corresponding to a specified character code.
Syntax
Char ( n )
Arguments
n is a number representing the binary equivalent to a character.
Remarks
If n is null, then Char returns null.
Char_Length
Returns the number of characters in the string argument.
Syntax
Char_Length ( s )
Arguments
s is a string expression.
Remarks
If s is NULL, Char_Length returns zero (0).
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
259
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Cos
Calculates the cosine
Syntax
Cos ( d )
Arguments
d is a double value whose cosine is to be calculated.
Appendix A: MapInfo SQL Reference
Count
Counts the number of values in an aggregation of values.
Syntax
Count ( expression )
Count ( * )
Arguments
expression is any scalar expression of any data type.
Remarks
Count is an aggregation function which can only be used in an aggregating Select statement.
Null values are ignored except in the special form Count(*).
Current_Date
Returns the current date.
Syntax
Current_Date ()
Remarks
Note:
The Current_Date function is Non-deterministic.
DateToNumber
Converts a date into a number.
Syntax
DateToNumber ( date )
Arguments
date is a date.
Remarks
DateToNumber converts a date value (date) into an eight-digit integer representation of the date as YYYYMMDD.
DateToString
Converts a Date into a string.
Syntax
DateToString ( date, fmt )
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
260
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix A: MapInfo SQL Reference
Arguments
date is a date, and fmt is a string identifying how to format the date (date).
Remarks
Date Format Strings on page 284
for more information on using the fmt
argument to format dates.
Day
Returns the day portion of a date as an integer.
Syntax
Day ( date )
Arguments
date is a Date expression.
Remarks
Day returns an integer value between 1 and 31. If date is null, Day returns null.
Exp
Returns the value of e (the base of natural logarithms) raised to the power of the argument.
Syntax
Exp ( d )
Arguments
d is a double
Floor
Always returns the highest integer value that is not greater than the argument
Syntax
Floor ( d )
Arguments
d is a double.
InStr
Searches one character string for another character string.
Syntax
InStr ( str1, str2[, start_at[, occurrence]] )
Arguments
str1 is the string to search, str2 is the string to search for, start_at is an integer indicating the (one-based) position in str1 to begin searching, and occurrence is the integer indicating the occurrence of str2 to locate in str1.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
261
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix A: MapInfo SQL Reference
Remarks
Returns the (one-based) position in str1 that is the first character of the desired occurrence of str2. If the desired occurrence of str2 is not found, or of str1 or str2 is NULL, 0 is returned. The parameters start_at and occurrence are optional and default to 1 and 1, respectively.
Left
Returns a specified number of leftmost characters from a string.
Syntax
Left ( str, len )
Arguments
str is a string, and len is an integer, greater than or equal to zero.
Remarks
Left returns a string consisting of the leftmost len characters of the string expression str. The len parameter should be an integer value greater than or equal to zero. If len is equal to zero, a null value is returned. If len is greater than or equal to the length of the string str, then the entire string, str, is returned.
Log
Calculates the natural logarithm
Syntax
Log ( d )
Arguments
d is a double.
Lower
Converts a string to lower case.
Syntax
Lower ( str )
Arguments
str is a string
Ltrim
Removes leading space characters from a string and returns the resulting string.
Syntax
Ltrim ( str )
Arguments
str is a string
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
262
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix A: MapInfo SQL Reference
Max
Computes the maximum value of an aggregation of values.
Syntax
Max ( n )
Arguments
n is a numeric expression.
Remarks
Max is an aggregation function which can only be used in an aggregating Select statement.
Null values are ignored. If there are only null values supplied in the aggregation, then a null value is returned.
MI_AggregateBuffer
Returns a MultiPolygon geometry object which represents a buffered distance around the aggregated geometry objects.
Syntax
MI_AggregateBuffer ( geometry, dist, unit, calculationType, res )
Arguments
geometry is an expression which returns a geometry, dist is a number which represents the distance from the source geometry for the buffer, unit is an area unit specification, calculationType is a string that indicates whether to perform a ‘Spherical’ or ‘Cartesian’ calculation. There is no default, and res is a number which specifies the minimum number of segments used in creating a circle from buffering a point.
MI_AggregateConvexHull
Returns a MultiPolygon geometry object which represents a convex hull around the set of points contained within an aggregated set of geometry objects.
Syntax
MI_AggregateConvexHull ( geometry )
Arguments
geometry is an expression which returns a geometry
MI_AggregateEnvelope
Returns an Envelope geometry object representing the minimum bounding rectangle (MBR) of an aggregated set of geometry objects.
Syntax
MI_AggregateEnvelope ( geometry )
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
263
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Arguments
geometry is an expression which returns a geometry.
Appendix A: MapInfo SQL Reference
Remarks
The geometry object returned will be in the coordinate system of the input geometry.
MI_AggregateIndividual
Returns any individual value from the aggregation of values.
Syntax
MI_AggregateIndividual ( expression)
Arguments
expression is any expression
Remarks
When aggregating several records together, occasionally it is desirable to want a value from a column (or expression) without specifying the column or expression in the GroupBy clause.
Use MI _AggregationIndividual to accomplish this.
MI_AggregateIntersection
Returns a geometry object which represents the intersection of an aggregated set of geometry objects.
Syntax
MI_AggregateIntersection ( geometry )
Arguments
geometry is an expression which returns a geometry.
MI_AggregateUnion
Returns a geometry object which represents the union of an aggregated set of geometry objects.
Syntax
MI_AggregateUnion ( geometry )
Arguments
geometry is an expression which returns a geometry.
MI_Area
Returns the geographical area of a geometry object.
Syntax
MI_Area ( geometry, unit, calculationType )
Arguments
geometry is an expression which returns a geometry, unit is an area unit specification, and
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
264
MapXtreme2004_DevGuide_A4.pdf
sq li sq ch sq rd perch rood sq survey ft sq nmi sq twip sq pt sq pica sq degree acre hectare sq mi sq km sq in sq ft sq yd sq mm sq cm sq m
Value
Developer Guide Appendix A: MapInfo SQL Reference
calculationType is a string that indicates whether to perform a ‘Spherical’ or ‘Cartesian’ calculation. There is no default.
Remarks
The value returned is a double and represents a value in the units specified by the units argument. MI_Area is applicable only to geometries of type Envelope, Polygon, Multipolygon, and Ring. Any other type of input geometry results in a value of zero.
Valid values for unit are the following area units:
Description
square miles square kilometers square inches square feet square yards square millimeters square centimeters square meters square US Survey feet square nautical miles square twips square points square picas square degrees acres hectares square links square chains square rods perches roods
MI_Buffer
Returns a MultiPolygon geometry object which represents a buffered distance around another geometry object.
Syntax
MI_Buffer ( geometry, dist, unit, calculationType, res )
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
265
MapXtreme2004_DevGuide_A4.pdf
m survey ft nmi twip pt pica degree li ch rd ft yd mm cm mi km in
Value
Developer Guide
Arguments
geometry is an expression which returns a geometry,
Appendix A: MapInfo SQL Reference
dist is a number which represents the distance from the source geometry for the buffer, unit is an area unit specification, calculationType is a string that indicates whether to perform a ‘Spherical’ or ‘Cartesian’ calculation. There is no default, and res is a number which specifies the minimum number of segments used in creating a circle from buffering a point.
Remarks
The geometry object returned is in the same coordinate system as the supplied geometry argument. The distance (dist) is in the units specified by the units argument. If res is NULL or zero, a reasonable default value is used.Otherwise, res must be at least 3.The minimum number of segments used in fractional circles, such as formed when buffering the corners of a rectangle, will be proportionally smaller. (for example, a half circle will have at least res/2 segments). The distance, dist,may be either positive or negative.
Valid values for unit are the following distance units: miles kilometers inches feet yards millimeters centimeters meters
US Survey feet nautical miles twips points picas degrees links chains rods
Description
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
266
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix A: MapInfo SQL Reference
MI_Box
Creates a new Feature Geometry object which represents a rectangular box.
Syntax
MI_Box ( x1, y1, x2, y2, csys )
Arguments
x1, y1, x2, and y2 are doubles that identify the extents of the box, and csys is a coordinate system specification
Remarks
The csys parameter may be a reference to a bound coordinate system object or a string representation of a coordinate system using the codespace:code notation.
MI_Centroid
Returns the centroid of a geometry object as a Point geometry object.
Syntax
MI_Centroid ( geometry )
Arguments
geometry is an expression which returns a geometry.
Remarks
The point geometry object returned will be in the coordinate system of the input geometry.
MI_CentroidDistance
Returns the geographic distance between the centroids of two geometry objects.
Syntax
MI_CentroidDistance ( geom1, geom2, unit, calculationType )
Arguments
geom1 is an expression which returns a geometry, geom2 is an expression which returns a geometry, unit is a linear unit specification, and calculationType is a string that indicates whether to perform a ‘Spherical’ or ‘Cartesian’ calculation. There is no default.
Remarks
Calculates the distance between two points. If either of the geometry arguments, geom1 or geom2, is anything other than a point geometry, the centroid of the geometry will be used in the calculation. The value returned is a double and represents a value in the units specified by the units argument.
For valid values for unit see
MI_Buffer on page 265
:
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
267
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix A: MapInfo SQL Reference
MI_CentroidWithin
Determines if the centroid of a geometry object lies within another geometry object.
Syntax
MI_CentroidWithin ( testGeometry, containerGeometry )
Arguments
testGeometry and containerGeometry are geometry objects (or expressions).
Remarks
Returns true if the centroid of testGeometry lies within containerGeometry, false otherwise. If either testGeometry or containerGeometry are null, false is returned. The function is performed using the coordinate system of the first argument (testGeometry).
MI_CentroidX
Returns the x-coordinate of the centroid of a geometry object.
Syntax
MI_CentroidX ( geometry )
Arguments
geometry is an expression which returns a geometry.
Remarks
The value returned is a double and represents a value in terms of the coordinate system of the input geometry.
MI_CentroidY
Returns the y-coordinate of the centroid of a geometry object.
Syntax
MI_CentroidY ( geometry )
Arguments
geometry is an expression which returns a geometry.
Remarks
The value returned is a double and represents a value in terms of the coordinate system of the input geometry.
MI_Contains
Determines if one geometry object entirely contains another geometry object.
Syntax
MI_Contains ( containerGeometry, testGeometry )
Arguments
containerGeometry and testGeometry are geometry objects (or expressions).
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
268
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix A: MapInfo SQL Reference
Remarks
Returns true if containerGeometry entirely contains testGeometry, false otherwise. If either containerGeometry or testGeometry are null, false is returned. The function is performed using the coordinate system of the first argument (containerGeometry).
This is synonymous with MI_Within (testGeometry, containerGeometry).
MI_ContainsCentroid
Determines if the centroid of a geometry object lies within another geometry object.
Syntax
MI_ContainsCentroid ( containerGeometry, testGeometry )
Arguments
containerGeometry and testGeometry are geometry objects (or expressions).
Remarks
Returns true if the centroid of testGeometry lies within containerGeometry, false otherwise. If either containerGeometry or testGeometry are null, false is returned. The function is performed using the coordinate system of the first argument (containerGeometry).
MI_ConvexHull
Returns a MultiPolygon geometry object which represents a convex hull around the set of points contained in the input geometry.
Syntax
MI_ConvexHull ( geometry )
Arguments
geometry is an expression which returns a geometry
MI_EngineVersion
Indicates the version of the engine.
Syntax
MI_EngineVersion
MI_Envelope
Returns an Envelope geometry object representing the minimum bounding rectangle (MBR) of the input geometry.
Syntax
MI_Envelope ( geometry )
Arguments
geometry is an expression which returns a geometry.
Remarks
The geometry object returned will be in the coordinate system of the input geometry.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
269
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix A: MapInfo SQL Reference
MI_EnvelopesIntersect
Determines if the minimum bounding rectangles (MBR) of two geometry objects intersect.
Syntax
MI_EnvelopesIntersect
( geometry1, geometry2 )
Arguments
geometry1 and geometry2 are geometry objects (or expressions).
Remarks
Returns true if the MBR of geometry1 intersects the MBR of geometry2, false otherwise. If either geometry1 or geometry2 are null, false is returned. The function is performed using the coordinate system of the first argument (geometry1).
MI_GeometryType
Returns a string indicating the type of a geometry object.
Syntax
MI_GeometryType ( geometry )
Arguments
geometry is an expression which returns a geometry.
Remarks
The value returned is one of the following (which is also found in the
MapInfo.Geometry.GeometryType enumeration)
Envelope
Point
MultiPoint
MultiCurve
MultiPolygon
FeatureGeometryCollection
Curve
Ring
Polygon
LineString
MI_GridMaxValue
Returns the maximum grid value as a double.
Syntax
MI_GridMaxValue ( GridInfo )
Arguments
GridInfo is an expression which returns a GridInfo.
Remarks
Raster tables expose a RasterInfo and grid tables expose a GridInfo as the value for the
MI_Raster column. This function applies only to Grid images.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
270
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix A: MapInfo SQL Reference
MI_GridMinValue
Returns the minimum grid value as a double.
Syntax
MI_GridMinValue ( GridInfo )
Arguments
GridInfo is an expression which returns a GridInfo.
Remarks
Raster tables expose a RasterInfo and grid tables expose a GridInfo as the value for the
MI_Raster column. This function applies only to Grid images.
MI_GridValueAtPixel
Returns the value of a Grid at the specified pixel location as a double.
Syntax
MI_GridValueAtPixel ( GridInfo, XPixel, YPixel )
Arguments
GridInfo is an expression which returns a GridInfo,
XPixel is an expression which returns an integer representing the X pixel coordinate, and
YPixel is an expression which returns an integer representing the Y pixel coordinate
Remarks
Raster tables expose a RasterInfo and grid tables expose a GridInfo as the value for the
MI_Raster column. This function applies only to Grid images.
MI_ImageFile
Returns the filename from an ImageInfo (Raster or Grid) as a string.
Syntax
MI_ImageFile ( ImageInfo )
Arguments
ImageInfo is an expression which returns a RasterInfo or GridInfo.
Remarks
Raster tables expose a RasterInfo and grid tables expose a GridInfo as the value for the
MI_Raster column.
MI_ImagePixelHeight
Returns the height of a raster or grid image in pixels as an integer.
Syntax
MI_ImagePixelHeight ( ImageInfo )
Arguments
ImageInfo is an expression which returns a RasterInfo or GridInfo.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
271
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix A: MapInfo SQL Reference
Remarks
Raster tables expose a RasterInfo and grid tables expose a GridInfo as the value for the
MI_Raster column.
MI_ImagePixelWidth
Returns the width of a raster or grid image in pixels as an integer.
Syntax
MI_ImagePixelWidth ( ImageInfo )
Arguments
ImageInfo is an expression which returns a RasterInfo or GridInfo.
Remarks
Raster tables expose a RasterInfo and grid tables expose a GridInfo as the value for the
MI_Raster column.
MI_Intersection
Returns a geometry object which represents the intersection between two input geometry objects.
Syntax
MI_Intersection ( geometry1, geometry2 )
Arguments
geometry1 is an expression which returns a geometry, and geometry2 is an expression which returns a geometry.
MI_Intersects
Determines if one geometry object intersects another geometry object.
Syntax
MI_Intersects ( geometry1, geometry2 )
Arguments
geometry1 and geometry2 are geometry objects (or expressions).
Remarks
Returns true if geometry1 intersects geometry2, false otherwise. If either geometry1 or geometry2 are null, false is returned. The function is performed using the coordinate system of the first argument (geometry1).
MI_Length
Returns the geographic length of a line or polyline geometry object.
Syntax
MI_Length ( geometry, unit, calculationType )
Arguments
geometry is an expression which returns a geometry,
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
272
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
unit is a linear unit specification, and
Appendix A: MapInfo SQL Reference
calculationType is a string that indicates whether to perform a ‘Spherical’ or ‘Cartesian’ calculation. There is no default.
Remarks
The value returned is a double and represents a value in the units specified by the units argument. MI_Length is applicable only to geometries of type Curve, LineString, and
MultiCurve. Any other type of input geometry results in a value of zero.
For valid values for unit see
MI_Buffer on page 265
:
MI_MaxX
Returns the maximum x value of the MBR of a geometry.
Syntax
MI_MaxX ( geometry )
Arguments
geometry is an expression which returns a geometry.
Remarks
The value returned is a double and represents a value in terms of the coordinate system of the input geometry.
MI_MaxY
Returns the maximum y value of the MBR of a geometry.
Syntax
MI_MaxY( geometry )
Arguments
geometry is an expression which returns a geometry.
Remarks
The value returned is a double and represents a value in terms of the coordinate system of the input geometry.
MI_MinX
Returns the minimum x value of the MBR of a geometry.
Syntax
MI_MinX ( geometry )
Arguments
geometry is an expression which returns a geometry.
Remarks
The value returned is a double and represents a value in terms of the coordinate system of the input geometry.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
273
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix A: MapInfo SQL Reference
MI_MinY
Returns the minimum y value of the MBR of a geometry.
Syntax
MI_MinY ( geometry )
Arguments
geometry is an expression which returns a geometry.
Remarks
The value returned is a double and represents a value in terms of the coordinate system of the input geometry.
MI_Perimeter
Returns the geographic perimeter of a geometry object.
Syntax
MI_Perimeter ( geometry, unit, calculationType )
Arguments
geometry is an expression which returns a geometry, unit is a linear unit specification, and calculationType is a string that indicates whether to perform a ‘Spherical’ or ‘Cartesian’ calculation. There is no default.
Remarks
The value returned is a double and represents a value in the units specified by the units argument. MI_Perimeter is applicable only to geometries of type Envelope, Polygon,
Multipolygon, and Ring. Any other type of input geometry results in a value of zero.
For valid values for unit see
MI_Buffer on page 265
:
MI_Point
Creates a new Feature Geometry object represents a point.
Syntax
MI_Point( x, y, csys )
Arguments
x and y are doubles which identify the coordinates of the point, and csys is a coordinate system specification.
Remarks
The csys parameter may be a reference to a bound coordinate system object or a string representation of a coordinate system using the codespace:code notation.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
274
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix A: MapInfo SQL Reference
MI_SQLVersion
Indicates the version of the SQL language the engine currently supports.
Syntax
MI_SQLVersion
Remarks
The highest current value is 1.0.
MI_Transform
Transforms a geometry from one coordinate system to another.
Syntax
MI_Transform ( geometry, csys )
Arguments
geometry is an expression which returns a geometry, and csys is a coordinate system specification.
MI_Union
Returns a geometry object which represents the union of two input geometry objects.
Syntax
MI_Union ( geometry1, geometry2 )
Arguments
geometry1 is an expression which returns a geometry, and geometry2 is an expression which returns a geometry.
MI_Within
Determines if one geometry object is entirely within another geometry object.
Syntax
MI_Within ( testGeometry, containerGeometry )
Arguments
testGeometry and containerGeometry are geometry objects (or expressions).
Remarks
Returns true if testGeometry is entirely within containerGeometry, false otherwise. If either testGeometry or containerGeometry are null, false is returned. The function is performed using the coordinate system of the first argument (testGeometry).
This is synonymous with MI_Contains (containerGeometry, testGeometry).
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
275
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix A: MapInfo SQL Reference
MI_X
Returns the x coordinate of a Point geometry.
Syntax
MI_X ( point_geometry )
Arguments
point_geometry is an expression which returns a feature geometry of type Point.
Remarks
The value returned is a double and represents a value in terms of the coordinate system of the input point_geometry. If the input geometry is not a Point geometry, then null is returned.
MI_Y
Returns the y coordinate of a Point geometry.
Syntax
MI_Y ( point_geometry )
Arguments
point_geometry is an expression which returns a feature geometry of type Point.
Remarks
The value returned is a double and represents a value in terms of the coordinate system of the input point_geometry. If the input geometry is not a Point geometry, then null is returned.
Min
Computes the minimum value of an aggregation of values.
Syntax
Min ( n )
Arguments
n is a numeric expression.
Remarks
Min is an aggregation function which can only be used in an aggregating Select statement. Null values are ignored. If there are only null values supplied in the aggregation, then a null value is returned.
Mod
Modulo division.
Syntax
Mod ( d, v )
Arguments
d is a double and v is a double
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
276
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix A: MapInfo SQL Reference
Remarks
Divides one numeric expression by another numeric expression and returns the remainder.
Note: MapBasic treats this as an operator.
Month
Returns the month portion of a date as an integer.
Syntax
Month ( date )
Arguments
date is a Date expression.
Remarks
Month returns an integer value between 1 and 12. If date is null, Month returns null.
NumberToDate
Creates a Date from a number.
Syntax
NumberToDate ( n )
Arguments
n is an eight-digit integer representing a date as YYYYMMDD.
NumberToString
Converts a number into a string.
Syntax
NumberToString ( n, fmt )
Arguments
n is a number, and fmt is a string identifying how to format the number (n).
Remarks
Number Format Strings on page 285
for more information on using the
fmt argument to format numbers.
ProportionAvg
Computes the average of an aggregation of values which are adjusted based on the proportion of two geometry objects.
Syntax
ProportionAvg ( n, value_geometry, reference_geometry )
Arguments
n is a numeric expression, value_geometry is a geometry expression, and reference_geometry is a geometry expression.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
277
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix A: MapInfo SQL Reference
Remarks
ProportionAvg is an aggregation function which can only be used in an aggregating Select statement. Null values for n, value_geometry, and/or reference_geometry are ignored. If there are only null values supplied in the aggregation, then a null value is returned.
The values of n times a proportion are accumulated and averaged. The proportion is determined to be the area of the overlap of the value_geometry and the reference_geometry divided by the area of the value_geometry.
The ProportionAvg aggregation function can be replaced with the following formula:
Avg ( n * p ) where p is defined as
AreaOverlap(value_geometry, reference_geometry, 'sq mi', 'Spherical') /
MI_Area(value_geometry, 'sq mi', 'Spherical')
If the coordinate system of the value_geometry is Non-Earth, a Cartesian area calculation will be performed.
ProportionSum
Computes the sum of an aggregation of values which are adjusted based on the proportion of two geometry objects.
Syntax
ProportionSum ( n, value_geometry, reference_geometry )
Arguments
n is a numeric expression indicating the values to add, value_geometry is a geometry expression, and reference_geometry is a geometry expression.
Remarks
ProportionSum is an aggregation function which can only be used in an aggregating Select statement. Null values for n, value_geometry, and/or reference_geometry are ignored. If there are only null values supplied in the aggregation, then a null value is returned.
The values of n times a proportion are accumulated. The proportion is determined to be the area of the overlap of the value_geometry and the reference_geometry divided by the area of the value_geometry.
For example, a reference geometry might be a region representing a flood risk which intersects several counties. The population for each county could be proportionally summed based on the proportion of the county’s area which overlaps the risk region.
The ProportionSum aggregation function can be replaced with the following formula:
Sum ( n * p ) where p is defined as
AreaOverlap(value_geometry, reference_geometry, 'sq mi', 'Spherical') /
MI_Area(value_geometry, 'sq mi', 'Spherical')
If the coordinate system of the value_geometry is Non-Earth, a Cartesian area calculation will be performed.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
278
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix A: MapInfo SQL Reference
ProportionWtAvg
Computes the weighted average of an aggregation of values which are adjusted based on the proportion of two geometry objects.
Syntax
ProportionWtAvg ( n, w, value_geometry, reference_geometry )
Arguments
n is a numeric expression, w is a numeric expression indicating the weight, value_geometry is a geometry expression, and reference_geometry is a geometry expression.
Remarks
ProportionWtAvg is an aggregation function which can only be used in an aggregating Select statement. Null values for n, value_geometry, and/or reference_geometry are ignored. If there are only null values supplied in the aggregation, then a null value is returned. If the denominator results in a value of zero (which would occur if the weight or the area of the overlap are zero for each record accumulated), then a value of null will be returned.
The ProportionAvg aggregation function can be replaced with the following formula:
Sum ( n * w * a ) / Sum ( w * a ) where a is defined as
AreaOverlap(value_geometry, reference_geometry, 'sq mi', 'Spherical')
If the coordinate system of the value_geometry is Non-Earth, a Cartesian area calculation will be performed.
Right
Returns a specified number of rightmost characters from a string.
Syntax
Right ( str, len )
Arguments
str is a string, and len is an integer, greater than or equal to zero.
Remarks
Right returns a string consisting of the rightmost len characters of the string expression str. The len parameter should be an integer value greater than or equal to zero. If len is equal to zero, a null value is returned. If len is greater than or equal to the length of the string str, then the entire string, str, is returned.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
279
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix A: MapInfo SQL Reference
Round
Rounds X to the nearest multiple of m. Argument m is optional and if missing rounds to the nearest integer.
Syntax
Round ( X, m )
Arguments
X is a double indicating the value to round, and m is a double indicating the nearest value to which X will be rounded.
Rtrim
Removes trailing space characters from a string and returns the resulting string.
Syntax
Rtrim ( str )
Arguments
str is a string
Sign
Returns the sign of the argument as –1, 0, or 1 if the argument is negative, zero, or positive, respectively.
Syntax
Sign ( d )
Arguments
d is a double
Sin
Calculates the sine
Syntax
Sin ( d )
Arguments
d is a double
Space
Returns a string consisting of a specified number of space characters.
Syntax
Space ( len )
Arguments
len is an integer.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
280
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Remarks
If len is less than or equal to zero, a null value is returned.
Appendix A: MapInfo SQL Reference
Sqrt
Calculates the square root
Syntax
Sqrt ( d )
Arguments
d is a double
StringToDate
Creates a Date from a character string.
Syntax
StringToDate ( str, fmt )
Arguments
str is a string representation of a date, and fmt is a string identifying the format of str.
Remarks
Refer to the section
Date Format Strings on page 284
for more information on the meaning of
the fmt argument.
StringToNumber
Converts a string into a number.
Syntax
StringToNumber (str, fmt)
Arguments
str is a string representation of a number, and fmt is a string identifying the format of str.
Remarks
StringToNumber converts a string value (str) into its numeric representation using the string
template (fmt) to interpret the numeric string (str). Refer to the section
Number Format Strings on page 285
for more information on the meaning of the fmt argument.
Substring
Extracts a portion of a string to form a new string.
Syntax
Substring ( str1, start[, length] )
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
281
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix A: MapInfo SQL Reference
Arguments
str1 is the source string, start is the one-based index into string str1 at which the extraction is to begin, and length is an integer indicating the number of characters to extract.
Remarks
The length parameter is optional and, if omitted, defaults to the end of str1.
Sum
Computes the sum of an aggregation of values.
Syntax
Sum ( n )
Arguments
n is a numeric expression.
Remarks
Sum is an aggregation function which can only be used in an aggregating Select statement.
Null values are ignored. If there are only null values supplied in the aggregation, then a null value is returned.
Tan
Calculates the tangent
Syntax
Tan ( d )
Arguments
d is a double
Trim
Removes leading and trailing space characters from a string and returns the resulting string.
Syntax
Trim ( str )
Arguments
str is a string
Trunc
Truncates the argument X to the number of decimal places specified by d.
Syntax
Trunc ( X, d )
Arguments
X is a double, and d is an integer
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
282
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix A: MapInfo SQL Reference
Remarks
For example, Trunc(12.345, 1) returns 12.3. The value of d can be negative in which case it refers to the number of decimal places to the left of the decimal point. Trunc(12.345, -1) returns
10. d is optional and if missing is assumed to be zero.
Upper
Converts a string to upper case.
Syntax
Upper ( str )
Arguments
str is a string
Weekday
Returns an integer from 1 to 7, indicating the weekday of the specified date.
Syntax
Weekday ( date )
Arguments
date is a Date expression.
Remarks
Weekday returns an integer value representing the day of the week with 1 = Sunday, 2 =
Monday, etc. If date is null, Year returns null.
WtAvg
Computes the weighted average value of an aggregation of values and weights.
Syntax
WtAvg ( n, w )
Arguments
n is a numeric expression indicating the values to average, and w is a numeric expression indicating the weight to apply to n.
Remarks
WtAvg is an aggregation function which can only be used in an aggregating Select statement.
Null values for n and/or w are ignored. If there are only null values supplied in the aggregation, then a null value is returned. If the denominator results in a value of zero (which would occur if the weights are zero for each record accumulated), then a value of null will be returned.
WtAvg can be replaced with the following formula
Sum (n * w) / Sum (w)
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
283
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix A: MapInfo SQL Reference
Year
Returns the year portion of a date as an integer.
Syntax
Year ( date )
Arguments
date is a Date expression.
Remarks
Year returns an integer value representing the year including the century (e.g., 2003). If date is null, Year returns null.
Date Format Strings
Format strings are used as templates for converting a string into a date and a date into a string.
The following tokens will be interpreted in the format string (fmt) and used to read the portions of a date value from a string (StringToDate) or replaced with the specified date component values to generate a string (DateToString).
dd d hh
H mm m dddd ddd
HH
H nn n ss
Token
yyyy yy mmmm mmm
Value
4 digit year (e.g., 2003)
2 digit year (e.g., 03).
Full month name – e.g., January
Abbreviated month name – e.g., Jan
2 digit month (including leading zero if appropriate). January = 1, December = 12.
1 or 2 digit month (no leading zero). January = 1, December = 12.
Full day of the week name, e.g., – Tuesday.
Abbreviated day of the week name – e.g., Tues.
2 digit day of the month (including leading zero if appropriate).
1 or 2 digit day of the month (no leading zero).
2 digit hour in 12-hour format. Includes leading zero if appropriate.
1 or 2 digit hour in 12-hour format with no leading zero.
2 digit hour in 24-hour format. Includes leading zero if appropriate.
1 or 2 digit hour in 24-hour format with no leading zero.
2 digit minute. Includes leading zero if appropriate.
1 or 2 digit minute with no leading zero.
2 digit second. Includes leading zero if appropriate.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
284
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix A: MapInfo SQL Reference
s t
T
Token Value
1 or 2 digit second with no leading zero.
AM or PM am or pm
Note:
The table identifies the tokens that translate portions of the time value. However, time is currently not supported by MapXtreme 2004. These tokens will NOT be supported and will be translated as-is (e.g., as static text).
When calling DateToString, the format string (fmt) may contain other tokens and characters which will be passed on to the resulting string unchanged.
Examples using Date Format Strings
Given the date Tuesday, October 7, 2003 as the value of argument 'date', the following calls to
DateToString produce the indicated results.
DateToString(date, 'mm-dd-yy') : 10-07-03
DateToString(date, 'm-d-yyyy') : 10-7-2003
DateToString(date, 'dddd, mmmm d, yyy') : Tuesday, October 7, 2003
DateToString(date, 'Today is dddd') : Today is Tuesday
The following calls to StringToDate all produce a date value for October 7, 2003.
StringToDate('10/7/2003', 'm/d/yyyy')
StringToDate('10-07-03', 'm-dd-yy')
StringToDate('Today is 2003-Oct-07', 'Today is yyyy-mmm-dd')
Number Format Strings
Format strings are used as templates for converting a string into a number and a number into a string. The following elements may be combined in the format string (fmt) and used to generate a string from a number (NumberToString) or a number from a string (StringToNumber).
Element
9
0
$
, (comma)
. (period)
MI
Value
Each 9 represents a significant digit to be displayed. Leading zeros are displayed or treated as blanks.
Each represents a significant digit. Leading zeros are displayed or treated as zeros.
Prefix: puts a dollar sign ($) in front of the number. See the L element for other currency characters.
Represents a comma in the numeric string. The comma is always interpreted as a group separator. See the G element for other group separator characters.
Represents a decimal point in the numeric string. See the D element for other decimal point characters.
Suffix: places a minus sign after the number if it is negative or a space if it is positive.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
285
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Element
S
D
G
L
Appendix A: MapInfo SQL Reference
Value
Prefix or Suffix: Places a plus(+) sign in front of a positive number and a minus(-) sign in front of a negative number.
Specifies the location of the decimal point. All format elements to the left of D will format the integer component of the value. All format elements to the right of D will format the fractional part of the value. Determination of the character used to represent the decimal character is platform specific – e.g., for MapXtreme 2004 this value will be determined by the Culture setting of the current thread. For Spatialware, this will be determined by the database (most likely an initialization parameter).
Specifies the location of the group separator (e.g., the comma to separate thousands in 6,234). Like the decimal character (D), determination of the character used to represent the group character is platform specific.
Specifies the location of the local currency symbol (e.g., $). Like the decimal character (D), determination of the character used to represent the group character is platform specific.
Examples using Number Format Strings
The following examples illustrate the use of the number format elements to format a number or parse a string. Results that are shown with quotes to indicate the presence of blanks (spaces) in the result – the quotes themselves are not part of the result.
NumberToString(123.4567, '999999.99')
NumberToString(123.4567, '099999.99')
NumberToString(1234567, '99,999,999')
NumberToString(1234567, '9,999,999,999')
NumberToString(1234567, '0,999,999,999')
NumberToString(123.4567, '0.9999E99')
NumberToString(123.4567, '0.9999E09')
NumberToString(123.4567, '0.9999E+09')
NumberToString(12.345, '9.99')
: '123.46'
: '000123.46'
: ' 1,234,567'
: '1,234,567'
: ' 0,001,234,567'
: '1.2346E2'
: '1.2346E02'
: '1.2346E+02'
: '####'
StringToNumber(' 123.456', '9999.999')
StringToNumber(' 123.456-', '9999.999')
: 123.456
: Error
StringToNumber(' 123.456-', '9999.999MI') : -123.456
StringToNumber('1,234.56', '999,999.99') : 1234.56
StringToNumber('1,234.56', '999,999.9') : Error
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
286
MapXtreme2004_DevGuide_A4.pdf
Customizing MapXtreme
2004
B
This appendix contains examples of classes, interfaces, and other elements of MapXtreme 2004 which can be customized.
In this appendix:
!
!
Developer Guide
Customizable Classes
Appendix B: Customizing MapXtreme 2004
The following classes have been designed to facilitate sub-classing to create custom subclasses that more closely fit your development needs.
Engine.CustomProperties
Use the CustomProperties class to add custom information to an object. The different kinds of objects that CustomProperties can add to are: FeatureCollection, FeatureStyleModifer,
GmlFeatureCollection, GroupLayer, IFeatureCollection, IMapLayer, ISession, LabelModifier,
LabelSource, Legend, LegendFrame, Map, MapLayer, MapTool, MultiFeatureCollection,
Session.PooledSession, and Table. Add information using the Add method. Retrieve information using the Item method. CustomProperties can be of any type.
Note:
Do not add MapXtreme 2004 objects directly into a CustomProperties collection. Doing so causes errors during serialization. Instead add an Alias. For example, do not add a
Map to a CustomProperties collection. Instead add Map.Alias.
Here is an example of how CustomProperties is used to add and retrieve properties: using MapInfo.Engine;
CustomProperties bag = new CustomProperties(); bag.Add("One", 1); bag.Add("DateNow", DateTime.Now); int i = (int)bag["One"];
DateTime ts = (DateTime)bag["DateNow"];
Search
To customize your search functions, there are a few classes that you can work with to accomplish almost any kind of search that you desire. The QueryFilter class allows you to create custom “where” clause to be used in SQL queries; the QueryDefinition class allows you to define a custom SQL query to be executed; and a SearchResultProcessor sets up the post processing of the results of your query.
For an example of how these classes are used, refer to the Search sample application included in the Samples directory of your MapXtreme 2004 installation (the default installation location is: C:\Program Files\MapInfo\MapXtreme\6.0\Samples\Features\Search).
QueryFilter
The IQueryFilter interface defines the interface that all query filters must support. A QueryFilter is used to define all or part of the “where” clause of a QueryDefinition.
QueryDefinition
The QueryDefinition class defines a query to be executed by a search. The QueryDefinition is made up of a filter (IQueryFilter), Columns, and OrderBy. If no Columns are specified, then “*” is used.
ISearchResultProcessor or SearchResultProcessor
The SearchResultProcessor implements the ISearchResultProcessor interface which is used to do post processing on the results of a search to narrow down the rows selected.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
288
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix B: Customizing MapXtreme 2004
FeatureStyleModifier or FeatureOverrideStyleModifier
Create your own FeatureStyleModifiers to change the appearance of a layer by deriving from
FeatureStyleModifier or FeatureOverrideStyleModifier. These classes are used to specify a specific FeatureStyle modification for the objects in a specific layer.
The following example creates a modifier that sets regions in USA.TAB to red if the population has decreased from 1980 to 1990.
using MapInfo.Mapping; using MapInfo.Style; internal class UsaPopulatioinDecreasedModifier :
MapInfo.Mapping.FeatureStyleModifier
{ public UsaPopulationDecreasedModifier() : base(null, null)
{
// use 2 columns for expressions
Expressions = new string[] { I18N.Wrap(
"Pop_1980",I18N.WrapType.Column),
I18N.Wrap("Pop_1990",I18N.WrapType.Column) };
}
// called during draw events protected override System.Boolean
Modify(MapInfo.Styles.FeatureStyleStack styles, object[] values)
{
// compares the values from each column if ( double.Parse(values[0].ToString()) > double.Parse(values[1].ToString()) )
{
// if population decreased, color the region red
CompositeStyle style = styles.Current; if (style.AreaStyle.Interior is SimpleInterior)
{
((SimpleInterior)style.AreaStyle.Interior).ForeColor =
Color.Red;
// modifies the region return true;
}
}
// does not modify the region return false;
}
}
UserDrawLayer
The UserDrawLayer class is used to draw a custom layer in your map. You can populate this layer with anything you like, including a customized logo, a transparent overlay of points, etc.
To use this class derive a new class from it and overload the draw method. The sample code below illustrates this: using MapInfo.Mapping; class MyUserDrawLayer : UserDrawLayer, ISerializable
{ string myLayerName = "My User Draw Layer Name"; public string MyName { get { return myLayerName; } set { myLayerName = value; } }
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
289
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix B: Customizing MapXtreme 2004
// This constructor must be present for the class to be serializable public MyUserDrawLayer(string Name, string Alias) : base(Name, Alias) {} public override void Draw(MapInfo.Geometry.LRect ClientRect,
MapInfo.Geometry.LRect UpdateRect, Graphics graphics)
{
// Create pen.
Pen blackPen = new Pen(Color.Black, 3);
// Create location and size of rectangle.
float x = 10.0F; float y = 10.0F; float width = 200.0F; float height = 200.0F;
// Draw rectangle to screen.
graphics.DrawRectangle(blackPen, x, y, width, height);
} public override void GetObjectData(SerializationInfo info,
StreamingContext context)
{ base.GetObjectData(info, context); info.AddValue("myLayerName", myLayerName);
} public override void SetObjectData(SerializationInfo info,
StreamingContext context)
{ base.SetObjectData(info, context); myLayerName = info.GetString("myLayerName");
}
}
Windows.Controls
Many of the classes in the Windows.Controls namespace can be sub-classed to implement custom behavior. Below are two examples of customizing the LayerControl using this approach.
MapInfo.Windows.Controls.PropertiesUserControl
If you want to add your own custom tabs to the LayerControl, create a class that subclasses
PropertiesUserControl. Then add your class to the collection of other tab classes by calling the
LayerControl's GetLayerTypeControls() and SetLayerTypeControls() methods. For an example of how this works, refer to the sample application included in your Samples\Features directory of your MapXtreme 2004 installation. Look in the MapBackgroundControl.cs file in the
LayerControl sample application for the class MapBackgroundControl which subclasses
PropertiesUserControl.
MapInfo.Windows.Controls.LayerNodeHelper and all of its subclasses
LayerNodeHelper classes control the appearance and behavior of nodes in the LayerControl's layer tree. For example, these helper classes dictate which layers the user is allowed to remove. If the properties of the ILayerNodeHelper interface do not give you enough control over the appearance or behavior of layer nodes—for example, if you want to apply per-table logic, where the user is allowed to remove some map layers, but not others—you can subclass any of these helper classes, override the appropriate method, and perform your per-layer logic in your overridden method. Then put your new helper class to use by calling the
LayerControl.SetLayerTypeHelper method.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
290
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix B: Customizing MapXtreme 2004
By default, when the user removes a GroupLayer, a confirmation dialog appears, except in cases when the GroupLayer is completely empty—in that case, the empty GroupLayer is simply removed with no confirmation prompt (LabelLayers work similarly). To force the Layer
Control to always display a confirmation prompt, even when the GroupLayer is empty, create a class that derives from GroupLayerNodeHelper and override the IsRemovalConfirmed method.
The code example below illustrates how this is done.
using System; using MapInfo.Windows.Controls; namespace MapInfo.Samples.LayerControl
{ public class CustomLayerNodeHelper : GroupLayerNodeHelper
{ public CustomLayerNodeHelper()
{
} public override bool IsRemovalConfirmed(object obj)
{ return true;
}
}
}
Then, to use this new helper class in your application, call the LayerControl's
SetLayerTypeHelper method, using syntax such as this:
layerControlDlg.LayerControl.SetLayerTypeHelper( typeof(GroupLayer), new CustomLayerNodeHelper() );
The subclasses of LayerNodeHelper are:
•
MapNodeHelper
•
MapLayerNodeHelper
•
GroupLayerNodeHelper
•
LabelLayerNodeHelper
•
LabelSourceNodeHelper
•
LabelModifierNodeHelper
•
FeatureStyleModifierNodeHelper
•
RangedThemeNodeHelper
•
DotDensityThemeNodeHelper
•
IndividualValueThemeNodeHelper
•
PieThemeNodeHelper
•
BarThemeNodeHelper
•
GradSymbolThemeNodeHelper
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
291
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix B: Customizing MapXtreme 2004
Tools
Tools can be customized in two ways: by sub classing an existing tool or by adding code to a
Custom base tool. See
Customizing Tools in Chapter 14 on page 178
Styles
The following classes can be used to add customization to your collections of styles to apply to objects.
BitmapPointStyleRepository
The BitmapPointStyleRepository class is used to iterate through all current bitmap point styles and allows you to add new bitmap images from a specified directory. Using the Refresh() method places any new bitmap images into the repository that holds all images. The following code sample demonstrates the reloading of the collection of images used for
BitmapPointStyles from a directory named “C:\MyData\MyBitmapImages.” using MapInfo.Styles;
StyleRepository styleRepository = Session.Current.StyleRepository;
BitmapPointStyleRepository bmpPointStyleRepository = styleRepository.BitmapPointStyleRepository; bmpPointStyleRepository.Reload("C:\MyData\MyBitmapImages");
InteriorStyleRepository
The InteriorStyleRepository class is used to iterate through all current interior styles and allows you to add new bitmap images for new interior styles from a specified directory. To add onto the current set of interior patterns used to fill regions use the AppendBitmapPattern() method. The following code sample demonstrates adding a new BMP image to the InteriorStyleRepository.
using MapInfo.Styles;
StyleRepository styleRepository = Session.Current.StyleRepository;
InteriorStyleRepository interiorStyleRepository = styleRepository.InteriorStyleRepository;
// AppendBitmapPattern returns the zero-based index of the pattern in
// the repository. The index returned may be used to
// retrieve a SimpleInterior style using the repository indexer.
int index = interiorStyleRepository.AppendBitmapPattern(
"C:\MyImages\trees.bmp"
); if (index >= 0)
{
SimpleInterior style =
(SimpleInterior)interiorStyleRepository[index];
}
LineStyleRepository
The LineStyleRepository class is used to iterate through all current line styles and allows you to add new line styles (created with MILISTED.EXE, available for download from
MapInfo.com
).
The new MAPINFOW.PEN file is written by the MILISTED.EXE application and then you can use the Reload() method to put the new file into the repository. The following sample code demonstrates reloading the collection of line style patterns used for SimpleLineStyles from a
PEN file in the “C:\MyData” directory.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
292
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
using MapInfo.Styles;
Appendix B: Customizing MapXtreme 2004
StyleRepository styleRepository = Session.Current.StyleRepository;
LineStyleRepository lineStyleRepository = styleRepository.LineStyleRepository; lineStyleRepository.Reload("C:\MyData\MyLineStyles.PEN");
VectorPointStyleRepository
The VectorPointStyleRepository class is used to iterate through all current vector symbols and allows you to add new vector symbols from a specified file. In order to create your own version of the symbol set, you need to use the Symbol Maker MapBasic application. Once your vector symbol set is changed you use the Reload() method to read the symbol set into the repository.
The following sample code demonstrates reloading the collection of SimpleVectorPointStyles from an FNT file in the “C:\MyData” directory.
using MapInfo.Styles;
StyleRepository styleRepository = Session.Current.StyleRepository;
VectorPointStyleRepository vecPointStyleRepository = styleRepository.VectorPointStyleRepository; vecPointStyleRepository.Reload("C:\MyData\MyVectorSymbols.FNT");
GmlFeatureCollection
The GmlFeatureCollection class is used to import features from an XML file. Derive from this class for specific XML schema. You can add Features to a map by creating a FeatureCollection object and constructing FeatureObjects to add to it. Then you can insert the FeatureCollection into a table.
WorkSpacePersistence and WorkSpaceLoader
The WorkSpaceLoader can be subclassed so that the persistence file being used can hold extra information saved from the application. The developer can have the application write any information that they would like saved into the persistence XML file by adding it under the
UserData node. When the WorkSpacePersistence class writes the persistence file and there is some content in this node, the content is automatically written to the file. The
WorkSpaceLoader class or some derived version of the class reads in all the data including what is a child of the UserData node. The following code shows an example of this.
using MapInfo.Persistence; class myWorkSpaceLoader : WorkSpaceLoader
{ public myWorkSpaceLoader(string fileName): base(fileName)
{
// empty
} override public void Load()
{
// called parent Load() method.
base.Load();
XmlNode userData = this.UserDataXmlNode; foreach (XmlNode childNode in userData.ChildNodes)
{ string text = childNode.Name; text = childNode.InnerText;
// user can do their own load stuff here
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
293
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
}
}
}
Appendix B: Customizing MapXtreme 2004
Other Customizable Aspects of MapXtreme 2004
ADO.Net
If you are accessing data stored in a DataTable that is not accessible through an ADO.NET data provider, you can use the TableInfoAdoNet class to access TableTypes of non-mappable data for which we have not provided a DataSource. See the TableInfoAdoNet class in the online help for more detailed information about using this class.
Location of Application Data Files
Any MapXtreme 2004 application uses data stored in the following files.
File Type
Abbreviation file
Pen file
Projection file
Vector symbol file
Custom symbol directory
Nadcon files jgd2000 files
MAPINFOW.ABB
Filename
MAPINFOW.PEN
MapInfoCoordinateSystemSet.xml
MapInfow.fnt
CustSymb
*.las, *.los
jgd2000.*
By default, MapXtreme applications look in the following directories for data files:
•
C:\Program Files\Common Files\MapInfo\MapXtreme\6.0—This is the directory the
MapXtreme 2004 installer places these files.
•
The directory where your application is located. For a Windows application, this is the directory where the .exe file is located. For web applications, this is the directory where the Web.config file is located.
•
MapInfo.CoreEngine assembly folder—This directory is the last place any application looks.
The list of directories corresponding to the above locations is obtained via the
ISessions.AppDataPaths property which returns the list as a an array of strings. While you cannot add to this list programmatically, you can add to it by defining a custom section in the application’s configuration file. This is illustrated in the sample code below. Note that the order in which additional paths are defined determines the order in which they are searched, and all custom locations are searched before the default locations listed above.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="MapInfo.CoreEngine" type="MapInfo.Engine.ConfigSectionHandler,
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
294
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix B: Customizing MapXtreme 2004
MapInfo.CoreEngine, Version=1.0.0.75, Culture=neutral,
PublicKeyToken=93e298a0f6b95eb1" />
</configSections>
<MapInfo.CoreEngine>
<ApplicationDataPaths>
<SpecialPath>
<Personal>MyAppData</Personal>
</SpecialPath>
<Path>c:\MyAppData</Path>
</ApplicationDataPaths>
</MapInfo.CoreEngine>
</configuration>
Each element in the configuration element above is defined as follows:
<configSections>
This is where handlers for custom sections are declared. In this case the ConfigSectionHandler class defined in assembly MapInfo.CoreEngine is responsible for parsing the
MapInfo.CoreEngine section of the configuration file.
<MapInfo.CoreEngine>
This section contains settings for the MapInfo.CoreEngine assembly. Specifically, application data search paths.
<ApplicationDataPaths>
This section defines additional paths used by MapXtreme 2004 when searching for application data files.
<Path>
An element to use if the full path to the application data is known.
<SpecialPath>
Use this syntax if the application data is stored in a location relative to a well-known system folder. For example, if your application data is stored in a directory named MyAppData, located under the “My Documents” directory, then the entry in the configuration file looks like
<Personal>MyAppData</Personal>
, where “Personal” is the value of the
Environment.SpecialFolder enumeration that represents the “My Documents” directory. Any of the enumeration values in the Environment.SpecialFolder can be used to define an application data path in the configuration file.
Find Abbreviation File
The Abbreviation file can be customized to match your data to make your find operations more
Fine Tuning the Find Process in Chapter 10 on page 131
for more information.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
295
MapXtreme2004_DevGuide_A4.pdf
Understanding the New
MapInfo Workspace
C
In MapXtreme 2004 we have created a new type of workspace that is portable, interoperable, and uses the MapInfo codespace definition. In this appendix, we discuss the new workspace use and
capabilities. For more about the MapInfo codespace definition, see
Appendix E: Defining the MapInfo
In this appendix:
!
!
Developer Guide Appendix C: Understanding the New MapInfo Workspace
What is the New MapInfo Workspace?
Using MapXtreme 2004, you can persist the maps you create as XML-based workspaces (with a .MWS extension) that are portable and interoperable. You will then be able to share these maps with anyone else using MapInfo products regardless of their working environment.
If you are familiar with MapXtreme Java, MapX, or MapInfo Professional, you know that currently users persist maps using different file formats:
•
MapXtreme Java maps are saved as Map Definition Files (.MDF files)
•
MapX maps are saved as geosets (.GST files)
•
MapInfo Professional maps are saved as workspaces (.WOR files)
These files have been the way for users of individual MapInfo products to share maps. MapInfo
Professional workspaces can also contain settings for browser and layout windows, graphs, legends, and sometimes even printer settings.
Users requested a single persistence file format that could be shared by all MapInfo products.
The new MapInfo XML-based workspace used in MapXtreme 2004 will also be used by future releases of all MapInfo products. XML gives us the portability and interoperability we need to share workspaces across locales and networks.
In MapXtreme 2004, you can create named connections to define preferred paths for sharing new workspaces. Named connections allow you to specify alternate drive and path information or specific database connections to data on shared equipment. Users working on different computers can set up these named connection paths based on their own environment to use workspaces created by others. The path may be absolute or relative, but the file names are never included. Named connections can establish paths to a URI, a WMS, a local connection, and an RDBMS (using ODBC, OCI, or JDBC). Later, when a user gets a workspace that contains a named connection path, the correct path can be defined to locate the data referenced in the workspace.
MXP_MapDataSource_1_0.xsd is a fully documented XML schema file that specifies the format of the XML file used to define named connections. The XML schemas (.XSDs) that define the workspace and named connections are provided with MapXtreme 2004. There are comments in the schema files to assist you in using and understanding the workspace structure. You can view these files using any text viewing tool, such as Notepad, however, we recommend using a more robust XML viewing and editing tool.
Our XML documents use textual identifiers and, where possible, we have used identifiers defined by XML standards organizations. However, XML, being eXtensible, allows for identifiers to be added by any document author to clarify the meaning of the data used in the document. To ensure that these identifiers are clearly labelled as defined by the MapInfo
Corporation, we specify them in what we call the MapInfo Codespace. To review the MapInfo
Codespace identifiers, see
Appendix E: Defining the MapInfo Codespace
For more information about creating workspaces and about using the Workspace Manager, see
Chapter 18: Using the Workspace Manager
Note:
You cannot use workspaces created in MapInfo Professional with MapXtreme 2004.
MapXtreme 2004 can read MapX geosets.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
297
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Structure of a Workspace
Appendix C: Understanding the New MapInfo Workspace
To give you a sense of the structure of a workspace, let’s look at a workspace and the XML code behind it. We will be looking at the World.MWS workspace, which is in the Sample directory of your MapXtreme 2004 installation. Here, we describe four of the five types of data in the workspace.
1.
The Header contains the basic file information including the version type and the creation date.
2.
The Connection Section defines the location of the individual files that are contained in the workspace. This is where the named connection information is stored.
3.
The DataSourceDefinition Section lists the TAB file sources of the data in the workspace.
4.
The MapDefinition Section contains definitions of layer, theme, and label features associated with the workspace, such as the label details, the zoom range, the colors used, etc.
5.
The UserData Section allows applications to persist their own data. User data is a “wild card” element meaning you can enter any content you want because the schema does not validate it.
Header Section
The file begins with the required XML file header information that describes the XML version the file conforms to, the encoding description, and a field that indicates whether the file is a standalone. The top level element in the file is the Workspace Element, which contains attributes for the file version, date, and XML namespace definitions.
Note:
The supported encoding for workspace persistence is UTF-8 for MapXtreme 2004.
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<WorkSpace version="MXP_WorkSpace_1_0" date="2004-02-03T14:00:00" xmlns:gml="http://www.opengis.net/gml" xmlns="http://www.mapinfo.com/mxp">
Connection Section
The ConnectionSet section defines the database connections, file connections, and WMS connections that are necessary to use the workspace. Currently supported database connections include MS Windows ODBC connections, Oracle C interface (OCI) connections, and JDBC driver connections. File connections identify the path to the file. What follows are some examples of these connections. These connections do not appear in your sample workspaces, but rather serve as an example of database and file connections.
<ConnectionSet>
<FileConnection dbType="file">
<ConnectionName>mts_data_japanese</ConnectionName>
<FilePath>\\servername\DIR\AP\DATA\TestScripts\Japanese
</FilePath>
</FileConnection>
<DBConnection dbType="xy">
<ConnectionName>Project_xy_ids_informix_9.3</ConnectionName>
<ODBCConnectionString>Driver={INFORMIX 3.81 32 BIT};
UID=privateuser;PWD=privateuser;DATABASE=xy;
HOST=HOST;SRVR=Project_ds;SERV=1800;PRO=onsoctcp;
CLOC=en_US.CP1252;DLOC=en_US.CP1252;VMB=0;CURB=0;
OPT=;SCUR=0;ICUR=0;OAC=1;OPTOFC=0;RKC=0;ODTYP=0;DDFP=0;
DNL=0;RCWC=0
</ODBCConnectionString>
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
298
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix C: Understanding the New MapInfo Workspace
</DBConnection>
<DBConnection dbType="oracle">
<ConnectionName>Server_japanese_oracle_9i_release_2
</ConnectionName>
<OCIConnectionString>SRVR=INTL;UID=USER;PWD=USER;SCROLL=NO
</OCIConnectionString>
</DBConnection>
<DBConnection dbType="oracle">
<ConnectionName>SERVER_oracle_9i_release_1</ConnectionName>
<OCIConnectionString>SRVR=SERVER;UID=USER;PWD=USER
</OCIConnectionString>
</DBConnection>
<DBConnection dbType="sqlserver">
<ConnectionName>server_sqlserver2000_server</ConnectionName>
<ODBCConnectionString>DRIVER={SQL Server};
DATABASE=QADB;Server=Server;UID=User;PWD=user;
QuotedID=No;Trusted_Connection=No;Network=DBMSN;
Address=Server,1433</ODBCConnectionString>
</DBConnection>
<DBConnection dbType="informix">
<ConnectionName>spyro_ius_9.2_hpux</ConnectionName>
<ODBCConnectionString>Driver={INFORMIX 3.81 32 BIT};
UID=user;PWD=user;DATABASE=thedb;HOST=host;
SRVR=server_ds;SERV=1800;PRO=onsoctcp;CLOC=en_US.CP1252;
DLOC=en_US.CP1252;VMB=0;CURB=0;OPT=;SCUR=0;ICUR=0;
OAC=1;OPTOFC=0;RKC=0;ODTYP=0;DDFP=0;DNL=0;
RCWC=0</ODBCConnectionString>
</DBConnection>
</ConnectionSet>
DataSource Definition Section
The DataSource Definition section defines the data files (for example, TAB files) and database tables that are retrieved at each connection location. Optional meta data may also be included to describe the data that is retrieved.
<DataSourceDefinitionSet>
<DBDataSourceDefinition id="id1" readOnly="false">
<DataSourceName>alias_Line_ontario_oracle_9i_rel
</DataSourceName>
<ConnectionMember>
<ConnectionName>ontario_oracle_9i_release_1</ConnectionName>
</ConnectionMember>
<DBQuery>
<Query>select * from us_hiway_extra</Query>
</DBQuery>
<DBDataSourceMetadata>
<FeatureGeometryAttribute srsName="mapinfo:coordsys 1,62">
OBJECT
</FeatureGeometryAttribute>
<KeyAttributes />
</DBDataSourceMetadata>
</DBDataSourceDefinition>
<TABFileDataSourceDefinition id="id2" readOnly="false">
<DataSourceName>alias_Line_us_hiway_extra</DataSourceName>
<FileName>FeatureLayerBuilder\us_hiway_extra.tab</FileName>
</TABFileDataSourceDefinition>
<DBDataSourceDefinition id="id3" readOnly="false">
<DataSourceName>alias_Point_ontario_oracle_9i_re
</DataSourceName>
<ConnectionMember>
<ConnectionName>ontario_oracle_9i_release_1</ConnectionName>
</ConnectionMember>
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
299
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix C: Understanding the New MapInfo Workspace
<DBQuery>
<Query>select * from usa_caps_extra</Query>
</DBQuery>
<DBDataSourceMetadata>
<FeatureGeometryAttribute srsName="mapinfo:coordsys 1,62">
OBJECT
</FeatureGeometryAttribute>
<KeyAttributes />
</DBDataSourceMetadata>
</DBDataSourceDefinition>
<TABFileDataSourceDefinition id="id4" readOnly="false">
<DataSourceName>alias_Point_usa_caps_extra</DataSourceName>
<FileName>FeatureLayerBuilder\usa_caps_extra.tab</FileName>
</TABFileDataSourceDefinition>
<DBDataSourceDefinition id="id5" readOnly="false">
<DataSourceName>alias_Region_ontario_oracle_9i_r
</DataSourceName>
<ConnectionMember>
<ConnectionName>ontario_oracle_9i_release_1</ConnectionName>
</ConnectionMember>
<DBQuery>
<Query>select * from usa_extra</Query>
</DBQuery>
<DBDataSourceMetadata>
<FeatureGeometryAttribute srsName="mapinfo:coordsys 1,104">
OBJECT
</FeatureGeometryAttribute>
<KeyAttributes />
</DBDataSourceMetadata>
</DBDataSourceDefinition>
<TABFileDataSourceDefinition id="id6" readOnly="false">
<DataSourceName>alias_Region_usa_extra</DataSourceName>
<FileName>FeatureLayerBuilder\usa_extra.tab</FileName>
</TABFileDataSourceDefinition>
</DataSourceDefinitionSet> ...
Map Definition Section
The Map Definition section defines one or more maps and their constituent layers. Each map has display conditions that include the size of the image, the zoom and center settings, the coordinate system of the rendered map.
<MapDefinitionSet>
<MapDefinition id="id7" name="tab_map__632140027761992151" alias="alias_tab_map__632140027761992151">
<DisplayConditions>
<MapSize uom="mapinfo:imagesize pixel">
<ImageWidth>600</ImageWidth>
<ImageHeight>400</ImageHeight>
</MapSize>
<ZoomAndCenter>
<MapZoom uom="mapinfo:length mi">3000</MapZoom>
<gml:Point srsName="mapinfo:coordsys 1,62">
<gml:coordinates>-79.771366,38.003251000000006
</gml:coordinates>
</gml:Point>
</ZoomAndCenter>
<DisplayCoordSys>
<SRSName>mapinfo:coordsys 1,62</SRSName>
</DisplayCoordSys>
<ResizeMethod>preserveZoom</ResizeMethod>
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
300
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix C: Understanding the New MapInfo Workspace
<RasterConditions dither="halfTone" trueColor="true" optimizeRasterLayers="screen" optimizeVectorLayers="screen" />
</DisplayConditions>
<LayerList>
<FeatureLayer id="id8" name="Tab_Point_632140027762460886" alias="alias_Tab_Point_632140027762460886" volatile="unknown">
<DataSourceRef ref="id4" />
</FeatureLayer>
<FeatureLayer id="id9" name="Tab_Line_632140027764492071" alias="alias_Tab_Line_632140027764492071" volatile="unknown">
<DataSourceRef ref="id2" />
</FeatureLayer>
<FeatureLayer id="id10" name="Tab_Region_632140027764960806" alias="alias_Tab_Region_632140027764960806" volatile="unknown">
<DataSourceRef ref="id6" />
</FeatureLayer>
</LayerList>
<MapLegendSet />
</MapDefinition>
<MapDefinition id="id11" name="ontario_oracle_9i_release_1__632140027766054521" alias="alias_ontario_oracle_9i_release_1__632140027766054521">
<DisplayConditions>
<MapSize uom="mapinfo:imagesize pixel">
<ImageWidth>600</ImageWidth>
<ImageHeight>400</ImageHeight>
</MapSize>
<ZoomAndCenter>
<MapZoom uom="mapinfo:length mi">3000</MapZoom>
<gml:Point srsName="mapinfo:coordsys 1,62">
<gml:coordinates>-79.771366,38.003251000000006
</gml:coordinates>
</gml:Point>
</ZoomAndCenter>
<DisplayCoordSys>
<SRSName>mapinfo:coordsys 1,62</SRSName>
</DisplayCoordSys>
<ResizeMethod>preserveZoom</ResizeMethod>
<RasterConditions dither="halfTone" trueColor="true" optimizeRasterLayers="screen" optimizeVectorLayers="screen" />
</DisplayConditions>
<LayerList>
<FeatureLayer id="id12" name="oracle_usa_caps_extra_632140027766054521" alias="alias_oracle_usa_caps_extra_632140027766054521" volatile="unknown">
<DataSourceRef ref="id3" />
</FeatureLayer>
<FeatureLayer id="id13" name="oracle_us_hiway_extra_632140027768398196" alias="alias_oracle_us_hiway_extra_632140027768398196" volatile="unknown">
<DataSourceRef ref="id1" />
</FeatureLayer>
<FeatureLayer id="id14" name="oracle_usa_extra_632140027768866931" alias="alias_oracle_usa_extra_632140027768866931" volatile="unknown">
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
301
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix C: Understanding the New MapInfo Workspace
<DataSourceRef ref="id5" />
</FeatureLayer>
</LayerList>
<MapLegendSet />
</MapDefinition>
</MapDefinitionSet>
The layer list displays with the label properties that are set for this map. These properties include the layer the labels are on, the file source for the labels, the visibility rules for the labels including the range at which the labels are visible, if applicable, the font and size properties of the labels, the label character limits, callouts, if applicable, label position settings, alignment, justification, and orientation of the label with regard to the point it is labelling.
Creating a Workspace Programmatically
In MapX, you used the Map.SaveMapAsGeoset method to create a geoset from the existing map. You give users the ability to save their workspaces programmatically as well and view these workspaces in the Workspace Manager later on using the code fragment shown below.
Note:
Users need to have a map open with one or more layers to save it as a workspace.
// Reads a MapX geoset, writes a MapXtreme 2004 workspace.
using MapInfo.Persistence; using MapInfo.Mapping;
.
.
.
MapLoader MapLoader = MapLoader.CreateFromFile("my.gst");
MapExport MapExport = new MapExport();
MapExport.Map.Load(MapLoader);
MapInfo.Persistence wsp = new WorkSpacePersistence(); wsp.Save("c:\\temp\\newwork.mws");
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
302
MapXtreme2004_DevGuide_A4.pdf
Using the GeoDictionary
Manager
D
In this appendix:
!
!
!
!
!
Developer Guide
Overview
Appendix D: Using the GeoDictionary Manager
The GeoDictionary Manager is a utility that comes with MapXtreme 2004 to aid in your
Mapping applications. This appendix deals with how to use this tool.
Using the GeoDictionary Manager
The GeoDictionary Manager application is designed to support the manipulation of a
GeoDictionary file. The GeoDictionary is an XML file containing registration information about the MapInfo tables that can be matched by your application during automatic databinding. Only
MapInfo tables that can or will be matched against should be registered in the GeoDictionary.
There is no need to register every .tab file that an application uses in the GeoDictionary, and in fact there is some overhead in having unnecessary files registered. You only need to register those tables against which you would like to match.
Changes in the GeoDictionary Manager
The GeoDictionary Manager for MapXtreme 2004 is, in appearance, very similar to the utility that was included in MapX and previous versions of MapXtreme. The major difference is that now the underlying file (*.dct) is an XML file and completely editable using a text or XML editor.
The GeoDictionary Manager’s User Interface
This section describes the user interface for the GeoDictionary Manager.
Run GeoDictionary Manager
To run the GeoDictionary Manager when you want to manually register layers:
1.
Start -> All Programs -> MapInfo -> MapXtreme 2004 -> GeoDictionaryManager
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
304
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix D: Using the GeoDictionary Manager
The GeoDictionary Manager is displayed. The file last opened is reloaded upon startup.
Part
GeoDictionary
Description
The GeoDictionary edit box contains the full path to the GeoDictionary that is currently being managed. The button (to the right of the GeoDictionary edit box) allows the user to browse for another GeoDictionary to manage. Both binary and
XML GeoDictionary files can be opened, but only the XML format is saved.
Registered tables The Registered Tables list box contains a list of the friendly names for all tables registered in the GeoDictionary. Highlight a particular table to either unregister it or modify its properties. Double-clicking a table brings up the Properties dialog box to edit those properties.
Register The Register button brings up the common File Open dialog box, with the Files of
Type combo box set to “MapInfo Tables (*.tab)”. After the table has been chosen from the file picker, the Table Properties dialog for that table is displayed. If you choose multiple files in the File Open dialog box, a Properties dialog box is opened for each table added.
Unregister
Properties
New
Pressing this button removes the selected table from the GeoDictionary. You can also select multiple tables (by shift-clicking) for unregistering. The Unregister button does not remove the files from the disk.
The Properties button brings up the Table Properties dialog box for the selected table. See the Table Properties dialog box below.
The New button clears the fields on the screen allowing the creation of a new
GeoDictionary file. When you choose to close this GeoDictionary file you are prompted to save your changes.
Save
Save As
Exit
The Save button saves the current file as XML, regardless of the format of the file when it was opened.
The Save As button allows you to save the current file to a new name or location.
The Exit button closes the application. If you have modified the GeoDictionary file you are prompted to save your changes.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
305
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix D: Using the GeoDictionary Manager
Set the matching table properties for a given table using the Properties dialog box. To access the Properties Dialog box, click the Properties button, or double-click on any table name in the
Registered Tables list.
Part
MapInfo Table
Description
Match Percentage
Field Information
Table used to refine searches
Description
Read-only edit box containing the file name of the MapInfo table if it is located in the same directory of the GeoDictionary, or the relative pathname to the file if it is not. If the file is located on a different drive or volume, the full path is displayed.
This field provides a mechanism for changing the friendly name for the table. This control is defaulted to the Description tag in the .TAB file, or the filename if the Description tag is not found, but can be changed by the user. Note that changes to the description in the GeoDictionary
Manager are only be stored in the GeoDictionary and is not reflected in the table itself. This allows the GeoDictionary Manager to easily work with read-only data, e.g., data on CD-ROMs.
This field is initially populated with the default value for the GeoDictionary and can be altered for specific tables by changing this value.
Values must be between 1 and 100.
This list box contains a list of all the indexed columns in the table. If the box for a given column is checked, that field is searched during the matching process.
This field allows the user to set a refining table to determine exact match for data that is not unique in a particular index.
Some tables, e.g., US Counties, contain indexed columns that are not unique. In that situation, a refining table is necessary to determine an exact match for data. If the table has non-unique indexed columns, use this field to specify a table to use to match against to find unique entries.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
306
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Associated maps that this table belongs to
Add
Part
Remove
Appendix D: Using the GeoDictionary Manager
Description
This list box shows the particular Workspaces, GeoSets, or other files of which this particular table is a part.
This displays a common file picker to allow you to choose GeoSets,
Workspaces, or other files to associate with the particular Tab file.
Selecting one or more files adds them to the list of associated maps.
You can select multiple files by holding down the shift or control keys while clicking.
Deletes the selected geoset, workspace, or other filename from the list of associated maps.
The GeoDictionary File
The GeoDictionary file (*.dct) can be manipulated manually if you choose to skip using the
GeoDictionary Manager. If you understand and can write XML easily then this is a viable alternative to using the GeoDictionary Manager. The .dct file is straight XML.
Sample .dct file
The following is a sample GeoDictionary file, GeoDic_US.dct. This file is a very simple
GeoDictionary provided merely as an example of the structure.
<?xml version="1.0" encoding="Windows-1252" standalone="yes"?>
<!--GeoDictionary file-->
<GeoDictionary>
<DefaultMatchThreshold>80</DefaultMatchThreshold>
<MatchTables>
<MatchTable>
<TablePath>US_CNTY.TAB</TablePath>
<TableDescription>US county boundary</TableDescription>
<RefineTableName>USA.TAB</RefineTableName>
<MatchThreshold>90</MatchThreshold>
<AssociatedMaps>
<AssociatedMap>USA.GST</AssociatedMap>
</AssociatedMaps>
<MatchFields>
<MatchField>
<FieldName>County</FieldName>
</MatchField>
<MatchField>
<FieldName>Fips_code</FieldName>
</MatchField>
</MatchFields>
</MatchTable>
</MatchTables>
</GeoDictionary>
The elements in the structure correspond to individual fields and controls in the GeoDictionary
Manager as defined in the following table:
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
307
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix D: Using the GeoDictionary Manager
XML Element
Table Properties Dialog
Box Field
GeoDictionary none
DefaultMatchThreshold none
Description
The root element of the file
The DefaultMatchThreshold is the threshold of matching when a specific MatchThreshold is not defined for a particular table.
Note:
This value cannot be set using the
GeoDictionary Manager.
MatchTables
MatchTable none
MapInfo Table.
The container elements for the registered MatchTables.
There should be a single MatchTable element for each item in the Registered Table list.
The filename for each table to be matched.
TablePath
TableDescription
RefineTableName
MatchThreshold
MapInfo Table.
The relative path for each MatchTable.
Description field (also the name that appears in the
Registered Tables list in the main dialog box.
The friendly name for the MatchTable.
The related table with which to refine matching.
Table used to refine searches
Match Percentage The match threshold for this MatchTable. If none is specified, the DefaultMatchThreshold is used.
AssociatedMaps,
AssociatedMap
MatchFields
Associated maps to which this table belongs.
This list box shows the particular Workspaces and Geo-
Sets of which this particular table is a part.
none This element is a container for MatchField and Field-
Name elements.
MatchField, FieldName Field Information list box.
Each item in the list box that is checked to be searched for automatch and binding.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
308
MapXtreme2004_DevGuide_A4.pdf
Defining the MapInfo
Codespace
E
The MapInfo Codespace is a list of definitions and standards that are commonly used in creating
MapInfo maps and workspaces. You can refer to these definitions to assist you in using MapXtreme
2004. You may want to compare our codespace definitions with another commonly used codespace, the European Petroleum Survey Group (EPSG), which is available on their website:
http:// www.epsg.org/
.
In this Appendix:
!
Developer Guide Appendix E: Defining the MapInfo Codespace
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
310
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix E: Defining the MapInfo Codespace
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
311
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix E: Defining the MapInfo Codespace
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
312
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix E: Defining the MapInfo Codespace
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
313
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix E: Defining the MapInfo Codespace
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
314
MapXtreme2004_DevGuide_A4.pdf
Web Map Server
Example
F
This appendix contains a sample wmsconfig.xml file that illustrates a Web Mapping Service.
In this appendix:
!
Developer Guide
Sample WMS Configuration File
Appendix F: Web Map Server Example
The following XML file describes the configuration for a sample Web Map Service (WMS). You will need a similar file, named wmsconfig.xml, if you wish to host a WMS. For an overview of
MapXtreme 2004’s implementation of WMS, see
that defines the WMS configuration in MapXtreme 2004 is located on the product CD (file name
MXP_WMS_Configuration_1_0.xsd).
This sample server hosts map data that, when requested by a WMS client, will return a raster image of the data which can be used as a layer in your mapping application. Key elements have been marked in bold to highlight the types of information that you will need to include in your file. See also the document comments for further information.
<?xml version="1.0" encoding="utf-8"?>
<WmsConfig xmlns:gml="http://www.opengis.net/gml" xmlns:xlink="http:// www.w3.org/1999/xlink" xmlns:mxp="http://www.mapinfo.com/mxp" version="MXP_WMSConfig_1_0" disableFeatureInfo="false" xmlns="http:// www.mapinfo.com/mxp/wms" xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xsi:schemaLocation="http://www.mapinfo.com/mxp/wms
C:\SANDBOX\Schemas\WMS\1_0\MXP_WMS_Configuration_1_0.xsd">
<mxp-wms:Service>
<mxp-wms:Name>Sample WMS Server</mxp-wms:Name>
<mxp-wms:Title>Sample WMS Server</mxp-wms:Title>
<mxp-wms:Abstract>This is a sample WMS server
</mxp-wms:Abstract>
<mxp-wms:KeywordList/>
<!-- The following is the URL of the WMS server -->
<mxp-wms:OnlineResource>http://localhost/WMS/GetMap.ashx
</mxp-wms:OnlineResource>
<mxp-wms:Fees>$10</mxp-wms:Fees>
<mxp-wms:AccessConstraints>none</mxp-wms:AccessConstraints>
</mxp-wms:Service>
<!-- The following MIME types will not be used by the server -->
<mxp-wms:WmsRasterFormatExcludeSet>
<mxp-wms:Format>image/jpeg2000</mxp-wms:Format>
<mxp-wms:Format>image/photoshop</mxp-wms:Format>
<mxp-wms:Format>image/jp2</mxp-wms:Format>
</mxp-wms:WmsRasterFormatExcludeSet>
<!-- The following connection is referenced by one of the data sources -->
<ConnectionSet xmlns="http://www.mapinfo.com/mxp">
<DBConnection dbType="informix">
<ConnectionName>spyro</ConnectionName>
<ODBCConnectionString>Driver={INFORMIX 3.81 32
BIT};UID=atsmipro;PWD=atsmipro;DATABASE=qadb;
HOST=threemile;SRVR=threemile_ds;SERV=1800;
PRO=onsoctcp;CLOC=en_US.CP1252;DLOC=en_US.CP1252;
VMB=0;CURB=0;OPT=;SCUR=0;ICUR=0;OAC=1;OPTOFC=0;
RKC=0;ODTYP=0;DDFP=0;DNL=0;RCWC=0
</ODBCConnectionString>
</DBConnection>
</ConnectionSet>
<DataSourceDefinitionSet xmlns="http://www.mapinfo.com/mxp/wms">
<!-- The following data sources reference local TAB files -->
<TABFileDataSourceDefinition id="id1" readOnly="false" xmlns="http://www.mapinfo.com/mxp">
<DataSourceName>STATES</DataSourceName>
<FileName>C:\data\MIPro65\Tut_Data\Tut_Usa\USA\STATES.TAB
</FileName>
</TABFileDataSourceDefinition>
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
316
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix F: Web Map Server Example
<TABFileDataSourceDefinition id="id2" readOnly="false" xmlns="http://www.mapinfo.com/mxp">
<DataSourceName>US_HIWAY</DataSourceName>
<FileName>C:\data\MIPro65\Tut_Data\Tut_Usa\USA\US_HIWAY.TAB
</FileName>
</TABFileDataSourceDefinition>
<TABFileDataSourceDefinition id="id4" readOnly="false" xmlns="http://www.mapinfo.com/mxp">
<DataSourceName>CANHIWAY</DataSourceName>
<FileName>C:\data\MIPro65\Tut_Data\Tut_Usa\CANADA\CANHIWAY.TAB
</FileName>
</TABFileDataSourceDefinition>
<TABFileDataSourceDefinition id="id5" readOnly="false" xmlns="http://www.mapinfo.com/mxp">
<DataSourceName>OCEAN</DataSourceName>
<FileName>C:\data\MIPro65\Tut_Data\Tut_Usa\WORLD\OCEAN.TAB
</FileName>
</TABFileDataSourceDefinition>
<!-- The following data source references a local named connection -->
<DBDataSourceDefinition id="id3" readOnly="false" xmlns="http://www.mapinfo.com/mxp">
<DataSourceName>alias_Line_spyro</DataSourceName>
<ConnectionMember>
<ConnectionName>spyro</ConnectionName>
</ConnectionMember>
<DBQuery>
<Query>select * from usa_caps_extra</Query>
</DBQuery>
<DBDataSourceMetadata>
<FeatureGeometryAttribute srsName="mapinfo:coordsys 1,62"> sw_geometry</FeatureGeometryAttribute>
<KeyAttributes/>
</DBDataSourceMetadata>
</DBDataSourceDefinition>
<!-- The following data source uses an inline connection to an Oracle server -->
<DBDataSourceDefinition id="id6" readOnly="false" xmlns="http://www.mapinfo.com/mxp">
<DataSourceName>ASIA</DataSourceName>
<ConnectionMember>
<InlineDBConnection>
<OCIConnectionString>SRVR=ontario;UID=atsmipro;PWD=atsmipro
</OCIConnectionString>
</InlineDBConnection>
</ConnectionMember>
<DBQuery>
<Query>select * from "ATSJAVA"."ASIA"</Query>
</DBQuery>
<DBDataSourceMetadata>
<FeatureGeometryAttribute srsName="mapinfo:coordsys 1,0">
OBJECT
</FeatureGeometryAttribute>
<KeyAttributes/>
</DBDataSourceMetadata>
</DBDataSourceDefinition>
</DataSourceDefinitionSet>
<mxp-wms:WmsLayer queryable="false">
<mxp-wms:Name>World</mxp-wms:Name>
<mxp-wms:Title>The World</mxp-wms:Title>
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
317
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix F: Web Map Server Example
<mxp-wms:Abstract>This is a root layer that represents the whole world.
</mxp-wms:Abstract>
<!-- The following SRS is available to all layers -->
<mxp-wms:SRSNameSet>
<mxp:SRSName>EPSG:4326</mxp:SRSName>
</mxp-wms:SRSNameSet>
<mxp-wms:WmsStyleSet/>
<mxp-wms:WmsLayerList>
<mxp-wms:WmsLayer queryable="false">
<mxp-wms:Name>USA</mxp-wms:Name>
<mxp-wms:Title>United States</mxp-wms:Title>
<mxp-wms:Abstract>Contains layers for the United States
</mxp-wms:Abstract>
<!-- The following SRS is available to this layer and all of the layers underneath it -->
<mxp-wms:SRSNameSet>
<mxp:SRSName>EPSG:4267</mxp:SRSName>
</mxp-wms:SRSNameSet>
<mxp-wms:WmsStyleSet/>
<mxp-wms:WmsLayerList>
<mxp-wms:WmsLayer>
<mxp-wms:Name>States</mxp-wms:Name>
<mxp-wms:Title>States</mxp-wms:Title>
<mxp-wms:SRSNameSet/>
<mxp-wms:WmsStyleSet>
<mxp-wms:WmsStyle>
<mxp-wms:Name>BlueFill</mxp-wms:Name>
<mxp-wms:Title>Blue Fill</mxp-wms:Title>
<mxp-wms:Abstract>This is a blue area fill with a red border.</mxp-wms:Abstract>
<AreaStyle xmlns="http://www.mapinfo.com/mxp">
<!-- The following defines the red border -->
<LineStyle stroke="red" width="1" width-unit="mapinfo:imagesize pixel">
<Pen>mapinfo:pen 2</Pen>
</LineStyle>
<!-- The following defines the blue fill -->
<Interior fill-opacity="0" fill="(#id7)">
<Defs>
<Pattern id="id7">
<Bitmap uri="mapinfo:brush 2">
<ColorAdjustmentSet>
<ColorAdjustment color-1="nonWhite" color-2="blue" opacity="1"/>
<ColorAdjustment color-1="white" opacity="1"/>
</ColorAdjustmentSet>
</Bitmap>
</Pattern>
</Defs>
</Interior>
</AreaStyle>
</mxp-wms:WmsStyle>
</mxp-wms:WmsStyleSet>
<FeatureLayer id="id8" name="STATES" alias="STATES" volatile="unknown" xmlns="http://www.mapinfo.com/mxp">
<DataSourceRef ref="id1"/>
</FeatureLayer>
</mxp-wms:WmsLayer>
<mxp-wms:WmsLayer>
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
318
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix F: Web Map Server Example
<mxp-wms:Name>USHighways</mxp-wms:Name>
<mxp-wms:Title>US Highways</mxp-wms:Title>
<mxp-wms:Abstract>The major highways for the
United States</mxp-wms:Abstract>
<mxp-wms:SRSNameSet/>
<mxp-wms:WmsStyleSet/>
<FeatureLayer id="id9" name="US_HIWAY" alias="US_HIWAY" volatile="unknown" xmlns="http://www.mapinfo.com/mxp">
<DataSourceRef ref="id2"/>
</FeatureLayer>
</mxp-wms:WmsLayer>
<mxp-wms:WmsLayer>
<mxp-wms:Name>USCapitals</mxp-wms:Name>
<mxp-wms:Title>US Capitals</mxp-wms:Title>
<mxp-wms:Abstract>The capitals for the United
States.</mxp-wms:Abstract>
<mxp-wms:SRSNameSet/>
<mxp-wms:WmsStyleSet/>
<FeatureLayer id="id10" name="STATECAP" alias="STATECAP" volatile="unknown" xmlns="http://www.mapinfo.com/mxp">
<DataSourceRef ref="id3"/>
</FeatureLayer>
</mxp-wms:WmsLayer>
</mxp-wms:WmsLayerList>
</mxp-wms:WmsLayer>
<mxp-wms:WmsLayer queryable="false">
<mxp-wms:Name>Canada</mxp-wms:Name>
<mxp-wms:Title>Canada</mxp-wms:Title>
<mxp-wms:Abstract>Contains layers for
Canada</mxp-wms:Abstract>
<mxp-wms:SRSNameSet/>
<mxp-wms:WmsStyleSet/>
<mxp-wms:WmsLayerList>
<mxp-wms:WmsLayer>
<mxp-wms:Name>CanadaHighway</mxp-wms:Name>
<mxp-wms:Title>Canada Highway</mxp-wms:Title>
<mxp-wms:Abstract>The major highways in Canada
</mxp-wms:Abstract>
<mxp-wms:SRSNameSet/>
<mxp-wms:WmsStyleSet>
<mxp-wms:WmsStyle>
<mxp-wms:Name>ThickGreenLine</mxp-wms:Name>
<mxp-wms:Title>Thick Green Line
</mxp-wms:Title>
<mxp-wms:Abstract>A thick, green line style.</mxp-wms:Abstract>
<!-- The following defines a black line style -->
<LineStyle stroke="black" width="1" width-unit="mapinfo:imagesize pixel" xmlns="http://www.mapinfo.com/mxp">
<Pen>mapinfo:pen 2</Pen>
</LineStyle>
</mxp-wms:WmsStyle>
</mxp-wms:WmsStyleSet>
<FeatureLayer id="id11" name="CANHIWAY" alias="CANHIWAY" volatile="unknown" xmlns="http://www.mapinfo.com/mxp">
<DataSourceRef ref="id4"/>
</FeatureLayer>
</mxp-wms:WmsLayer>
</mxp-wms:WmsLayerList>
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
319
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix F: Web Map Server Example
</mxp-wms:WmsLayer>
<mxp-wms:WmsLayer>
<mxp-wms:Name>Oceans</mxp-wms:Name>
<mxp-wms:Title>Oceans</mxp-wms:Title>
<mxp-wms:Abstract>The oceans of the world
</mxp-wms:Abstract>
<mxp-wms:SRSNameSet/>
<mxp-wms:WmsStyleSet/>
<mxp:FeatureLayer id="id12" name="OCEAN" alias="OCEAN" volatile="unknown">
<mxp:DataSourceRef ref="id5"/>
</mxp:FeatureLayer>
</mxp-wms:WmsLayer>
<mxp-wms:WmsLayer>
<mxp-wms:Name>Asia</mxp-wms:Name>
<mxp-wms:Title>Asia</mxp-wms:Title>
<mxp-wms:SRSNameSet/>
<mxp-wms:WmsStyleSet/>
<FeatureLayer id="id13" name="ASIA" alias="ASIA" volatile="unknown" xmlns="http://www.mapinfo.com/mxp">
<DataSourceRef ref="id6"/>
</FeatureLayer>
</mxp-wms:WmsLayer>
</mxp-wms:WmsLayerList>
</mxp-wms:WmsLayer>
</WmsConfig>
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
320
MapXtreme2004_DevGuide_A4.pdf
Elements of a
Coordinate System
G
In this appendix:
!
!
!
!
For More Information on Coordinate Systems and Projections. . . . . . . . . . . . . . . . 335
!
Developer Guide
Projections and Their Parameters
Appendix G: Elements of a Coordinate System
The following table indicates the parameters applicable to each projection, which are listed in the order they appear in the relevant coordinate system lines in the
MapInfoCoordinateSystemSet.xml. The document is located in C:\Program Files\Common
Files\MapInfo\MapXtreme\6.0.
Albers Equal-Area Conic
Azimuthal Equidistant
Cassini-Soldner
Cylindrical Equal Area
Double Stereographic
Eckert IV
Eckert VI
Equidistant Conic
Gall
Hotine Oblique Mercator
Lambert Azimuthal Equal-Area
Lambert Conformal Conic
Longitude-Latitude
Mercator
Miller
Mollweide
New Zealand Map Grid
Polyconic
Regional Mercator
Robinson
Sinusoidal
Stereographic
Swiss Oblique Mercator
Transverse Mercator
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
322
X X X X
X X X X
X X X X
X X X
X X X X
X X X
X X X
X X X X
X X X
X X X X
X X X X
X X X X
X
X X X
X X X
X X X
X X X X
X X X X
X X X
X X X
X X X
X X X X
X X X X
X X X X
X X
X
X X
X X
X
X
X X X X
X
X
X
X
X
X
X
X
X
X
X
X
X
X
X
X
X
X
X
X
X
X
X
X
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix G: Elements of a Coordinate System
Projection
The projection is the equation or equations used by a coordinate system. The following list names the projections MapInfo uses and gives the number used to identify the projection in the
MapInfoCoordinateSystemSet.xml file:
18
27
26
12
1
10
11
13
16
20
25
8
21
4
29
3
19
15
6
17
7
30
2
31
14
Number
9
28
5
Projection
Albers Equal-Area Conic
Azimuthal Equidistant (all origin latitudes)
Azimuthal Equidistant (polar aspect only)
Cassini-Soldner
Cylindrical Equal-Area
Double Stereographic
Eckert IV
Eckert VI
Equidistant Conic, also known as Simple Conic
Gall
Hotine Oblique Mercator
Lambert Azimuthal Equal-Area (polar aspect only)
Lambert Azimuthal Equal-Area
Lambert Conformal Conic
Lambert Conformal Conic (modified for Belgium 1972)
Longitude/Latitude
Mercator
Miller Cylindrical
Mollweide
New Zealand Map Grid
Polyconic
Regional Mercator
Robinson
Sinusoidal
Stereographic
Swiss Oblique Mercator
Transverse Mercator, (also known as Gauss-Kruger)
Transverse Mercator, (modified for Danish System 34 Jylland-Fyn)
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
323
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix G: Elements of a Coordinate System
Number
22
23
24
Projection
Transverse Mercator, (modified for Danish System 34 Sjaelland)
Transverse Mercator, (modified for Danish System 34/45 Bornholm)
Transverse Mercator, (modified for Finnish KKJ)
For example, a Longitude/Latitude projection is listed in the MapInfoCoordinateSystemSet.xml as:
<GeographicCRS>
<srsName>Longitude / Latitude (Porto Santo 1936)</srsName>
<srsID>
<code>coordsys 1,94</code>
<codeSpace>mapinfo</codeSpace>
<remarks>Longitude / Latitude (v 6.0 and later projections)</ remarks>
</srsID>
<usesEllipsoidalCS/>
<usesGeodeticDatum/>
</GeographicCRS>
Projection numbers in the MapInfoCoordinateSystemSet.xml may be modified by the addition of a constant value to the base number listed in the Projection table, above. Valid values and their meanings are tabulated below:
Constant
1000
2000
3000
Meaning
System has affine transformations
Parameters
Affine units specifier and coefficients appear after the regular parameters for the system.
System has explicit bounds Bounds appear after the regular parameters for the system.
System with both affine and bounds Affine parameters follow system’s parameters; bounds follow affine parameters.
Example:
Assume you want to work with a simple system based on the Transverse Mercator projection and using the NAD 1983 datum. You might have a line such as the following in your
MapInfoCoordinateSystemSet.xml file:
<ProjectedCRS>
<srsName>UTM Zone 1 (NAD 83)</srsName>
<srsID>
<code>coordsys 8,33,7,-177,0,0.9996,500000,0</code>
<codeSpace>mapinfo</codeSpace>
<remarks>Universal Transverse Mercator </remarks>
</srsID>
<baseCRS/>
<definedByConversion/>
<usesCartesianCS/>
</ProjectedCRS>
Now let’s say that you want a system based on this, but with an affine transformation specified by the following parameters:
Units=meters; A=0.5; B=-0.866; C=0; D=0.866; E=0.5; and F=0.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
324
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix G: Elements of a Coordinate System
The required line in the MapInfoCoordinateSystemSet.xml file is:
<ProjectedCRS>
<srsName>UTM Zone 1 (NAD 83)- rotated 60 degrees</srsName>
<srsID>
<code>coordsys 8,33,7,-177,0,0.9996,500000,0, 7, 0.5, -
0.866, 0, 0.866, 0.5, 0 </code>
<codeSpace>mapinfo</codeSpace>
<remarks>Universal Transverse Mercator</remarks>
</srsID>
<baseCRS/>
<definedByConversion/>
<usesCartesianCS/>
</ProjectedCRS>
Alternatively, if you want to bound the system to (x1, y1, x2, y2)=(-500000, 0, 500000,
1000000), the required line is:
<ProjectedCRS>
<srsName>UTM Zone 1 (NAD 83)- bounded</srsName>
<srsID>
<code>coordsys 8,33,7,-177,0,0.9996,500000,0, -500000, 0,
</code>
500000, 1000000
<codeSpace>mapinfo</codeSpace>
<remarks>Universal Transverse Mercator </remarks>
</srsID>
<baseCRS/>
<definedByConversion/>
<usesCartesianCS/>
</ProjectedCRS>
To customize the system using both of these modifications, the line is:
<ProjectedCRS>
<srsName>UTM Zone 1 (NAD 83)</srsName>
<srsID>
<code>coordsys 8,33,7,-177,0,0.9996,500000,0, 7, 0.5, -
0.866, 0, 0.866, 0.5, 0, -500000, 0, 500000,
1000000 </code>
<codeSpace>mapinfo</codeSpace>
<remarks>Universal Transverse Mercator </remarks>
</srsID>
<baseCRS/>
<definedByConversion/>
<usesCartesianCS/>
</ProjectedCRS>
Projection Datums
The datum is established by tying a reference ellipsoid to a particular point on the earth. The following table lists these details for each datum:
•
The number used to identify the datum in the MapInfoCoordinateSystemSet.xml file.
•
The datum’s name
•
The maps for which the datum is typically used
•
The datum’s reference ellipsoid
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
325
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
9
8
6
7
10
11
151
118
4
119
5
1008
1009
1006
3
1
Number
2
1007
12
13
1006
1007
1008
1009
151
120
Adindan
Afgooye
AGD 66, 7 parameter
AGD 66, 7 parameter
AGD 66, 7 parameter
AGD 84, 7 parameter
Ain el Abd 1970
American Samoa
Anna 1 Astro 1965
Antigua Island Astro 1943
Arc 1950
Datum Area Maps
Ethiopia, Mali, Senegal, Sudan
Somalia
Australia, A.C.T.
Australia, Tasmania
Australia, Victoria/NSW
Australia
Bahrain Island
American Samoa Islands
Cocos Islands
Antigua, Leeward Islands
Botswana, Lesotho, Malawi,
Swaziland, Zaire, Zambia,
Zimbabwe
Arc 1960
Ascension Island 1958
Astro B4 Sorol Atoll
Astro Beacon “E”
Astro DOS 71/4
Astronomic Station 1952
ATS77 (Average Terrestrial
System 1977)
Australian Geodetic 1966
(AGD 66 - 3 param)
Kenya, Tanzania
Ascension Island
Tern Island
Iwo Jima Island
St. Helena Island
Marcus Island
Canada
Australia and Tasmania Island
Australian Geodetic 1984
(AGD 84 - 3 param)
Australia and Tasmania Island
Australia-National-AGD84 7 param
Australia
Australia (A.C.T. AGD66 7param)
Australia
Australia (Tasmania AGD66
7-param)
Tasmania
Victoria, NSW Australia (Victoria/NSW
AGD66 7-param)
Average Terrestrial System
1977 (ATS77)
Ayabelle Lighthouse Djibouti
Appendix G: Elements of a Coordinate System
Ellipsoid
Clarke 1880
Krassovsky
Australian National
Australian National
Australian National
Australian National
International
Clarke 1866
Australian National
Clarke 1880
Clarke 1880
Clarke 1880
Clarke 1880
International
International
International
International
International
ATS77
Australian National
Australian National
Australian National
Australian National
Australian National
Australian National
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
326
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix G: Elements of a Coordinate System
24
123
124
1000
25
26
27
115
28
108
125
30
116
17
18
19
20
1005
21
22
23
122
Number
110
14
15
16
121
29
Belgium
Datum
Bellevue (IGN)
Bermuda 1957
Belgium
Area Maps
Efate and Erromango Islands
Bermuda Islands
Ellipsoid
International
International
Clarke 1866
International
Bessel 1841
Bogota Observatory
Bukit Rimpah
Colombia
Bangka and Belitung Islands
(Indonesia)
Argentina Campo Inchauspe
Canton Astro 1966
Cape
Cape Canaveral
Cape, 7 parameter
Carthage
Chatham 1971
Phoenix Islands
South Africa
Florida and Bahama Islands
South Africa
Tunisia
Chatham Island (New Zealand)
Chua Astro Paraguay
Co-Ordinate System 1937 of
Estonia
Estonia
Corrego Alegre Brazil
Dabola
Deception Island
Guinea
Deception Island, Antarctica
Deutsches Hauptdreicksnetz
(DHDN)
Germany
Djakarta (Batavia)
DOS 1968
Easter Island 1967
EUREF 89
European 1950 (ED 50)
Sumatra Island (Indonesia)
Gizo Island (New Georgia Islands)
Easter Island
Europe
International
Clarke 1880
Clarke 1880
Bessel
Bessel 1841
International
International
GRS 80
European 1979 (ED 79)
European 1987 (ED 87)
Fort Thomas 1955
Gandajika Base
GDA 94
Austria, Belgium, Denmark, Finland, France, Germany, Gibraltar,
Greece, Italy, Luxembourg, Netherlands, Norway, Portugal, Spain,
Sweden, Switzerland
Austria, Finland, Netherlands, Norway, Spain, Sweden, Switzerland
Europe
International
International
Nevis, St. Kitts, Leeward Islands
Republic of Maldives
Australia
International
Clarke 1880
International
GRS 80
International
International
Clarke 1880
Clarke 1866
WGS 84
Clarke 1880
International
International
Bessel 1841
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
327
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Number
32
33
126
Datum
Geodetic Reference System 1967 (GRS 67)
Geodetic Reference System 1980 (GRS 80)
Graciosa Base SW 1948
34
35
150
127
128
42
134
43
152
130
131
132
133
39
40
41
129
36
37
38
1004
44
45
46
47
Worldwide
Worldwide
Appendix G: Elements of a Coordinate System
Area Maps Ellipsoid
GRS 67
GRS 80
Guam 1963
GUX 1 Astro
Hartbeesthoek 94
Herat North
Hermannskogel
Hito XVIII 1963
Hjorsey 1955
Hong Kong 1963
Hungarian Datum (HD 72)
Hu-Tzu-Shan
Indian
Indian
Indian
Indian 1954
Indian 1960
Indian 1975
Indonesian 1974
Ireland 1965
ISTS 061 Astro 1968
ISTS 073 Astro 1969
Japanese Geodetic Datum
2000 (JGD2000)
Johnston Island 1961
Kandawala
Kerguelen Island
Kertau 1948
Johnston Island
Sri Lanka
Kerguelen Island
West Malaysia and Singapore
Faial, Graciosa, Pico, Sao Jorge, and Terceira Islands (Azores)
Guam Island
Guadalcanal Island
South Africa
International 1924
Clarke 1866
International
WGS 84
Afghanistan International 1924
Yugoslavia (Prior to 1990), Slovenia, Croatia, Bosnia and Herzegovina, Serbia
Bessel 1841
South Chile (near 53×S)
Iceland
Hong Kong
Hungary
Taiwan
Thailand and Vietnam
Bangladesh, India, Nepal
Pakistan
International
International
International
GRS 67
International
Everest (India 1830)
Everest (India 1830)
Everest (Pakistan)
Thailand
Vietnam
Thailand
Indonesia
Ireland
South Georgia Island
Diego Garcia
Japan
Everest (India 1830)
Everest (India 1830)
Everest (India 1830)
Indonesian 1974
Modified Airy
International 1924
International
GRS80
International
Everest (India 1830)
International
Everest (W. Malaysia and Singapore
1948)
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
328
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Number
135
48
136
49
113
50
51
52
53
54
114
55
56
57
137
138
58
59
60
61
109
31
1010
62
63
64
65
Datum
Kusaie Astro 1951
L.C. 5 Astro
Leigon
Liberia 1964
Lisboa (DLx)
Luzon
Luzon
Mahe 1971
Marco Astro
Massawa
Melrica 1973 (D73)
Merchich
Midway Astro 1961
Minna
Montserrat Island Astro
1958
M’Poraloko
Nahrwan
Nahrwan
Nahrwan
Naparima, BWI
Netherlands
New Zealand Geodetic
Datum 1949 (NZGD 49)
(New Zealand (NZGD49 7parameter)
North American 1927
(NAD 27)
North American 1927
(NAD 27)
North American 1927
(NAD 27)
North American 1927
(NAD 27)
Mahe Island
Morocco
Midway Island
New Zealand
Alaska
Appendix G: Elements of a Coordinate System
Area Maps Ellipsoid
Caroline Islands, Federated States of Micronesia
International 1924
Cayman Brac Island Clarke 1866
Ghana
Liberia
Portugal
Philippines (excluding Mindanao
Island)
Mindanao Island
Clarke 1880
Clarke 1880
International
Clarke 1866
Salvage Islands
Eritrea (Ethiopia)
Portugal
Nigeria
Montserrat, Leeward Islands
Gabon
Masirah Island (Oman)
United Arab Emirates
Saudi Arabia
Trinidad and Tobago
Netherlands
New Zealand
Continental US
Bahamas (excluding San Salvador Island)
San Salvador Island
Clarke 1866
Clarke 1880
International
Bessel 1841
International
Clarke 1880
International
Clarke 1880
Clarke 1880
Clarke 1880
Clarke 1880
Clarke 1880
Clarke 1880
International
Bessel
International
International
Clarke 1866
Clarke 1866
Clarke 1866
Clarke 1866
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
329
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix G: Elements of a Coordinate System
111
117
1010
75
140
76
77
97
78
79
Number
66
67
68
69
70
71
72
73
74
139
107
1002
80
Datum
North American 1927
(NAD 27)
North American 1927
(NAD 27)
North American 1927
(NAD 27)
North American 1927
(NAD 27)
Area Maps
Canada (including Newfoundland
Island)
Canal Zone
Caribbean (Turks and Caicos
Islands)
Central America (Belize, Costa
Rica, El Salvador, Guatemala,
Honduras, Nicaragua)
Cuba
Ellipsoid
Clarke 1866
Clarke 1866
Clarke 1866
Clarke 1866
North American 1927
(NAD 27)
North American 1927
(NAD 27)
Greenland (Hayes Peninsula)
Clarke 1866
Clarke 1866
North American 1927
(NAD 27)
North American 1927
(NAD 27)
North American 1983
(NAD 83)
North Sahara 1959
Mexico Clarke 1866
Michigan (used only for State
Plane
Coordinate System 1927)
Alaska, Canada, Central America,
Continental US, Mexico
Algeria
Modified Clarke
1866
GRS 80
Clarke 1880
Modified Clarke
1880
Nouvelle Triangulation
Francaise (NTF) Greenwich
Prime Meridian
France
Nouvelle Triangulation
Francaise (NTF) Paris Prime
Meridian
France Modified Clarke
1880
NWGL 10
NZGD 2000
NZGD 49, 7 parameter
Observatorio 1966
Worldwide
New Zealand
New Zealand
Corvo and Flores Islands (Azores)
WGS 72
GRS 80
International
International
Observatorio Meteorologico
1939
Corvo and Flores Islands (Azores) International 1924
Old Egyptian
Old Hawaiian
OldTokyo
Oman
Ordnance Survey of Great
Britain 1936
Pico de las Nieves
Egypt
Hawaii
Japan, Korea, Okinawa
Oman
England, Isle of Man, Scotland,
Shetland Islands, Wales
Canary Islands
Helmert 1906
Clarke 1866
Bessel 1841
Clarke 1880
Airy
International
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
330
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix G: Elements of a Coordinate System
87
88
89
85
1000
86
112
83
1001
1012
84
144
145
146
1013
1024
92
Number
81
141
142
143
1000
82
36
1011
90
91
Datum
Pitcairn Astro 1967
Point 58
Pointe Noire 1948
Porto Santo 1936
Potsdam
Area Maps
Pitcairn Island
Burkina Faso and Niger
Congo
Porto Santo and Madeiras Islands
Germany
Ellipsoid
International
Clarke 1880
Clarke 1880
International 1924
Bessel
Provisional South American
1956
Provisional South Chilean
1963
Bolivia, Chile, Colombia, Ecuador,
Guyana, Peru, Venezuela
South Chile (near 53×S)
International
International
Puerto Rico
Pulkovo 1942
PZ90
Qatar National
Qornoq
Rauenberg
Reunion
Rikets Triangulering 1990
(RT 90)
Rikets Triangulering 1990
(RT 90), 7 parameter
Rome 1940
Santo (DOS)
São Braz
Sapper Hill 1943
Schwarzeck
Puerto Rico and Virgin Islands
Germany
Russia
Qatar
South Greenland
Germany
Mascarene Island
Sweden
Sweden
Sardinia Island
Espirito Santo Island
São Miguel, Santa Maria Islands
(Azores)
East Falkland Island
Namibia
Clarke 1866
Krassovsky
PZ90
International
International
Bessel
International
Bessel
Bessel
International
International
International
Selvagem Grande 1938
Sierra Leone 1960
S-JTSK
SK42
SK95
South American 1969
Salvage Islands
Sierra Leone
Czech Republic
Russia
Russia
Argentina, Bolivia, Brazil, Chile,
Colombia, Ecuador, Guyana,
Paraguay, Peru, Venezuela,
Trinidad, and Tobago
International
Modified Bessel
1841
International 1924
Clarke 1880
Bessel 1841
PZ90
PZ90
South American
1969
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
331
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Number
93 South Asia
Datum
94
95
1003
147
96
Southeast Base
Southwest Base
Switzerland (CH 1903)
Tananarive Observatory
1925
Timbalai 1948
1015
98
99
148
149
100
101
102
103
104
105
106
Tokyo
Tristan Astro 1968
Viti Levu 1916
Voirol 1874
Voirol 1960
Wake-Eniwetok 1960
World Geodetic System
1960 (WGS 60)
World Geodetic System
1966 (WGS 66)
World Geodetic System
1972 (WGS 72)
World Geodetic System
1984 (WGS 84)
Yacare
Zanderij
Singapore
Appendix G: Elements of a Coordinate System
Area Maps
Porto Santo and Madeira Islands
Faial, Graciosa, Pico, Sao Jorge,
Terceira Islands (Azores)
Switzerland
Madagascar
Ellipsoid
Modified Fischer
1960
International
International
Bessel
International 1924
Brunei and East Malaysia
(Sarawak and Sabah)
Japan
Tristan da Cunha
Viti Levu Island (Fiji Islands)
Tunisia/Algeria
Algeria
Marshall Islands
Worldwide
Everest (India 1830)
Bessel 1841
International
Clarke 1880
Clarke 1880
Clarke 1880
Hough
WGS 60
Worldwide
Worldwide
Worldwide
Uruguay
Surinam
WGS 66
WGS 72
WGS 84
International
International
Units
The following table lists the available coordinate units and the number used to identify the unit in the MapInfoCoordinateSystemSet.xml file:
2
1
6
31
3
Number
Centimeters
Chains
Feet (also called International Feet)
*
Inches
Kilometers
Units
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
332
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix G: Elements of a Coordinate System
5
9
7
0
30
Number Units
32
8
Links
Meters
Miles
Millimeters
Nautical Miles
†
Rods
US Survey Feet (used for 1927 State Plane)
‡
4 Yards
* One International Foot equals exactly 30.48 cm.
† One Nautical Mile equals exactly 1852 meters.
‡ One US Survey Foot equals exactly 12/39.37 meters, or approximately 30.48006 cm.
Coordinate System Origin
The origin is the point specified in longitude and latitude from which all coordinates are referenced. It is chosen to optimize the accuracy of a particular coordinate system. As we move north from the origin, Y increases. X increases as we move east. These coordinate values are generally called northings and eastings.
For the Transverse Mercator projection the origin’s longitude defines the central meridian. In constructing the Transverse Mercator projection a cylinder is positioned tangent to the earth.
The central meridian is the line of tangency. The scale of the projected map is true along the central meridian.
In creating a Hotine Oblique Mercator projection it is necessary to specify a great circle that is not the equator nor a meridian. MapInfo does this by specifying one point on the ellipsoid and an azimuth from that point. That point is the origin of the coordinate system.
Standard Parallels (Conic Projections)
In conic projections a cone is passed through the earth intersecting it along two parallels of latitude. These are the standard parallels. One is to the north and one is to the south of the projection zone. To use a single standard parallel specify that latitude twice. Both are expressed in degrees of latitude.
Oblique Azimuth (Hotine Oblique Mercator)
When specifying a great circle (Hotine Oblique Mercator) using a point and an azimuth (arc), the azimuth is called the Oblique Azimuth and is expressed in degrees.
Scale Factor (Transverse Mercator)
A scale factor is applied to cylindrical coordinates to average scale error over the central area of the map while reducing the error along the east and west boundaries. The scale factor has the effect of recessing the cylinder into the earth so that it has two lines of intersection. Scale is true along these lines of intersection.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
333
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix G: Elements of a Coordinate System
You may see the scale factor expressed as a ratio, such as 1:25000. In this case it is generally called the scale reduction. The relationship between scale factor and scale reduction is: scale factor = 1-scale reduction
In this case the scale factor would be 1-(1/25000) or 0.99996.
False Northings and False Eastings
Calculating coordinates is easier if negative numbers aren’t involved. To eliminate this problem in calculating State Plane and Universal Transverse Mercator coordinates, it is common to add measurement offsets to the northings and eastings. These offsets are called False Northings and False Eastings. They are expressed in coordinate units, not degrees. (The coordinate units are specified by the Units parameter.)
Range (Azimuthal Projections)
The range specifies, in degrees, how much of the earth you are seeing. The range can be between 1 and 180. When you specify 90, you see a hemisphere. When you specify 180 you see the whole earth, though much of it is very distorted.
Polyconic Projection
The following description is copied from Map Projections – A Working Manual, USGS
Professional Paper 1395, by John P. Snyder.
The Polyconic projection, usually called the American Polyconic in Europe, achieved its name because the curvature of the circular arc for each parallel on the map is the same as it would be following the unrolling of a cone which had been wrapped around the globe tangent to the particular parallel of latitude, with the parallel traced onto the cone. Thus, there are many
(“poly-”) cones involved, rather than the single cone of each regular conic projection.
The Polyconic projection is neither equal-area nor conformal. Along the central meridian, however, it is both distortion free and true to scale. Each parallel is true to scale, but the meridians are lengthened by various amounts to cross each parallel at the correct position along the parallel, so that no parallel is standard in the sense of having conformality (or correct angles), except at the central meridian. Near the central meridian, distortion is extremely small.
This projection is not intended for mapping large areas. The conversion algorithms used break down when mapping wide longitude ranges. For example, the sample table WORLD.TAB may exhibit anomalies if reprojected using Polyconic.
Datum Conversion
When converting coordinates from one datum to another, MapInfo has used the Molodensky
(3-parameter) and Bursa-Wolf (7-parameter) methods. These are general-purpose methods that can convert coordinates from any datum to any other datum.
After the NAD 83 datum was introduced, NOAA developed a program called NADCON, which stands for North American Datum CONversion. This is a very specialized program that converts coordinates only from NAD 27 to NAD 83 and vice versa. For this specialized task, it’s much more accurate than the Molodensky general-purpose method; NADCON is accurate to
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
334
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix G: Elements of a Coordinate System
about 0.1 meter, and Molodensky is accurate to only 10–30 meters. Most U.S. government agencies, including the Census Bureau, have standardized on NADCON for converting between NAD 27 and NAD 83.
Beginning with MapInfo 4.1.2, the NADCON algorithm is used to convert coordinates between
NAD 27 and NAD 83 if those coordinates lie within the areas covered by NADCON (United
States, Puerto Rico, and the Virgin Islands). If the coordinates lie outside those areas, or if they use datums other than NAD 27 or NAD 83, MapInfo uses the Molodensky or Bursa-Wolfe conversion methods.
Due to the file access required, the NADCON conversion method can be slightly slower than the Molodensky method. If you want to turn off the NADCON conversion, remove the *.las and
*.los files from the MapXtreme program or the MapXtreme Common directory.
For More Information on Coordinate Systems and Projections
The first three publications listed are relatively short pamphlets. The last two are substantial books. We’ve also given addresses and phone numbers for the American Congress of
Surveying and Mapping (the pamphlets) and the U.S. Geological Survey (the books).
•
American Cartographic Association. Choosing a World Map—Attributes, Distortions,
Classes, Aspects. Falls Church, VA: American Congress on Surveying and Mapping.
Special Publication No. 2. 1988.
•
American Cartographic Association. Matching the Map Projection the Need. Falls
Church, VA: American Congress on Surveying and Mapping. Special Publication No. 3.
1991.
•
American Cartographic Association. Which Map is Best? Projections for World Maps.
Falls Church, VA: American Congress on Surveying and Mapping. Special Publication
No. 1. 1986.
•
John P. Snyder. Map Projections—A Working Manual. Washington: U.S. Geological
Survey Professional Paper 1395. 1987
•
John P. Snyder and Philip M. Voxland. An Album of Map Projections. Washington: U.S.
Geological Survey Professional Paper 1453. 1989.
•
Contact Information
•
American Congress on Surveying and Mapping, 5410 Grosvenor Lane, Suite 100,
Bethesda, MD 20814 2212; (301) 493-0200
•
Earth Science Information Center, U.S. Geological Survey, 507 National Center,
Reston, VA 22092; (703) 860-6045 or (800) USA-MAPS
•
Peter H. Dana of the Department of Geography, University of Texas at Austin has also put up a website for explanations of Map projections, Geodetic Datums, and
Coordinate systems. It is a valuable as many of these explanations were also presented using MapInfo Professional. The materials may be used for study, research, and education, but please credit the author:
•
Peter H. Dana, The Geographer’s Craft Project, Department of Geography, The
University of Texas at Austin.
For Geodetic Datum information and explanations, go to:
http://www.colorado.edu/geography/gcraft/notes/datum/datum.html
For Information on Coordinate systems and other principles, go to:
http://www.colorado.edu/geography/gcraft/notes/coordsys/coordsys.html
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
335
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
For Information on Map Projections go to:
Appendix G: Elements of a Coordinate System http://www.colorado.edu/geography/gcraft/notes/mapproj/mapproj.html
Custom Datums
A datum is a mathematical description of the earth’s shape and orientation. Because the earth’s shape is not uniform, there are many different local datums used in different parts of the world. These local datums provide a close approximation to the earth’s surface in a particular area.
Each Earth coordinate system uses a specific datum to approximate the earth’s surface. If two coordinate systems use different datums, then MapInfo’s mapping products must perform a datum transformation when it converts coordinates from one coordinate system to the other.
MapInfo uses the Bursa-Wolfe datum transformation method, which is generally accurate to within 10 meters. (When the conversion is between two coordinate systems that use the same datum, no datum transformation is performed, and the results are generally accurate to within
0.1 meter.)
Defining Custom Datums
Most coordinate systems use one of MapInfo’s predefined datums, listed in this appendix. If you need to use a datum that isn’t in the list, and you know what the datum’s mathematical parameters are, then you can define the coordinate system using a custom datum. MapInfo uses the following information to define a datum:
•
An ellipsoid, also called a spheroid. This is an ellipse rotated around its minor axis to form a three-dimensional surface. The ellipsoid is described by two mathematical parameters: the length, in meters, of its semi-major axis (denoted by the letter a) and its degree of flattening (denoted by the letter f). MapInfo supports over 40 predefined ellipsoids, which are listed in the next table.
•
Three shift parameters specifying the distance, in meters, to shift the ellipsoid along each of its axes. These parameters are usually denoted by dX, dY, and dZ. You may also see them denoted by DX, DY, and DZ, or by u, v, and w.
•
Three rotation parameters specifying the angle, in arc-seconds, to rotate the ellipsoid around each of its axes. These parameters are usually denoted by EX, EY, and EZ.
You may also see them denoted by eX, eY, and eZ, or by e, y, and w.
•
A scale correction factor specifying the amount, in parts per million, to adjust the size of the ellipsoid. This parameter is denoted by the letter m, or sometimes k.
•
The longitude of the prime meridian, in degrees east of Greenwich. The prime meridian specifies which location on earth is assigned longitude 0×. Most datums use
Greenwich as the prime meridian, so this parameter is usually zero. However, some datums use a different location as the prime meridian. For example, the NTF datum uses Paris as its prime meridian, which is 2.33722917 degrees east of Greenwich. If you use the NTF datum in a coordinate system, all longitudes in that coordinate system are relative to Paris instead of Greenwich.
You can define a custom datum in any coordinate system definition. Use datum number 9999 followed by the datum parameters, in this order:
9999, EllipsoidNumber, dX, dY, dZ, EX, EY, EZ, m, PrimeMeridian
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
336
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix G: Elements of a Coordinate System
Some datums specify only an ellipsoid and shift parameters (dX, dY, dZ), with no rotation parameters, scale correction, or prime meridian. In those cases, you can use datum number
999 instead of 9999, to simplify the definition:
999, EllipsoidNumber, dX, dY, dZ
The ellipsoid number must be chosen from the following list. Currently, there is no way to define a custom ellipsoid. If you need to use an ellipsoid that does not appear on this list, please notify
MapInfo Technical Support so that we can add your ellipsoid to a future MapInfo release.
48
18
19
20
21
11
40
50
17
6
15
30
37
7
8
14
36
16
38
39
51
2
10
35
Number
9
13
Ellipsoid
Airy 1930
Airy 1930 (modified for Ireland 1965)
ATS7 77
Australian
Bessel 1841
Bessel 1841 (modified for NGO 1948)
Bessel 1841 (modified for Schwarzeck)
Clarke 1858
Clarke 1866
Clarke 1866 (modified for Michigan)
Clarke 1880
Clarke 1880 (modified for Arc 1950)
Clarke 1880 (modified for IGN)
Clarke 1880 (modified for Jamaica)
Clarke 1880 (modified for Merchich)
Clarke 1880 (modified for Palestine)
a
6377563.396
6377340.189
6378135.0
6378160.0
6377397.155
6377492.0176
6377483.865
6378293.639
6378206.4
6378450.047484481
6378249.145
6378249.145326
6378249.2
6378249.136
6378249.2
6378300.79
Everest (Brunei and East Malaysia (Sabah and
Sarawak))
6377298.556
1/f
299.3249646
299.3249646
298.257
298.25
299.1528128
299.15281
299.1528128
294.26068
294.9786982
294.9786982
293.465
293.4663076
293.4660213
293.46631
293.46598
293.46623
300.8017
Everest (India 1830)
Everest (India 1956)
Everest (Pakistan)
Everest (W. Malaysia and Singapore 1948)
Everest (West Malaysia 1969)
Fischer 1960
Fischer 1960 (modified for South Asia)
Fischer 1968
GRS 67
6377276.345
6377301.243
6377309.613
6377304.063
6377295.664
6378166.0
6378155.0
6378150.0
6378160.0
300.8017
300.80174
300.8017
300.8017
300.8017
298.3
298.3
298.3
298.247167427
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
337
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix G: Elements of a Coordinate System
24
12
47
34
44
45
46
52
25
26
27
1
32
33
43
42
41
4
49
3
Number
0 GRS 80
5
22
23
31
Hayford
Helmert 1906
Hough
IAG 75
Indonesian
International 1924
Irish (WOFO)
Krassovsky
MERIT 83
Ellipsoid
New International 1967
NWL 10D
NWL 9D
OSU86F
OSU91A
Plessis 1817
PZ90
South American
Sphere
Struve 1860
Walbeck
War Office
WGS 60
WGS 66
WGS 72
6378136.2
6378136.3
6376523.0
6378136.0
6378160.0
6370997.0
6378297.0
6376896.0
6378300.583
6378165.0
6378145.0
6378135.0
a
6378137.0
6378388.0
6378200.0
6378270.0
6378140.0
6378160.0
6378388.0
6377542.178
6378245.0
6378137.0
6378157.5
6378135.0
6378145.0
28 WGS 84 6378137.0
298.257223563
The shift and rotation parameters describe the ellipsoid’s orientation in space, as compared to the WGS 84 datum. It’s important to make sure that these parameters have the correct signs
(positive or negative). Usually, a document describing a local datum will list the parameters required to convert coordinates from the local datum to WGS 84. (This is the same as saying that the parameters were derived by subtracting the local datum from WGS 84.) In that case, you can use the parameters exactly as they appear in the document. However, if you have a document that lists parameters for converting coordinates in the opposite direction — from
WGS 84 to the local datum — then you must reverse the signs of the shift, rotation, and scale correction parameters.
298.25722
298.25722
308.64
298.257839303
298.25
0.0
294.73
302.78
296.0
298.3
298.25
298.26
298.247
297.0
299.325
298.3
298.257
298.25
298.26
298.25
1/f
298.257222101
297.0
298.3
297.0
298.257222
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
338
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix G: Elements of a Coordinate System
It’s also very important to list the parameters in the correct order. Some documents list the rotation parameters with EZ first, like this: EZ, EY, EX. In those cases, you must reverse the order of the rotation parameters when defining the custom datum. This is especially easy to overlook when your document uses Greek letters to denote the parameters. If the document lists the parameters in order as w, y, e, then you must reverse their order in the custom datum definition.
Here’s an example of a local datum description (we’ll call it LD-1) as it might appear in a technical article:
LD-2 ellipsoid: Krassovsky f a 6378245.0 m
1 / 298.3
Converting from LD-2 to WGS 84 e m w y u v w
+24 m
–123 m
–94 m
+0.13
+0.25
-0.02
+1.1 Þ 10-6
This datum uses the Krassovsky ellipsoid, which is number 3 in the ellipsoid table above. We do not need to reverse the signs of the parameters, since they describe a conversion from the local datum to WGS 84. However, the rotation parameters are listed with w first, so we must reverse their order in the custom datum definition:
9999, 3, 24, -123, -94, -0.02, 0.25, 0.13, 1.1, 0
Here’s a final example, LD-3, that provides only the ellipsoid and shift parameters:
LD-3 ellipsoid: Clarke 1880 f a 6378249.145 m
1 / 293.465
WGS 84 minus local datum LD-3 dX dY dZ
-7 m
36 m
225 m
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
339
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix G: Elements of a Coordinate System
This datum uses the Clarke 1880 ellipsoid, which is number 6 in the ellipsoid table above. We do not need to reverse the signs of the parameters or worry about the order of the rotation parameters (since they aren’t present). In this case, you can use datum number 999 instead of
9999 in the custom datum definition. These two definitions are equivalent, and you can use either one:
999, 6, -7, 36, 225
9999, 6, -7, 36, 225, 0, 0, 0, 0, 0
As with the other custom datum definitions, you would insert one of these definitions in place of the datum number in a MapInfoCoordinateSystemSet.xml line, as follows:
"Longitude / Latitude (LD-3)", 1, 999, 6, -7, 36, 225
<srsName>UTM Zone 30 (LD-3)</srsName>
- <srsID>
<code>coordsys 8, 999, 6, -7, 36, 225, 7, -3, 0, 0.9996, 500000, 0
</code>
<codeSpace>mapinfo</codeSpace>
<remarks>Universal Transverse Mercator (LD-3)</remarks>
</srsID>
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
340
MapXtreme2004_DevGuide_A4.pdf
Sample Data Copyrights
H
The following sources provided the data released with MapXtreme 2004. For more information on
MapInfo products, see the “MapInfo Data Products Catalog” or contact MapInfo Corporation.
Map Name
Argentina Cities
Argentina Country Boundary
Argentina Major Cities
South America Country Boundaries
World Ocean (Lat / Long)
Asia
Asia Capitals
Asia Major Cities
European Country Boundaries
World Ocean (for Asia)
Australia Cities
Australia Highways
Australia Major Cities
Australia State Boundaries
Australia State Capital Cities
World Ocean (Lat / Long)
Brazil Major Cities
Brazil Cities
Brazil Country Boundary
South America Country Boundaries
Copyright
Argentina Geoset
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo
Asia Geoset
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo 1998
MapInfo
Australia Geoset
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo
MapInfo from Digital Chart of the World
MapInfo
Brazil Geoset
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
Developer Guide
Map Name
World Ocean (Lat / Long)
Canada Cities
Canada Highways
Canada Major Cities
Canadian Province Boundaries
Canadian Province Capital Cities
US State Boundaries
World Ocean (Lat / Long)
Asia
Asia Major Cities
China Cities
China Country Bdy
China Highways
China Major Cities
World Ocean (for Asia)
Crime County Map
Crime Demo Map
Dallas City Boundary A
Dallas City Boundary B
Dallas Locations
Dallas Major Highways A
Dallas Major Highways B
Dallas Streets A
Dallas Streets B
Dallas Streets C
Dallas Water Bodies
Dallas Water Rivers
Dallas, TX Raster
Appendix H: Sample Data Copyrights
Copyright
MapInfo
Canada Geoset
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo
China Geoset
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo
Dallas, TX Geoset
MapInfo
MapInfo
MapInfo from USGS
MapInfo from USGS
MapInfo
MapInfo from USGS
MapInfo from USGS
MapInfo from USGS
MapInfo from USGS
MapInfo from USGS
MapInfo from USGS
MapInfo from USGS
Copyright © 1997, Horizons Technology, Inc.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
342
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Map Name
Dc Area Landmarks
Dc City Boundaries
DC Highways
DC Interstate Roads
DC Landmarks
DC Roads
DC State Roads
Dc Water Layer
DC Zips
Asia
European Capitals
European Cities
European Country Boundaries
European Highways
European Major Cities
World Ocean (Lat / Long)
European Country Boundaries
France Cities
France Highway Map
France Major Cities
World Ocean (Lat / Long)
European Country Boundaries
Germany Cities
Germany Highways
Germany Major Cities
World Ocean (Lat / Long)
Appendix H: Sample Data Copyrights
Copyright
DC Geoset
MapInfo
MapInfo
MapInfo from the Bureau of Transportation Statistics
MapInfo from the Bureau of Transportation Statistics
MapInfo
MapInfo from the Bureau of Transportation Statistics
MapInfo from the Bureau of Transportation Statistics
MapInfo
© 1995 Geographic Data Technology, Inc.
Europe Geoset
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo 1998
MapInfo 1998
MapInfo from Digital Chart of the World
MapInfo
France Geoset
MapInfo 1998
MapInfo from Digital Chart of the World
MapInfo 1998
MapInfo from Digital Chart of the World
MapInfo
Germany Geoset
MapInfo 1998
MapInfo from Digital Chart of the World
GisNET data licensed to MapInfo by GISdata Limited. © GDC Ltd. 1993
MapInfo from Digital Chart of the World
MapInfo
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
343
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
DC 1M Image
DC 3M Image
Map Name
Asia
India Capital Cities
India District Bdys
India Major Cities
India Minor Cities
India State Bdys
World Ocean (for Asia)
Africa Country Boundary
Asia
European Country Boundaries
Israel Cities
Israel Country Boundary
Israel Major Cities
World Ocean (Lat / Long)
European Country Boundaries
Italy Cities
Italy Highways
Italy Major Cities
World Ocean (Lat / Long)
Japan Cased Roads
Japan Cities
Appendix H: Sample Data Copyrights
Copyright
ImagePro Geoset
(c) MapInfo Corporation 2001. [Aerial Photography] used with permission of RSC Group, LLC 2001. All rights reserved.
(c) MapInfo Corporation 2001. [Aerial Photography] used with permission of RSC Group, LLC 2001. All rights reserved.
India Geoset
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
Risk Management Solutions, Inc.
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
Risk Management Solutions, Inc.
MapInfo
Israel Geoset
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo 1998
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo
Italy Geoset
MapInfo 1998
MapInfo from Digital Chart of the World
GisNET data licensed to MapInfo by GISdata Limited. © GDC Ltd. 1993
MapInfo from Digital Chart of the World
MapInfo
Japan Geoset
GisNET data licensed to MapInfo by GISdata Limited. © GDC Ltd. 1993
MapInfo from Digital Chart of the World
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
344
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Map Name
Japan Country background
Japan Highways
Japan Major Cities
Japan Rivers and Lakes
World Ocean (Lat / Long)
Mexico Cities
Mexico Highways
Mexico Major Cities
Mexico State Boundaries
Mexico State Capital Cities
US State Boundaries
World Ocean (Lat / Long)
Mid-Atlantic Capitals
Mid-Atlantic Cities
Mid-Atlantic Counties
Mid-Atlantic Highway
Mid-Atlantic Major Cities
Mid-Atlantic States
World Ocean (Lat / Long)
US State Boundaries
Canada Cities
Canada Highways
Canada Major Cities
Canadian Province Boundaries
Canadian Province Capital Cities
Mexico Cities
Mexico Highways
Appendix H: Sample Data Copyrights
Copyright
GisNET data licensed to MapInfo by GISdata Limited. © GDC Ltd. 1993
GisNET data licensed to MapInfo by GISdata Limited. © GDC Ltd. 1993
MapInfo from Digital Chart of the World
GisNET data licensed to MapInfo by GISdata Limited. © GDC Ltd. 1993
MapInfo
Mexico Geoset
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from the Bureau of Transportation Statistics
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo
Mid-Atlantic Geoset
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo
MapInfo from the Bureau of Transportation Statistics
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo
MapInfo from Digital Chart of the World
North American Geoset
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
345
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Map Name
Mexico Major Cities
Mexico State Boundaries
Mexico State Capital Cities
US Cities (Top 20)
US Cities
US County Boundaries
US Highways
US Major Cities
US State Boundaries
US State Capitals
US ZIP Codes
World Ocean (Lat / Long)
European Country Boundaries
Portugal Highways
Portugal Major Cities
World Ocean (Lat / Long)
Asia
South Korea Cities
South Korea Country Boundary
South Korea Major Cities
World Ocean (for Asia)
European Country Boundaries
Spain Cities
Spain Highways
Spain Major Cities
World Ocean (Lat / Long)
Appendix H: Sample Data Copyrights
Copyright
MapInfo from Digital Chart of the World
MapInfo from the Bureau of Transportation Statistics
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Census Bureau
MapInfo from the Bureau of Transportation Statistics
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
(c) 2001 Geographic Data Technology, Inc.
MapInfo
Portugal Geoset
MapInfo 1998
GisNET data licensed to MapInfo by GISdata Limited. © GDC Ltd. 1993
MapInfo from Digital Chart of the World
MapInfo
South Korea Geoset
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo
Spain Geoset
MapInfo 1998
MapInfo from Digital Chart of the World
GisNET data licensed to MapInfo by GISdata Limited. © GDC Ltd. 1993
MapInfo from Digital Chart of the World
MapInfo
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
346
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
StreetPro Austria
StreetPro Belgium
Map Name
StreetPro Denmark
DC ZIP codes GDT (dc_zips_G.tab)
StreetPro DC
StreetPro Deutschland
StreetPro Espana
StreetPro France
StreetPro Great Britain
StreetPro Italia
StreetPro Netherlands
StreetPro Norway
StreetPro Sweden
StreetPro Switzerland
European Country Boundaries
United Kingdom Cities
United Kingdom Class A Roads
United Kingdom Motorways
United Kingdom Standard Regions
World Ocean (Lat / Long)
Canadian Province Boundaries
Mexico State Boundaries
Appendix H: Sample Data Copyrights
Copyright
StreetPro Samples
2001 Tele Atlas B.V. 's-Hertogenbosch. All Rights
Reserved.
2001 Tele Atlas B.V. 's-Hertogenbosch. All Rights
Reserved.
2001 Tele Atlas B.V. 's-Hertogenbosch. All Rights
Reserved.
(c) 2001 Geographic Data Technology, Inc.
(c) 2001 Geographic Data Technology, Inc.
2001 Tele Atlas B.V. 's-Hertogenbosch. All Rights
Reserved.
2001 Tele Atlas B.V. 's-Hertogenbosch. All Rights
Reserved.
2001 Tele Atlas B.V. 's-Hertogenbosch. All Rights
Reserved.
2001 Tele Atlas B.V. 's-Hertogenbosch. All Rights
Reserved.
2001 Tele Atlas B.V. 's-Hertogenbosch. All Rights
Reserved.
2001 Tele Atlas B.V. 's-Hertogenbosch. All Rights
Reserved.
2001 Tele Atlas B.V. 's-Hertogenbosch. All Rights
Reserved.
2001 Tele Atlas B.V. 's-Hertogenbosch. All Rights
Reserved.
2001 Tele Atlas B.V. 's-Hertogenbosch. All Rights
Reserved.
UK Geoset
MapInfo 1998
MapInfo from Digital Chart of the World
GisNET data licensed to MapInfo by GISdata Limited. © GDC Ltd. 1993
GisNET data licensed to MapInfo by GISdata Limited. © GDC Ltd. 1993
Copyright URPI 1998
MapInfo
US Geoset
MapInfo from Digital Chart of the World
MapInfo from the Bureau of Transportation Statistics
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
347
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Map Name
US Cities
US County Boundaries
US Highways
US Major Cities
US State Boundaries
US State Capitals
US top 20 Cities
US ZIP Code Boundaries (Thinned)
US ZIPs
World Ocean (Lat / Long)
Canadian Province Boundaries
Landmark Map
Mexico State Boundaries
US Cities
US County Boundaries
US Highways
US Major Cities
US State Boundaries
US State Capitals
US top 20 Cities
US ZIP Code Boundaries
US ZIP Code Points
World Ocean (Lat / Long)
World Capitals
World Countries
World Graticule
World Ocean (Robinson)
World Top 25 Cities
Mgrs_100K
Mgrs_Nor_100K
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
348
Appendix H: Sample Data Copyrights
Copyright
MapInfo from Digital Chart of the World
MapInfo from Census Bureau
MapInfo from the Bureau of Transportation Statistics
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
(c) 2001 Geographic Data Technology, Inc.
(c) 2001 Geographic Data Technology, Inc.
MapInfo
US Detail Geoset
MapInfo from Digital Chart of the World
MapInfo from USGS
MapInfo from the Bureau of Transportation Statistics
MapInfo from Digital Chart of the World
MapInfo from Census Bureau
MapInfo from the Bureau of Transportation Statistics
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
© 2001Geographic Data Technology, Inc.
© 2001Geographic Data Technology, Inc.
MapInfo
World Geoset
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo
MapInfo
MapInfo from Digital Chart of the World
MapInfo
MapInfo
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix H: Sample Data Copyrights
Map Name Copyright
Mgrs_sou_100K
Mgrs_UPS_Nor
Mgrs_UPS_Sou
MGRS_Zones
MapInfo
MapInfo
MapInfo
World Capitals
World Countries
World Graticule
World Major Cities
World Minor Cities
World Ocean (Robinson)
World Top 25 Cities
MapInfo
World Detail Geoset
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo
MapInfo from Digital Chart of the World
MapInfo from Digital Chart of the World
MapInfo
MapInfo from Digital Chart of the World
Other Files
Dallas City Boundary from MapXsite Streets 1.0
MapInfo from USGS
Dallas Major Highways from MapXsite Streets
1.0
MapInfo from USGS
Dallas Streets from MapXsite Streets 1.0
MapInfo from USGS
Dallas Water Bodies from MapXsite Streets 1.0
MapInfo from USGS
Dallas Water Rivers from MapXsite Streets 1.0
MapInfo from USGS
US 5-Digit ZIP Code Points
US 5-Digit ZIP Code Points (compressed point file)
(c) 1999 Geographic Data Technology, Inc.
(c) 1995 Geographic Data Technology, Inc.
MapStats.mdb
Demographics for Asia
Demographics for Australia
Demographics for DC
Demographics for Mid-Atlantic States
Demographics for the World
Copyright United Nation Demographic Yearbook,
1994
MapInfo Australia
MapInfo Canada
MapInfo Canada
Copyright United Nation Demographic Yearbook,
1994
MapInfo Canada Demographics for US
DC Customer Database
US Customer Database
MapInfo
MapInfo
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
349
MapXtreme2004_DevGuide_A4.pdf
Glossary
I
This glossary defines terms used in this guide and in MapInfo products that are necessarily understandable or are used in a way specific to MapInfo products and technology.
Terms
Adornment
A map element that consists of either a legend, title, or scalebar.
Cartesian
A coordinate system using an x,y scale not tied to any real-world system. Most CAD drawing uses this method of registering objects (for example, a drawing of a ball-bearing assembly or a floor plan). If a drawing uses Cartesian coordinates, one corner of the drawing probably has coordinates 0, 0.
Cartesian Coordinates
The conventional representation of geometric objects by x and y values on a plane.
Centroid
Usually the center of a map object. For most map objects, the centroid is located at the middle of the object (the location halfway between the northern and southern extents and halfway between the eastern and western extents of the object). In some cases, the centroid is not at the middle point because there is a restriction that the centroid must be located on the object itself. Thus, in the case of a crescent-shaped region object, the middle point of the object may actually lie outside the limits of the region; however, the centroid is always within the limits of the region.
Character Encoding
A method of converting a sequence of bytes into a sequence of characters. See also
Character Set (UCS) on page 355
Unicode Transformation Format-8 (UTF-8) on page 355
Class
In an object-oriented language, a class is an object or a set of objects that contain(s) methods for performing some type of function, similar in meaning to a derived type in procedural languages.
Codespace
See
Developer Guide Appendix I: Glossary
Convex Hull Buffer
A type of buffer that creates a region object that represents a polygon based on the nodes from the input object. You can think of the convex hull polygon as an operator that places a rubber band around all of the points. It consists of the minimum number of points so that all points lie on or inside the polygon. With convex hull buffers, no interior angle can be greater than 180 degrees.
Coordinate
An x,y location in a Cartesian coordinate system, or a Latitude, Longitude location in an earth coordinate system. Coordinates represent locations on a map relative to other locations. Earth coordinate systems may use the equator and the Greenwich prime meridian as fixed reference points. Plane coordinate systems describe a two-dimensional x,y location in terms of distance from a fixed reference and are usually in the first quadrant so that all coordinates are positive numbers.
Coordinate System
A coordinate system is used to create a numerical representation of geometric objects. Each point in a geometric object is represented by a pair of numbers. Those numbers are the coordinates for that point. In cartography, coordinate systems are closely related to projections.
You create a coordinate system by supplying specific values for the parameters of a projection.
Data Binding
The association of a data source with a server control. The MapXtreme 2004 DataBinding class contains information about a single data-binding expression in an ASP.NET server control, which allows rapid-application development (RAD) designers in Visual Studio .NET to create data-binding expressions at design time.
Decimal Degree
The decimal representation of fractions of degrees. Many paper maps express coordinates in degrees, minutes, seconds (for example, 40_30i10I), where minutes and seconds are fractions of degrees. Thirty minutes equal half a degree, and 30 seconds equal half a minute.
MapXtreme 2004 expresses coordinates in decimal degrees (e.g., 72.558 degrees). Thus, the longitude: 40 degrees, 30 minutes, would be expressed in MapXtreme 2004 as 40.5 degrees.
Degrees Longitude, Degrees Latitude, Decimal Degrees
Degrees longitude and degrees latitude are coordinates used to represent locations on the surface of the earth. Longitude, or X-coordinate, represents a location's east-west position, where any location west of the prime meridian has a negative X value. Latitude, or Ycoordinate, represents a location's north-south position, where any location south of the equator has a negative Y value.
Derived Class
A class that contains all of the features of its base class but contains either additional functionality or enhanced functionality with respect to its base.
Enumerate
A type that contains all of the variables and their possible values.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
351
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix I: Glossary
Event Handler
An attribute for an object on a page that can be written in either JavaScript or VBScript. For example, an event handler describes what to do when a user clicks a button or selects text in a list box. Both VBScript and JavaScript support explicitly defined event handlers, for example, on Click and on Select. In addition, you can define functions that replace the explicit event handlers. Such functions are called implicit event handlers.
Feature
A row in a table that has geometry, style, and attributes. A Feature usually has a Table and Key to identify which row it represents.
FeatureLayer
A layer that displays Features from a Table. For example, a layer of region objects representing world countries is a FeatureLayer. A FeatureLayer must be added to a Map via the Map's Layer collection. FeatureLayers can be native .TAB data, remote RDB, seamless or raster data.
Geocode
The process of assigning X and Y coordinates to records in a table or database so that the records can be displayed as objects on a map.
GeoDictionary
A file that contains information about tables (TAB files only). The GeoDictionary is used to automatically determine the table to which application data should be bound.
GeoDictionaryManager
A tool for maintaining the Geodictionary.
Geographic Information System (GIS)
An organized collection of computer hardware and software designed to efficiently create, manipulate, analyze, and display all types of geographically or spatially referenced data.
Geometric Centroid
A centroid point (see
) that does not need to be contained within the
object (usually a FeatureGeometry).
Geography Markup Language (GML)
A markup language specific to mapping. The GML is being developed by the Open GIS
Consortium (OGC), an international organization that develops and promotes geographic standards.
Graticule
A grid of horizontal (latitude) and vertical (longitude) lines displayed on an earth map, spaced at a regular distance (for example, every five degrees, every fifteen degrees). Used to establish a frame of reference.
Hypertext Markup Language (HTML)
A plain text (Ascii) language that enables developers to create Web pages that can be displayed by different Web browsers on different computing platforms. Html uses tags to specify the structure of the various parts of a document. Html supports links (using URLs) that point to other web documents and files.
Hypertext Transfer Protocol (HTTP)
The message-based network interface between a Web client and a Web server. HTTP runs on top of TCP/IP.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
352
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix I: Glossary
Internet Information Services (IIS)
The software services provided by Microsoft that support the creation, configuration, and management of web sites. Specifically some comment Internet Information Services include:
FTP (File Transfer Protocol) and SMTP (Simple Mail Transfer Protocol). In MapXtreme 2004, the WMS Server we provide must be configured to work with IIS to run the Server.
ISession Interface
An Engine namespace interface that provides the starting point for all MapXtreme applications.
ISession manages the initialization of resources needed for a MapXtreme application, and defines all data and functionality applicable to an instance of an application.
Latitude
The horizontal lines on a map that increase from 0 degrees at the Equator to 90 degrees at both the North (+90.0 degrees) and South (-90.0 degrees) poles. Used to describe the northsouth position of a point as measured usually in degrees or decimal degrees above or below the equator.
Layer
A basic component of map display in MapInfo products, typically consisting of several superimposed layers (e.g., a layer of street data superimposed over a layer of county or postal code boundaries). When a table appears in a Map window, it occupies a layer in that Map window. Typically, each map layer corresponds to one open table.
Longitude
The vertical lines on a map, running from the North to South poles, used to describe the eastwest position of a point. The position is reported as the number of degrees east (to -180.0 degrees) or west (to +180.0 degrees) of the prime meridian (0 degrees). Lines of longitude are farthest apart at the Equator and intersect at both poles, and therefore, are not parallel.
Longitude/Latitude
The default coordinate system for representing geographic objects in a map in MapInfo products.
MapControl
A Windows.Controls namespace object that enables you to view a Map on a form. The
MapControl owns the window that the Map draws to. It also controls the size of the Map and interacts with the MapTools.
MapInfo Codespace
A list of definitions and standards that are commonly used in creating MapInfo maps and workspaces. The MapInfo Codespace includes coordinate system settings; pen, brush, and distance settings and abbreviations; image size settings; frequently used types and their abbreviations; a list of available operators; time, date, and temperature unit settings, and abbreviations. For details, see
Appendix E: Defining the MapInfo Codespace
.
Meridian
A line or a portion of a line running from the North to the South pole. A longitudinal line.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
353
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix I: Glossary
Namespace
A hierarchal naming system that provides a way to group classes together independently of inheritance. For example, two unrelated classes with the same name can exist in different namespaces: System.Utilities.FileFinder and MyCompany.Utilties.FileFinder could have the same name, but different functionality. Namespaces also help to prevent the compiler from referencing the wrong class (a 'collision').
Non-Earth Map
A map whose objects are not explicitly referenced to locations on the earth's surface. Floor plans are typical examples.
Persistence
Persistence refers to the way MapXtreme 2004 (and other MapInfo products) manages data and ensures that maps created using this API can be used by other MapXtreme users.
Persistence is concerned with loading and saving XML-based workspaces and for parsing and publishing MapInfo Geometry objects from/to GML, and vice versa.
PointRef Schema
A spatial schema that can be applied to a non-mappable table to make it mappable. The schema references a Geometry object in another table by matching the values in a column
(MatchColumn) of the non-mappable table with a column (RefColumn) in a mappable table.
When the table is opened, it contains a read-only Geometry column. The table can then be added to a Map as a layer.
Projection
A mathematical model that transforms the locations of features on the earth's surface to locations on a two-dimensional surface, such as a paper map. Since a map is an attempt to represent a spherical object (the earth) on a flat surface, all projections have some degree of distortion. A map projection can preserve area, distance, shape or direction but only a globe can preserve all of these attributes. Some projections (for example, Mercator) produce maps well suited for navigation. Other projections (for example, equal-area projections, such as
Lambert) produce maps well suited for visual analysis.
Spatial Schema
A service that can be applied to a table to enhance its spatial capabilities. There are two types of spatial schemas in MapXtreme 2004: PointRef and XY. Non-mappable tables that contain either a column that can be referenced to a column in a mappable table, or columns that represent XY values, can use these schemas to create a Geomtry column. These tables can then be added to a Map as a layer. See the PointRef Schema and XY Schema glossary definitions for information about each type of schema.
Table
A collection of data organized in row and column format. In MapXtreme 2004, tables contains the data you wish to display on the map. Tables hold information that describe the features, including their geometry, style, and attributes. MapXtreme 2004 supports tables from a wide variety of sources including, native tables (MapInfo .TAB), relational database management systems (RDBMS), dBase, MS Access, ASCII, and ESRI ShapeFiles. Speciality tables include raster, grid, seamless, views, WMS, and ADO.NET. The type of table is available through the
TableInfo class. Tables are opened and closed via the Catalog in the Data namespace. See
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
354
MapXtreme2004_DevGuide_A4.pdf
Developer Guide Appendix I: Glossary
Uniform Resource Locator (URL)
The underlying implementation of a hypertext link or image map that contains the address of a
Web page or file somewhere on the World Wide Web. A URL contains information about the network protocol to use (usually HTTP) and the path to the page or file. An URL example is
“http://www.mycompany.com/index.html,” which points to the index page for the “my company” web site.
Universal Character Set (UCS)
The international standard ISO 10646 defines the Universal Character Set (UCS). UCS is a superset of all other character set standards. UCS also defines several methods for encoding a string of characters as a sequence of bytes, such as UTF-8 and UTF-16.
Unicode Transformation Format-8 (UTF-8)
An octet (8-bit) lossless encoding of Unicode characters. MapXtreme 2004 supports UTF-8 only as indicated in the workspace persistence schema.
Web Map Service (WMS)
WMS is an OGC-compliant Web service that provides map images for use as layers in a mapping application. MapXtreme 2004 provides a server implementation of WMS if you wish to host a WMS server and a client for accessing any OGC-compliant (1.0.0, 1.1.0, or 1.1.1) WMS.
Web Feature Service (WFS)
An OGC-compliant Web service that offers geo-referenced map features for use in mapping applications. MapXtreme 2004 provides an implementation of WMS Basic, a read-only service and a client for accessing WMS servers.
Web server
A computer system that runs the Hypertext Transfer Protocol and Web Server software. A Web server accepts URL-based HTTP requests from a Web user's browser and sends HTML pages back to the browser. A Web server can manage one or many Web sites. A commercial server, for example, would typically have many Web sites.
Workspace
An XML-based persistence file format that allows users of MapXtreme 2004 to share maps they have created in a wide variety of environments. This is the file format that all future
MapInfo products will conform to. For more about creating workspaces, see
. For more about the structure of workspaces, see
Appendix C: Understanding the New MapInfo Workspace
.
XY Schema
A spatial schema that can be applied to a non-mappable to make it mappable. The table must contain X and Y coordinate values, which the schema accesses to create a Geometry column for the table.
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
355
MapXtreme2004_DevGuide_A4.pdf
Index
A
abbreviations file
editing
,
substitution methods
accessing data
IDBCommand
accessing non-mappable data
accessing remote tables
cache management
DBMS databases
–
mappable tables
–
ODBC connection string format
specifying styles
Acos function
add tools
adding geometry objects to a map
adding
dialog box to application
geometry objects to a map
grid image to a map
address candidates
address component accuracy
address numbers
matching to with Find
address ranges
addresses
matching to with Find
adornments
defined
map elements
ADRG
supported raster format
aggregation functions
application state
application templates
ASP.NET
MapForm
architecture
Ascii function
ASP.NET
formatters
serialization
sessionState
ASP.NET applications
creating without MapXtreme 2004 templates
optimizing
session management
using ASP.NET template
Web controls
ASRP
supported raster format
Atan function
attribute data
accessing
autolabels
B
bar themes
creating
BaseGeocodeMatchCode class
best match from multiple candidates matches
geocoding result codes
.bil files
supported raster format
BinaryFormatter
BitmapPointStyleRepository class
customizing
bitmaps
creating custom
.bmp files
supported raster format
Boolean expressions
brush styles
in remote spatial tables
buffers
selecting objects outside
selecting objects within
Developer Guide
C
cache management
accessing remote tables
remote tables
CADRG
supported raster format
CandidateAddress class
Cartesian coordinates
defined
cartographic legends
Catalog
search methods
Ceil function
centroid
defined
Char function
Char_Length function
character encoding
defined
CIB
supported raster format
circle tools
class
defined
close matches
codespace
defined
columns
adding expressions
supported data types
COM+ pooling
composite styles
conic projections
contacting technical support
conversion functions
convex hull buffer
defined
coordinate systems
defined
–
raster images
registering in CoordSysFactory object
coordinate units
coordinates
converting between NAD 27 and NAD 83
converting to another datum
defined
Cos function
Count function
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
357
CreateThemeWizard
Windows dialog boxes
–
creating
LineStrings
MapInfo Map Catalog
creating applications
in Visual Studio .NET
without templates
creating geometries
LineStrings
Points
rings
creating label themes
individual value
ranged
creating layers
creating maps
MapFactory
creating themes
graduated symbol
pie
ranged
creating workspaces
programmatically
via Workspace Manager
Current_Date function
Curves
creating
custom bitmaps
point styles
custom tools
customizing
GMLFeatureCollection
styles
UserDrawLayer
–
Windows tools
Index
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
D
data
loading
using in MapXtreme 2004
data access
deploying applications
expressions
GeoDictionary Manager
–
SQL commands
data binding
defined
registering tables in GeoDictionary
data functions
Data namespace
UML diagram
data sources
Data.Find namespace
UML diagram
Data.TableInfo
UML diagram
date format strings
–
DateToNumber function
DateToString function
datums
converting coordinates
defining custom
–
list of
projections
Day function
DBMS databases
accessing remote tables
importing spatial tables to
decimal degrees
defined
default styles
composite styles
–
degrees latitude
defined
degrees longitude
defined
Delete command
.dem files
deploying applications
,
derived class
defined
development framework support
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
358
dialog boxes
CreateThemeWizard
customizing
Distance tool
documentation set
dot density themes
creating
drawing circles
drawing ellipses
drawing lines
drawing points
custom bitmap styles
font point styles
drawing polylines
polyline tools
styles
drawing rectangles
drawing regions
interior styles
styles
drawing text
font styles
styles
DTED files
supported grid format
dynamic selection
E
ECW files
supported raster format
editing
LineStrings
ellipses
Engine namespace
exception classes
Engine.Session.State
enumerate
defined
event handler
defined
events
tool
exception classes
Engine namespace
exporting
maps to an image
Index
MapXtreme2004_DevGuide_A4.pdf
Developer Guide expressions
AddColumns
Boolean
creating
examples
feature search
label priority
MapInfo SQL definition
selecting objects outside buffer
selecting objects within buffer
thematic
F
False Eastings
False Northings
FeatureCollection
FeatureGeometry
FeatureLayer
defined
FeatureOverrideStyleModfier
customizing
FeatureOverrideStyleModifier
overriding styles
features
defined
FeatureGeometry
modifiers themes
FeatureStyleModifier
changing layer appearance
customizing
modifying style
UML diagram
file formats
grid images
raster images
fill styles
drawing regions
Find class
requirements
returned objects
sample application
finding map features
place names
street addresses
–
font point styles
drawing points with MapInfo.Styles.Font class
Index font styles
functions
MapInfo SQL supported
,
G
.gen files
supported raster format
geocode
defined
geocoded addresses
GeocodeMatchCode class
GeocodeRequest object
GeocodeResponse object
candidate addresses
geocoding
adding geocoding client to applications
address candidates
–
defined
displaying data on maps
–
geocoding client
defining object
Geocoding namespace
GeoDictionary
defined
defined
Geographic Information System (GIS)
defined
Geography Markup Language (GML)
defined
geometric centroid
defined
geometries
routes
geometry aggregation functions
–
geometry column
mappable tables
geometry constructor functions
geometry functions
geometry measurement functions
Geometry namespace
geometry objects
converting to FeatureGeometry objects
geometry observer functions
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
359
MapXtreme2004_DevGuide_A4.pdf
Developer Guide geometry predicate functions
geosets
MapLoader
GeoTIFF files
supported raster format
GIF files
supported raster format
–
–
GmlFeatureCollection class
customizing
graduated symbol themes
creating
graticule
defined
.grc files
supported raster format
.grd files
supported raster format
grid images
adding to a map
hillshade parameters
retrieving data from
group by
MapInfo SQL definition
GTOPO30 files
H
I
hillshading
grid parameter
Hotine Mercator projection
Oblique Azimuth
Hypertext Markup Language (HTML)
defined
Hypertext Transfer Protocol (HTTP)
defined
IGeocodeClient interface
defining geocoding client object
importing
features from XML files
individual value label themes
creating
individual value themes
creating
inflection
grid images
InfoTool
Insert command
installation
prerequisites
procedure
system requirements
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
360
installed bitmap images
accessing
installers
,
interior styles
BaseInterior class
drawing regions
SimpleInterior
InteriorStyleRepository class
customizing
Internet Information Services (IIS)
defined
IRouteClient interface
defining routing client object
ISearchResultProcessor interface
ISession interface
defined
session management
J
JPEG files
supported raster format
JPEG2000 files
supported raster format
K
Key
keywords
Mapinfow.abb file substitutions
L
LabelLayer
LabelModifier
LabelProperties
labels
individual value theme
mapping term description
priority expressions
styles
–
LabelSource
latitude
defined
layer
defined
layer override styles
layer types
FeatureLayer
GroupLayer
ObjectThemeLayer
UserDrawLayer
Index
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
LayerControl
creating custom tabs
customizing
web control
Windows control
Workspace Manager
LayerNodeHelper classes
customizing
Layers
UML diagram
layers
customizing appearance
types
layers, creating
UserDrawLayer class
Left function
LegendControl
web control
adornments
cartographic
line styles
BaseLineStyle class
drawing polylines
line tools
LineStrings
creating
LineStyleRepository class
customizing
loading data
for web application
MapLoader
longitude
defined
Longitude/Latitude
defined
M
M category matches
Manual
session management
map class
map contents
map legends
map title
adornments
map view
MapBasic SQL syntax
Index
MapControl
defined
web application planning
web controls
Windows control
MapExport
exporting to an image
MapFactory
creating maps
MapForm applications
using MapForm template
MapInfo 3.0 Compatible fonts
MapInfo 3.0 Compatible symbols
VectorySymbolRepository class
MapInfo ADO.NET Data Provider
data access
MICommand
MIConnection
MapInfo Codespace
defined
MapInfo Grid files
supported grid format
MapInfo Map Catalog
adding rows
creating
MapInfo SQL language
commands
number format strings
MapInfo Workspace format (.MWS)
MapInfoCoordinateSystemSet.xml file
projection
Mapinfow.abb file
editing
,
matching to street abbreviations
substitution keywords
–
MapLoader
loading data
MapMarker server
mappable tables
adding rows to Map Catalog
–
defining with server table queries
–
Mapping namespace
,
mapping terms and concepts
Mapping.Legends namespace
Mapping.Thematics namespace
–
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
361
MapXtreme2004_DevGuide_A4.pdf
Developer Guide maps
MapToolBar
Windows control
–
MapView
list of views
MapXtreme 2004
architecture overview
changed features
feature overview
migrating to
new features
object model
MapXtreme 2004 ASP.NET Web applications
using templates
MapXtreme 2004 Windows Map applications
using templates
matching data
automatching
–
Max function
merge modules
creating an installer
meridian
defined
metadata
TAB files
MI_AggregateConvexHull function
MI_AggregateEnvelope function
MI_AggregateIndividual function
MI_AggregateIntersection function
MI_AggregateUnion function
MI_Area function
MI_Box function
MI_Buffer function
MI_CentroidDistance function
MI_CentroidWithin function
MI_CentroidX function
MI_CentroidY function
MI_ContainsCentroid function
MI_ConvexHull function
MI_EngineVersion function
MI_Envelope function
MI_EnvelopesIntersect function
MI_Geometry column
MI_GeometryType function
MI_GridMinValue function
MI_GridValueAtPixel function
MI_ImagePixelHeight function
MI_ImagePixelWidth function
MI_Intersection function
MI_Intersects function
MI_Key column
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
362
MI_Length function
MI_MinX function
MI_MinY function
MI_Perimeter function
MI_Point function
MI_Style column
MI_Union function
MI_X function
MI_Y function
miAware 3.0 Location Utility
miAware 3.0 route web service
with routing client
MICommand
SQL statements
MIConnection
MapInfo ADO.NET data provider
Microsoft Data Access Components (MDAC)
MIDataReader
migrating to MapXtreme 2004
Min function
miscellaneous functions
MapInfo SQL functions
Mod function
modifier styles
modifier themes
dot density theme
individual value label theme
individual value theme
ranged
ranged label theme
modifying features
Month function
MrSID files
supported raster format
MSI installers
creating an installer
MultiPoint objects
.mws
creating
MapInfo Workspace format
MXTRunNCP.exe
N
NADCON
converting between NAD 27 and NAD 83
named connections
types
–
defined
NITF
supported raster format
Index
MapXtreme2004_DevGuide_A4.pdf
Developer Guide non-earth map
defined
non-match codes
North American Datum Conversion (NADCON)
number format strings
–
NumberToDate function
NumberToString function
numeric functions
O
object model
implementation differences
namespaces
object themes
–
graduated symbol
–
pie
Oblique Azimuth
Hotine Oblique Mercator projection
opening tables
Catalog
operating systems
operator precedence
operators
–
optimizing ASP.NET applications
Oracle applications
Oracle Spatial
connection dialog
geometry conversion
order by
MapInfo SQL definition
overriding styles
P
parameters
projections
PCX files
supported raster format
pen styles
per-record styles
persistence
defined
saving information
Persistence namespace
Photoshop files
supported raster format
pie themes
creating
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
363
Index
PNG files
supported raster format
point styles
in remote spatial tables
using birtmap images as
defined
points
creating
Polygons
creating
polylines
drawing styles
pooling
advantages
ASP.NET applications
configuring
postal centroid matches
geocoding result codes
product features
highlights
new
what’s changed
projections
datums
defined
MapInfoCoordinateSystemSet.xml
MapInfoCoordinateSystemSet.xml ID numbers
mapping term description
ProportionAvg function
ProportionSum function
ProportionWtAvg function
Q
queries
customizing with QueryDefinition class
QueryDefinition
customizing
QueryFilters
customizing
quoted identifiers
R
range
ranged label themes
creating
ranged themes
creating
–
–
MapXtreme2004_DevGuide_A4.pdf
Developer Guide raster images
adding to a map
coordinate systems
retrieving data from
Raster namespace
UML diagram
raster/grid functions
rectangle tools
drawing rectangles
refining boundary table
finding street addresses
relief shading
remote spatial tables
–
importing to a DBMS database
–
per-record styles
specifying styles
remote tables
accessing attribute data
cache management
mappable tables
–
ODBC connection string format
classes
–
result properties
Find matches
–
Right function
rings
creating
Round function
routing
adding routing client to applications
code example
defined
Routing namespace
UML diagram
RoutingJServer
Rtrim function
runtime installer
deploying applications
Index
S
S category matches
geocoding result codes
sample application
search
sample connection strings
sample data copyright information
scale factor
Transverse Mercator projection
scalebar
adornments
Search functions
customizing
searching for features
SearchInfoFactory
SearchResultProcessor class
customizing
Select command
select statement
MICommand
select tools
selecting points and regions
selecting objects
serializable classes
server table queries
defining mappable tables
–
server tables
caching data
session management
ISession interface
sessionState
shape tools
drawing geometric features
.sid files
supported raster format
Sign function
single close address matches
geocoding result codes
SOAPFormatter
spatial operators
spatial schemas
defined
PointRef
SpatialWare applications
troubleshooting
special characters
Mapinfow.abb file substitutions
Spot files
supported raster format
SQL query types
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
364
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
SQL statements
–
standard parallels
conic projections
state
persisting
state management
session
stock styles
default styles
street abbreviations
matching to with Find
street addresses
matching to with Find
street intersections
matching to with Find
street names
matching to with Find
string functions
StringToDate function
StringToNumber function
StyleRepository
StyleRepository classes
accessing predefined styles
styles
area
composite
creating custom bitmaps
customizing with repository classes
–
,
points
raster
stock
vector points
Workspace Manager
Styles namespace
UML diagram
substitutions
Mapinfow.abb file keywords
Substring function
Sum function
supported file formats
grid images
raster images
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
365
symbol styles
in remote spatial tables
T
TAB files
MapLoader
TableInfo
metadata
tables
adding expression columns
alias
Catalog
closing
columns
defined
events
mapping term description
MI_Style column
opening
packing
tables, creating
native
temporary native
Targa files
supported raster format
technical support, contacting
templates
ASP.NET
MapForm
text
drawing styles
theme legends
creating
themes
CreateThemeWizard
dot density theme
graduated symbol
individual value label theme
individual value theme
mapping term description
modifier
object
pie
ranged
ranged label theme
,
TIFF files
supported raster format
Index
MapXtreme2004_DevGuide_A4.pdf
Developer Guide tools
customizing
for desktop applications
Workspace Manager
Tools namespace
UML diagram
Transverse Mercator projection
Trim function
TrueType fonts
StyleRepository class
Trunc function
turn-by-turn directions
route instructions
U
UML diagram
Data namespace
Data.Find
Data.TableInfo
Geometry
Mapping.FeatureStyleModifier
Mapping.Labels
Mapping.Thematics.ModiferThemeBin
Raster
Routing
Styles
Unicode Transformation Format (UTF-8)
defined
Uniform Resource Locator (URL)
defined
Universal Character Set (UCS)
defined
Update command
Upper function
user-created installers
deploying applications
UserDrawLayer class
customizing
USGS DEM files
utilities
GeoDictionary Manager
Workspace Manager
V
VectorPointStyleRepository class
customizing
Vertical Mapper Classified Grid
supported raster format
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
366
Vertical Mapper Continuous Grid
supported grid format
supported raster format
view tools
changing map view
Views
MapView
Visual Basic .NET
–
development framework
Map application template
–
Visual Studio .NET
creating applications in
development framework
W
web application planning
creating an application
data loading
MapControl
serialization
steps in creating
workspace preloading
web controls
ASP.NET Web applications
LayerControl
LegendControl
MapControl
types
Web Feature Service (WFS)
client
defined
server
Web Map Service (WMS)
defined
map requests
sample configuration file
–
server setup
–
Web namespace
Web server
defined
web tools
DistanceTool
for use with MapControl
InfoTool
Index
MapXtreme2004_DevGuide_A4.pdf
Developer Guide
Web.config file
configuring for WMS
enabling pooling in ASP.NET applications
session management in ASP.NET applications
Weekday function
WFS
Windows 2000
supported operating system
Windows 2003
supported operating system
Windows Bitmap files
supported raster format
Windows controls
desktop applications
MapControl
MapForm applications
–
Windows dialog boxes
CreateThemeWizard
customizing
Windows metafiles
supported raster format
Windows XP
supported operating system
Windows.Controls namespace
Windows.Dialogs namespace
.wmf files
supported raster format
WMS
Workspace Manager
feature summary
labels
–
–
LayerControl tools
–
–
save as XML
tools menu commands
WorkSpaceLoader class
customizing
workspaces
defined
,
–
XML format
WtAvg function
X
XML elements
building ASP.NET applications without templates
XML files
importing features from
MapLoader
defined
Y
Year function
Z
Z category matches
geocoding result codes
© 2004 MapInfo Corporation. All rights reserved.
MapXtreme 2004
367
Index
MapXtreme2004_DevGuide_A4.pdf
Download
Advertisement
Key features
Provides a comprehensive overview of the MapXtreme 2004 architecture
Explains core classes and namespaces
Covers data access, find locations, and thematic mapping
Guides on building web applications with MapXtreme controls
Details desktop controls and dialogs for desktop applications
Frequently asked questions
MapXtreme is a powerful software development kit (SDK) that lets you build rich mapping applications for the desktop and the Web using the MapInfo engine.
This Developer Guide provides a step-by-step approach to learning MapXtreme 2004. You can also find tutorials and examples on the MapInfo website.
The system requirements are listed in Chapter 2 of this guide. You'll need a compatible operating system, .NET Framework, and other prerequisites.