MB Ref
MB Ref
Reference Guide
Version 7.0
MapBasic
Development Environment
Reference
MapInfo Corporation
Troy, New York
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.
1992–2002 MapInfo Corporation. All rights reserved. MapInfo, MapInfo Professional, MapBasic, and the MapInfo Logo
are registered trademarks of MapInfo Corporation.
Contact MapInfo Corporation on the Internet at: http://www.mapinfo.com.
Voice: (518) 285-6000 Voice: +44 (0)1753 848 200 Voice: +49 (0)6142 203 400
Fax: (518) 285-6060 Fax:+44 (0)1753 621 140 Fax: +49 (0)6142 203 444
Technical Support Hotline: Toll-free telephone support is available in the U.S. and Canada. Contact
(518) 285-7283 your MapInfo sales representative for details. For international customers,
Technical Support Fax: please use the Technical Support Fax number.
(518) 285-6080
Adobe Acrobat® is a registered trademark of Adobe Systems Incorporated in the United States.
libtiff 1988–1995 Sam Leffler, copyright 1991–1995 Silicon Graphics, Inc.
libgeotiff 1995 Niles D. Ritter.
Portions Copyright 1999 3D Graphics, Inc. All Rights Reserved.
HIL – Halo Imaging Library™ Copyright 1993, Media Cybernetics Inc. Halo Imaging Library is a trademark of Media
Cybernetics, Inc.
Portions hereof LEAD Technologies, Inc. 1991–1997. All Rights Reserved.
Portions Copyright 1993–2002 Ken Martin, Will Schroeder, Bill Lorensen. All Rights Reserved.
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
Blue Marble 1993–2002.
ECW by ER Mapper 1998–2002.
VMGrid by Northwood Technologies, Inc., a Marconi Company 1995–2002 ™.
Portions 2002 Earth Resource Mapping, Ltd. All Rights Reserved.
Portions of this software are copyrighted by MERANT, 1991–2002.
MrSID, MrSID Decompressor and the MrSID logo are trademarks of LizardTech, Inc. used under license. Portions of this
computer program are copyright (c) 1995–1998 LizardTech and/or the university of California or are protected by US
patent nos. 5,710,835; 5,130,701; or 5,467,110 and are used under license. All rights reserved. MrSID is protected under US
and international patent & copyright treaties and foreign patent applications are pending. Unauthorized use or
duplication prohibited.
Universal Translator by Safe Software, Inc. 2002.
Crystal Reports® is proprietary trademark of Crystal Decisions. All Rights Reserved.
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.
This documentation reflects the contributions of almost all of the women and men that work for MapInfo Corporation. It
was specifically produced by Gayle Patenaude and Marie Costa, with the help of Juliette Funiciello, Colleen Cox, and Ed
McElroy. Dave Smith, now back in Engineering, is the ‘godfather’ of this volume. The Documentation Department is
indebted to MapInfo’s Quality Assurance Department and, of course, to all the members of the Product Development team
that engineered this project.
This manual uses the following conventions to designate specific items in the text:
Convention Meaning
If, Call, Map, Browse, Area Bold words with the first letter capitalized are MapBasic
keywords.
Language Overview
The following pages provide an overview of the MapBasic language. Task descriptions
appear on the left; corresponding statement names and function names appear on the
right, in bold. Function names are followed by parentheses ( ).
MapBasic Fundamentals
Variables
Declare local or global variables: Dim, Global
Resize array variables: ReDim, UBound( ), UnDim
Declare custom data structure: Type
Error Handling
Set up an error handler: OnError
Return current error information: Err( ), Error$( )
Return from error handler: Resume
Simulate an error: Error
Functions
Custom Funtions
Define a custom function: Declare Funtion, Funtion...End
Function
Exit a function: Exit Function
Data-Conversion Functions
Convert strings to codes: Asc( )
Convert codes to strings: Chr$( )
Convert strings to numbers: Val( )
Convert numbers to strings: Str$( ), Format$( )
Convert a number or a string to a NumberToDate( ), StringToDate( )
date:
Converting to a 2-Digit Year: Set Date Window, DateWindow( )
Convert object types: ConvertToRegion( ), ConvertToPline( )
Convert labels to text Labelinfo( )
Math Functions
Trigonometric functions: Cos( ), Sin( ), Tan( ), Acos( ), Asin( ), Atn( )
Geographic functions: Area( ), Perimeter( ), Distance( ), ObjectLen( ),
CartesianArea( ), CatesianPerimeter(),
CartesianDistance( ), CartesianObjectLen( ),
SphericalArea( ), SphericalPerimeter( ),
SphericalDistance( ), SphericalObjectLen( )
Random numbers: Randomize, Rnd( )
Sign-related functions: Abs( ), Sgn( )
Truncating fractions: Fix( ), Int( ), Round( )
Other math functions: Exp( ), Log( ), Minimum( ), Maximum( ), Sqr( )
String Functions
Upper / lower case: UCase$( ), LCase$( ), Proper$( )
Find a sub-string: InStr( )
Extract part of a string: Left$( ), Right$( ), Mid$( ), MidByte$( )
Trim blanks from a string: LTrim$( ), RTrim$( )
Format numbers as strings: Format$( ), Str$( ), Set Format,
FormatNumber$( ), DeformatNumber$()
Determine string length: Len( )
Convert character codes: Chr$( ), Asc( )
Compare strings: Like( ), StringCompare( ), StringCompareIntl()
Repeat a string sequence: Space$( ), String$( )
Return unit name: UnitAbbr$( ), UnitName$( )
Querying Tables
Position the row cursor: Fetch, EOT( )
Select data, work with Selection: Select, SelectionInfo( )
Find map objects by address: Find, Find Using, CommandInfo( )
Find map objects at location: SearchPoint( ), SearchRect( ), SearchInfo( )
Obtain table information: NumTables( ), TableInfo( )
Obtain column information: NumCols( ), ColumnInfo( )
Query a table’s metadata: GetMetadata$( ), Metadata
Query seamless tables: TableInfo( ), GetSeamlessSheet( )
Dialog Boxes
Display a standard dialog: Ask( ), Note, ProgressBar, FileOpenDlg( ),
FileSaveAsDlg( ), GetSeamlessSheet( )
Display a custom dialog: Dialog
Dialog handler operations: Alter Control, TriggerControl( ),
ReadControlValue( ),Dialog Preserve, Dialog
Remove
Determine whether user clicked OK: CommandInfo(CMD_INFO_DLG_OK)
Disable progress bars: Set ProgressBars
Modify a standard MI Pro dialog: Alter MapInfoDialog
Menus
Define a new menu: Create Menu
Redefine the menu bar: Create Menu Bar
Modify a menu: Alter Menu, Alter Menu Item
Modify the menu bar: Alter Menu Bar, Menu Bar
Invoke a menu command: Run Menu Command
Query a menu item’s status: MenuitemInfoByHandler( ), MenuitemInfoByID( )
Windows
Show or hide a window: Open Window, Close Window, Set Window
Open a new window: Map, Browse, Graph, Layout, Create Redistricter,
Create Legend, Create Cartographic Legend,
LegendFrameInfo
Determine a window’s ID: FrontWindow( ), WindowID( )
Modify an existing window: Set Map, Shade, Add Map, Remove Map, Set
Browse, Set Graph, Set Layout, Create Frame, Set
Legend, Set Cartographic Legend, Set Redistricter,
StatusBar, Cartographic Legend, Alter
Cartographic Frame, Add Cartographic Frame,
Remove Cartographic Frame, Set
Return a window’s settings: WindowInfo( ), MapperInfo( ), LayerInfo( )
Print a window: PrintWin
Control window redrawing: Set Event Processing, Update Window, Control
DocumentWindow
Count number of windows: NumWindows( ), NumAllWindows( )
Hide columns from Browser: Reproject
Integrated Mapping
Set MI Pro ’s parent window: Set Application Window
Set a Map window’s parent: Set Next Document
Create a Legend window: Create Legend
A – Z Reference
The next section describes the MapBasic language in detail. You will find both statements
and function descriptions arranged alphabetically. Each is described in the following
format:
Purpose
Brief description of the function or statement.
Restrictions
Information about limitations (e.g., “The DDEInitiate function is only available under
Microsoft Windows,” “You cannot issue a For...Next statement through the MapBasic
window”).
Syntax
The format in which you should use the function or statement and explanation of
argument(s).
Return Value
The type of value returned by the function.
Description
Thorough explanation of the function or statement’s role and any other pertinent
information.
Example
A brief example.
See Also
Related functions or statements.
Most MapBasic statements can be typed directly into MapInfo Professional, through
MI Pro ’s MapBasic window. If a statement may not be entered through the MapBasic
window, the Restrictions section identifies the limitation. Generally, flow-control
statements (such as looping and branching statements) cannot be entered through the
MapBasic window.
Abs( ) function
Purpose
Returns the absolute value of a number.
Syntax
Abs ( num_expr )
num_expr is a numeric expression
Return Value
Float
Description
The Abs( ) function returns the absolute value of the expression specified by num_expr.
If num_expr has a value greater than or equal to zero, Abs( ) returns a value equal to num_expr.
If num_expr has a negative value, Abs( ) returns a value equal to the value of num_expr
multiplied by negative one.
Example
Dim f_x, f_y As Float
f_x = -2.5
f_y = Abs(f_x)
Acos( ) function
Purpose
Returns the arc-cosine value of a number.
Syntax
Acos ( num_expr )
num_expr is a numeric expression between one and minus one, inclusive
Return Value
Float
Description
The Acos( ) function returns the arc-cosine of the numeric num_expr value. In other words,
Acos( ) returns the angle whose cosine is equal to num_expr.
The result returned from Acos( ) represents an angle, expressed in radians. This angle will be
somewhere between zero and Pi radians (given that Pi is equal to approximately 3.141593, and
given that Pi/2 radians represents 90 degrees).
To convert a degree value to radians, multiply that value by DEG_2_RAD. To convert a radian
value into degrees, multiply that value by RAD_2_DEG. Your program must Include
“MAPBASIC.DEF” in order to reference DEG_2_RAD or RAD_2_DEG.
Since cosine values range between one and minus one, the expression num_expr should
represent a value no larger than one and no smaller than minus one.
Example
Include ”MAPBASIC.DEF”
Dim x, y As Float
x = 0.5
y = Acos(x) * RAD_2_DEG
’ y will now be equal to 60,
’ since the cosine of 60 degrees is 0.5
See Also
Asin( ), Atn( ), Cos( ), Sin( ), Tan( )
Label is a valid expression or default (meaning that the default frame style pattern is used when
creating each style’s text, unless the style clause contains text). The default is default.
style_name is a string which displays next to a symbol, line, or region in a custom frame.
Description
If the Custom keyword is included, then each frame section must include a Position clause. If
Custom is omitted and the legend is laid out in portrait or landscape, then the frames will be
added to the end.
The Position clause controls the frame’s position on the legend window. The upper left corner
of the legend window has the position 0, 0. Position values use paper units settings, such as
“in” (inches) or “cm” (centimeters). MapBasic has a current paper units setting, which defaults
to inches; a MapBasic program can change this setting through the Set Paper Units
statement.You can override the current paper units by including the optional Units subclause
within the Position clause.
The defaults in this statement apply only to the frames being created in this statement. They
have no affect on existing frames. Frame defaults used in the Create Cartographic Legend or
previous have no affect on frames created in this statement.
The Style clause and the NoRefresh keyword allow you to create a custom frame that will not
be overwritten when the legend is refreshed. If the NoRefresh keyword is used in the Style
clause, then the table is not scanned for styles. Instead, the Style clause must contain your
custom list of definitions for the styles displayed in the frame. This is done with the Text and
appropriate Line, Region, or Symbol clause.
See Also
Create Cartographic Legend, Set Cartographic Legend, Alter Cartographic Frame, Remove
Cartographic Frame
Given these two tables, you might want to calculate the population that lives within the risk
region. If half of a town’s area falls within the risk region, you will consider half of that town’s
population to be at risk; if a third of a town’s area falls within the risk region, you will consider
a third of that town’s population to be at risk; etc.
The following example calculates the population at risk by using the Proportion Sum
aggregate function, then stores the calculation in a new column (population_at_risk):
Add Column Risk(population_at_risk Integer)
From towns
Set To Proportion Sum(town_pop)
Where Intersects
For each town that is at least partly within the risk region, MI Pro adds some or all of the town’s
town_pop value to a running total.
The Proportion Sum function produces results based on an assumption - the assumption that
the number being totalled is distributed evenly throughout the region. If you use Proportion
Sum to process population statistics, and half of a region falls within another region, MI Pro
adds half of the region’s population to the total. In reality, however, an area representing half of
a region does not necessarily contain half of the region’s population. For example, the
population of New York State is not evenly distributed, because a very large percentage of the
population lives in New York City.
If you use Proportion Sum in cases where the data values are not evenly distributed, the results
may not be realistic. To ensure accurate results, work with smaller region objects (e.g., operate
on county regions instead of state regions).
The Proportion Avg aggregate function performs an average calculation which takes into
account the percentage of an object that is covered by another object. Continuing the previous
example, suppose the Towns table contains a column, median_age, that indicates the median
age in each town. The following statement calculates the median age within the risk zone:
Add Column Risk(age Float)
From Towns
Set To Proportion Avg(median_age)
Where Intersects
For each row in the Towns table, MI Pro calculates the percentage of the risk region that is
covered by the town; that calculation produces a number between zero and one, inclusive. MI
Pro multiplies that number by the town’s median_age value, and adds the result to a running
total. Thus, if a town has a median_age value of 50, and if the town region covers 10% of the
risk region, MI Pro adds 5 (five) to the running total, because 10% of 50 is 5.
Proportion WtAvg is similar to Proportion Avg, but it also lets you specify a data column for
weighting the average calculation; the weighting is also proportionate.
Using Proportion... Functions With Non-Region Objects
When you use Proportion functions and the source table contains region objects, MI Pro
calculates percentages based on the overlap of regions. However, when the source table
contains non-region objects, MI Pro treats each object as if it were completely inside or
completely outside of the destination region (depending on whether the non-region object’s
centroid is inside or outside of the destination region).
Dynamic Columns
If you include the optional Dynamic keyword, the new column becomes a dynamic computed
column, meaning that subsequent changes made to the source table are automatically applied
to the destination table.
If you create a dynamic column, and then close the source table used to calculate the dynamic
column, the column values are frozen (the column is no longer updated dynamically).
Similarly, if a geographic join is used in the creation of a dynamic column, and you close either
of the maps used for the geographic join, the column values are frozen.
See Also
Alter Table, Update
vehicle as a point object. You can receive current vehicle coordinates by using GPS (Global
Positioning Satellite) technology, and then update the point objects to show the current vehicle
locations on the map. In this type of application, where map objects are constantly changing,
the map redraws much more quickly if the objects being updated are stored in the animation
layer instead of a conventional layer.
The following example opens a table (Vehicles) and makes the table an animation layer:
Open Table ”vehicles” Interactive
Add Map Layer vehicles Animate
If the Add Map statement specifies two or more layers and it includes the Animate keyword,
the first layer named becomes the animation layer, and the remaining layers are added to the
map as conventional layers.
To terminate the animation layer processing, issue a Remove Map ... Layer Animate statement.
Animation layers have special restrictions. For example, users cannot use the Info tool to click
on objects in an animation layer. Also, each Map window can have only one animation layer.
For more information about animation layers, see the MapBasic User’s Guide
Example
Open Table ”world”
Map From world
Open Table ”cust1992” As customers
Open Table ”lead1992” As leads
Add Map Auto Layer customers, leads
See Also
Map, Remove Map, Set Map
AEExecute( ) function
Purpose
Sends a DoScript event to an Apple Event server application.
Restrictions
This function is only available when running MapInfo for Macintosh.
Syntax
AEExecute( channel , command )
channel is an Integer value used to reference the Apple Event channel previously established by
AEInitiate( )
command is a String to send as a DoScript event
Return Value
Integer representing a standard Apple Event error code; 0 (zero) indicates that the function
executed successfully.
Description
After you have called AEInitiate( ) to initiate an Apple Event channel, you can call
AEExecute( ) to send a DoScript event.
See Also
AEInitiate( )
AEInitiate( ) function
Purpose
Establishes an Apple Event channel descriptor to use when sending an Apple Event through
the AEExecute( ) function.
Restrictions
This function is only available when running MapInfo for Macintosh.
Syntax
AEInitiate( channel )
channel is an Integer value used to reference the Apple Event channel
Return Value
Integer code:
Description
Call AEInitiate( ) to initiate an Apple Event channel.
See Also
AEExecute( )
different buttons call the same handler); or as a parameter to be used with the Alter Button
statement.
Icon n specifies the icon to appear on the button; n can be one of the standard MapInfo icon
codes listed in ICONS.DEF (e.g., MI_ICON_RULER). If the File sub-clause specifies the name
of a file containing icon resources, n is an Integer resource ID identifying a resource in the file.
Cursor n specifies the shape the mouse cursor should adopt whenever the user chooses a
ToolButton tool; cursor_code is a code (e.g., MI_CURSOR_ARROW) from ICONS.DEF. This
clause applies only to ToolButtons. If the File sub-clause specifies the name of a file containing
icon resources, n is an Integer resource ID identifying a resource in the file.
dm_code specifies whether the user can click and drag, or only click with the tool; dm_code is a
code (e.g., DM_CUSTOM_LINE) from ICONS.DEF. Applies only to ToolButtons.
msg is a String that specifies the button’s status bar help and, optionally, ToolTip help. The first
part of msg is the status bar help message. If the msg string includes the letters \n then the text
following the \n is used as the button’s ToolTip help.
The ModifierKeys clause applies only to ToolButtons; it controls whether the shift and control
keys affect “rubber-band” drawing if the user drags the mouse while using a ToolButton.
Default is Off (modifier keys have no effect).
Description
Use the Alter ButtonPad statement to show, hide, modify, or destroy an existing ButtonPad.
For an introduction to ButtonPads, see the MapBasic User’s Guide.
To show or hide a ButtonPad, include the Show or Hide keyword; see example below. The user
also can show or hide ButtonPads by choosing the Options > Toolbars command.
To set whether the pad is fixed to the top of the screen (“docked”) or floating like a window,
include the Fixed or the Float keyword. The user can also control whether the pad is docked or
not by dragging the pad to or from the top of the screen.
When a pad is floating, its position is controlled by the Position clause; when a pad is docked,
its position is controlled by the ToolbarPosition clause.
To destroy a ButtonPad, include the Destroy keyword. Once a ButtonPad is destroyed, it no
longer appears in the Options > Toolbars dialog.
The Alter ButtonPad statement can add buttons to existing ButtonPads, such as Main and
Drawing. There are three types of button controls you can add: PushButton controls (which the
user can click and release -for example, to display a dialog); ToggleButton controls (which the
user can select by clicking, then deselect by clicking again); and ToolButton controls (which the
user can select, and then use for clicking on a Map or Layout window).
If you include the optional Disable keyword when adding a button, the button is disabled
(grayed out) when it appears. Subsequent Alter Button statements can enable the button.
However, if the button’s handler is a standard MI Pro command, MI Pro automatically enables
or disables the button depending on whether the command is currently enabled.
If you include the optional Check keyword when adding a ToggleButton or a ToolButton, the
button is automatically selected (“checked”) when it first appears.
If the user clicks while using a custom ToolButton tool, MI Pro automatically calls the tool’s
handler, unless the user cancels (e.g., by pressing the Esc key while dragging the mouse). A
handler procedure can call CommandInfo( ) to determine where the user clicked. If two or
more tools call the same handler procedure, the procedure can call CommandInfo( ) to
determine the ID of the button currently in use.
All of the draw modes except for DM_CUSTOM_POINT support the autoscroll feature, which
allows the user to scroll a Map or Layout by clicking and dragging to the edge of the window.
To disable autoscroll, see Set Window.
Note: MapBasic supports an additional draw mode that is not available to MI Pro users. If a
custom ToolButton has the following Calling clause...
Calling M_TOOLS_SEARCH_POLYGON
...then the tool allows the user to draw a polygon. When the user double-clicks to close the
polygon, MI Pro selects all objects (from selectable map layers) within the polygon. The
polygon is not saved.
Examples
The following example shows the Main ButtonPad and hides the Drawing ButtonPad:
Alter ButtonPad ”Main” Show
Alter ButtonPad ”Drawing” Hide
The next example docks the Main ButtonPad and sets its docked position to 0,0 (upper left):
Alter ButtonPad ”Main” Fixed ToolbarPosition(0,0)
The next example moves the Main ButtonPad so that it is floating instead of docked, and sets
its floating position to half an inch inside the upper-left corner of the screen.
Alter ButtonPad ”Main” Float Position(0.5,0.5) Units ”in”
The sample program, ScaleBar, contains the following Alter ButtonPad statement, which adds
a custom ToolButton to the Tools ButtonPad. (Note that “ID 3” identifies the Tools ButtonPad.)
Alter ButtonPad ID 3
Add
Separator
ToolButton
Icon MI_ICON_CROSSHAIR
HelpMsg ”Draw a distance scale on a map\nScale Bar”
Cursor MI_CURSOR_CROSSHAIR
DrawMode DM_CUSTOM_POINT
Calling custom_tool_routine
Show
Note: The Separator keyword, which inserts space between the last button on the Tools
ButtonPad and the new “+” button.
See Also
Alter Button, ButtonPadInfo( ), Create ButtonPad
created. Therefore, if you plan to alter the length of a StaticText control, you may want to pad it
with spaces when you first define it. For example, your Dialog statement could include the
following clause:
Control StaticText ID 1 Title ”Message goes here” + Space$(30)
Example
The following example creates a dialog containing two check-boxes, an OK button, and a
Cancel button. Initially, the OK button is disabled (grayed out). The OK button is only enabled
if the user selects one or both of the check boxes.
Include ”mapbasic.def”
Declare Sub Main
Declare Sub checker
Sub Main
Dim browse_it, map_it As Logical
Dialog
Title ”Display a file”
Control CheckBox
Title ”Display in a Browse window”
Value 0
Calling checker
ID 1
Into browse_it
Control CheckBox
Title ”Display in a Map window”
Value 0
Calling checker
ID 2
Into map_it
Control CancelButton
Control OKButton
ID 3
Disable
If CommandInfo(CMD_INFO_DLG_OK) Then
’ ... then the user clicked OK...
End If
End Sub
Sub checker
’ If either check box is checked,
’ enable the OK button; otherwise, DISable it.
If ReadControlValue(1) Or ReadControlValue(2) Then
Alter Control 3 Enable
Else
Alter Control 3 Disable
End If
End Sub
See Also
Dialog, Dialog Preserve, ReadControlValue( )
The following table lists the names and ID numbers of all standard MI Pro menus. Note: menus
16 through 22 are shortcut menus, which appear if the user clicks with the right mouse button.
Shortcut menus are only available on Windows.
Examples
The following statement adds an item to the File menu.
Alter Menu ”File” Add
”Special” Calling sub_procedure_name
In the following example, the menu to be modified is identified by its number.
Alter Menu ID 1 Add
”Special” Calling sub_procedure_name
In the following example, the menu item that is added contains an ID clause. The ID number
(300) can be used in subsequent Alter Menu Item statements.
Alter Menu ID 1 Add
”Special” ID 300 Calling sub_procedure_name
The following example removes the custom item from the File menu.
Alter Menu ID 1 Remove sub_procedure_name
The sample program, TextBox, uses a Create Menu statement to create a menu called
“TextBox,” and then issues the following Alter Menu statement to add the TextBox menu as a
hierarchical menu located on the Tools menu:
Alter Menu ”Tools” Add
”(-”,
”TextBox” As ”TextBox”
The following example adds a custom command to the Map window’s shortcut menu (the
menu that appears when an MI Pro user right-clicks on a Map window).
Alter Menu ID 17 Add
”Find Nearest Site” Calling sub_procedure_name
See Also
Alter Menu Bar, Alter Menu Item, Create Menu, Create Menu Bar
Example
The following example creates a custom menu, called DataEntry, then uses an Alter Menu Bar
Add statement to add the DataEntry menu to MI Pro’s menu bar.
Declare Sub addsub
Declare Sub editsub
Declare Sub delsub
’Add the custom menu, then the Window & Help menus
Alter Menu Bar Add ”DataEntry”, ID 6, ID 7
Before adding the custom menu to the menu bar, this program removes the Help menu (menu
ID 7) and the Window menu (ID 6) from the menu bar. The program then adds the custom
menu, the Window menu, and the Help menu to the menu bar. This technique guarantees that
the last two menus will be Window and Help.
See Also
Alter Menu, Alter Menu Item, Create Menu, Create Menu Bar, Menu Bar Hide, Menu Bar
Show
Examples
The following example creates a custom “DataEntry” menu.
Declare Sub addsub
Declare Sub editsub
Declare Sub delsub
Geography clause
By issuing an Alter Object statement with a Geography clause, you can alter an object’s
geographical coordinates. The Geography clause applies to all object types except for polylines
and regions. To alter the coordinates of a polyline or region object, use the Node clause
(described below) instead of the Geography clause.
The Geography clause lets you modify the same attributes that you can query through the
ObjectGeography( ) function. For example, you can obtain a line object’s end coordinates by
calling the ObjectGeography( ) function:
Dim o_cable As Object
Dim x, y As Float
x = ObjectGeography(o_cable, OBJ_GEO_LINEENDX)
y = ObjectGeography(o_cable, OBJ_GEO_LINEENDY)
Conversely, the following Alter Object statements let you alter the line object’s end
coordinates:
Alter Object o_cable
Geography OBJ_GEO_LINEENDX, x
Alter Object o_cable
Geography OBJ_GEO_LINEENDY, y
Note: You use the same codes (e.g., OBJ_GEO_LINEENDX) in both the ObjectGeography()
function and the Alter Object statement.
The table below summarizes the values you can specify in the Geography clause in order to
perform various types of geographic alterations. Note that the obj_geo_code values are defined
in the standard MapBasic definitions file, MAPBASIC.DEF. Your program should Include
“MAPBASIC.DEF” if you intend to use the Alter Object...Geography statement.
Node clause
By issuing an Alter Object statement with a Node clause, you can add, remove, or reposition
nodes in a polyline or region object.
If the Node clause includes an Add sub-clause, the Alter Object statement adds a node to the
object. If the Node clause includes a Remove sub-clause, the statement removes a node. If the
Node clause includes a Set Position sub-clause, the statement repositions a node.
The Alter Object statement’s Node clause is often used in conjunction with the Create PLine
and Create Region statements. Create statements allow you to create new polyline and region
objects. However, Create statements are somewhat restrictive, because they force you to state at
compile time the number of nodes that will comprise the object. In some situations, you may
not know how many nodes should go into an object until run-time.
If your program will not know until run-time how many nodes should comprise an object, you
can issue a Create Pline or Create Region statement which creates an “empty” object (an object
with zero nodes). Your program can then issue an appropriate number of Alter Object ... Node
Add statements, to add nodes as needed.
Within the Node clause, the Position sub-clause includes two parameters - polygon_num and
node_num - that let you specify exactly which node you want to reposition or remove. The
Position sub-clause is optional when you are adding a node. The polygon_num and node_num
parameters should always be 1 (one) or greater.
The polygon_num parameter specifies which polygon in a multiple-polygon region (or which
section in a multiple-section polyline) should be modified.
Region Centroids
The Centroid of a Region can now be set by using the Alter Object command with the syntax
noted below:
Alter Object Obj Geography OBJ_GEO_CENTROID, PointObj
Note that PointObj is a point object. This differs from other values input by Alter Object
Geography, which are all scalars. A point is needed in this instance because we need two
values which define a point. The Point that is input is checked to make sure it is a valid
Centroid (i.e., it is inside the region). If the Obj is not a region, or if PointObj is not a point
object, or if the point is not a valid centroid, then an error is returned.
An easy way to center an X and Y value for a centroid is as follows:
Alter Object Obj Geography OBJ_GEO_CENTROID, CreatePoint(X, Y)
The user can also query the centroid by using the ObjectGeography function as follows:
PointObj = ObjectGeography(Obj, OBJ_GEO_CENTROID)
There are other ways to get the Centroid, including the Centroid(), CentroidX(), and
CentroidY() functions.
OBJ_GEO_CENTROID is defined in mapbasic.def.
Example
Dim myobj As Object, i As Integer
Create Region Into Variable myobj 0
For i = 1 to 10
Alter Object myobj
Node Add (Rnd(1) * 100, Rnd(1) * 100)
Next
Note: After using the Alter Object statement to modify an object, use an Insert statement or
an Update statement to store the object in a table.
See Also
Create PLine, Create Region, Insert, ObjectGeography( ), ObjectInfo( ), Update
Example
In the following example, we have a hypothetical table, “gcpop.tab” which contains the
following columns: pop_88, metsize, fipscode, and utmcode. The Alter Table statement below
makes several changes to the gcpop table. First, a Rename clause changes the name of the
pop_88 column to population. Then the Drop clause deletes the metsize, fipscode, and
utmcode columns. An Add clause creates two new columns: a small (2-byte) integer column
called schoolcode, and a floating point column called federalaid. Finally, an Order clause
specifies the order for the new set of columns: the schoolcode column comes first, followed by
the population column, etc.
Open Table ”gcpop”
Alter Table gcpop
(Rename pop_88 population
Drop metsize, fipscode, utmcode
Add schoolcode Smallint, federalaid Float
Order schoolcode, population, federalaid)
See Also
Add Column, Create Index, Create Map, Create Table, Drop
ApplicationDirectory$( ) function
Purpose
Returns a string containing the path from which the current MapBasic application is executing.
Syntax
ApplicationDirectory$( )
Return Value
String expression, representing a directory path.
Description
By calling the ApplicationDirectory$( ) function from within a compiled MapBasic application,
you can determine the directory or folder from which the application is running. If no
application is running (e.g., if you call the function by typing into the MapBasic window),
ApplicationDirectory$( ) returns a null string.
To determine the directory or folder where the MapInfo Professional software is installed, call
the ProgramDirectory$( ) function.
Example
Dim sAppPath As String
sAppPath = ApplicationDirectory$()
’ At this point, sAppPath might look like this:
’
’ ”C:\MAPBASIC\CODE\”
See Also
ProgramDirectory$( )
Area( ) function
Purpose
Returns the geographical area of an Object.
Syntax
Area ( obj_expr , unit_name )
obj_expr is an object expression
unit_name is a string representing the name of an area unit (e.g., “sq km”)
Return Value
Float
Description
The Area( ) function returns the area of the geographical object specified by obj_expr.
The function returns the area measurement in the units specified by the unit_name parameter;
for example, to obtain an area in acres, specify “acre” as the unit_name parameter. See the Set
Area Units statement for the list of available unit names.
Only regions, ellipses, rectangles, and rounded rectangles have any area. By definition, the
Area( ) of a point, arc, text, line, or polyline object is zero. The Area( ) function returns
approximate results when used on rounded rectangles. MapBasic calculates the area of a
rounded rectangle as if the object were a conventional rectangle.
For the most part, MapInfo Professional performs a Cartesian or Spherical operation. Generally,
a spherical operation is performed unless the coordinate system is nonEarth, in which case, a
Cartesian operation is performed.
Examples
The following example shows how the Area( ) function can calculate the area of a single
geographic object. Note that the expression tablename.obj (as in states.obj) represents the
geographical object of the current row in the specified table.
Dim f_sq_miles As Float
Open Table ”states”
Fetch First From states
f_sq_miles = Area(states.obj, ”sq mi”)
You can also use the Area( ) function within the SQL Select statement, as shown in the
following example.
Select state, Area(obj, ”sq km”)
From states Into results
See Also
ObjectLen( ), Perimeter( ), CartesianArea( ), SphericalArea( ), Set Area Units
AreaOverlap( ) function
Purpose
Returns the area resulting from the overlap of two closed objects.
Syntax
AreaOverlap ( object1, object2 )
object1 and object2 are closed objects.
Return Value
A Float value representing the area (in MapBasic’s current area units) of the overlap of the two
objects.
See Also
Overlap( ), ProportionOverlap( ), Set Area Units
Asc( ) function
Purpose
Returns the character code for the first character in a string expression.
Syntax
Asc ( string_expr )
string_expr is a String expression
Return Value
Integer
Description
The Asc( ) function returns the character code representing the first character in the string
specified by string_expr.
If string_expr is a null string, the Asc( ) function returns a value of zero.
Note: All MapInfo Professional environments have common character codes within the range
of 32 (space) to 126 (tilde).
On a system that supports double-byte character sets (e.g., Windows Japanese): if the first
character of string_expr is a single-byte character, Asc( ) returns a number in the range 0 - 255; if
the first character of string_expr is a double-byte character, Asc( ) returns a value in the range
256 - 65,535.
On systems that do not support double-byte character sets, Asc( ) returns a number in the
range 0 - 255.
Example
Dim code As SmallInt
code = Asc(”Afghanistan”)
’ code will now be equal to 65,
’ since 65 is the code for the letter A
See Also
Chr$( )
Asin( ) function
Purpose
Returns the arc-sine value of a number.
Syntax
Asin ( num_expr )
num_expr is a numeric expression from one to minus one, inclusive
Return Value
Float
Description
The Asin( ) function returns the arc-sine of the numeric num_expr value. In other words, Asin()
returns the angle whose sine is equal to num_expr.
The result returned from Asin( ) represents an angle, expressed in radians. This angle will be
somewhere between -Pi/2 and Pi/2 radians (given that Pi is approximately equal to 3.141593,
and given that Pi/2 radians represents 90 degrees).
To convert a degree value to radians, multiply that value by DEG_2_RAD. To convert a radian
value into degrees, multiply that value by RAD_2_DEG. (Note that your program will need to
Include “MAPBASIC.DEF” in order to reference DEG_2_RAD or RAD_2_DEG).
Since sine values range between one and minus one, the expression num_expr should represent
a value no larger than one and no smaller than minus one.
Example
Include ”MAPBASIC.DEF”
Dim x, y As Float
x = 0.5
y = Asin(x) * RAD_2_DEG
Ask( ) function
Purpose
Displays a dialog, asking the user a yes or no (OK or Cancel) question.
Syntax
Ask ( prompt , ok_text , cancel_text )
prompt is a String to appear as a prompt in the dialog box
ok_text is a String (e.g., “OK”) that appears on the confirmation button
cancel_text is a String (e.g., “Cancel”) that appears on the cancel button
Return Value
Logical
Description
The Ask( ) function displays a dialog box, asking the user a yes-or-no question. The prompt
parameter specifies a message, such as “File already exists; do you want to continue?” The
prompt string can be up to 300 characters long.
The dialog contains two buttons; the user can click one button to give a Yes answer to the
prompt, or click the other button to give a No answer. The ok_text parameter specifies the name
of the Yes-answer button (e.g., “OK” or “Continue”), and the cancel_text parameter specifies the
name of the No-answer button (e.g., “Cancel” or “Stop”).
If the user selects the ok_text button, the Ask( ) function returns TRUE. If the user clicks the
cancel_text button or otherwise cancels the dialog (e.g., by pressing the Escape key), the Ask( )
function returns FALSE. Since the buttons are limited in size, the ok_text and cancel_text strings
should be brief. If you need to display phrases that are too long to fit in small dialog buttons,
you can use the Dialog statement instead of calling the Ask( ) function. The ok_text button is
the default button (the button which will be selected if the user presses ENTER instead of
clicking with the mouse).
Example
Dim more As Logical
more = Ask(”Do you want to continue?”, ”OK”, ”Stop”)
See Also
Dialog, Note( ), Print
Atn( ) function
Purpose
Returns the arc-tangent value of a number.
Syntax
Atn( num_expr )
num_expr is a numeric expression
Return Value
Float
Description
The Atn( ) function returns the arc-tangent of the numeric num_expr value. In other words,
Atn( ) returns the angle whose tangent is equal to num_expr. The num_expr expression can have
any numeric value.
The result returned from Atn( ) represents an angle, expressed in radians, in the range -Pi/2
radians to Pi/2 radians.
To convert a degree value to radians, multiply that value by DEG_2_RAD. To convert a radian
value into degrees, multiply that value by RAD_2_DEG. (Note that your program will need to
Include “MAPBASIC.DEF” in order to reference DEG_2_RAD or RAD_2_DEG).
Example
Include ”MAPBASIC.DEF”
Dim val As Float
AutoLabel statement
Purpose
Draws labels in a Map window, and stores the labels in the Cosmetic layer.
Syntax
AutoLabel
[ Window window id ]
[ { Selection | Layer layer_id } ]
[ Overlap [ { On | Off } ] ]
[ Duplicates [ { On | Off } ] ]
window_id is an Integer window identifier for a Map window
layer_id is a table name (e.g., World) or a SmallInt layer number (e.g., 1 to draw labels for the
top layer)
Description
The AutoLabel statement draws labels (text objects) in a Map window. Only objects that are
currently visible in the Map window are labeled. The Window clause controls which Map
window is labeled. If you omit the Window clause, MapInfo Professional draws labels in the
front-most Map window. If you specify Selection, only selected objects are labeled. If you omit
both the Selection clause and the Layer clause, all layers are labeled.
The Overlap clause controls whether MI Pro draws labels that overlap other labels. This setting
defaults to Off (MI Pro will not draw overlapping labels). To force MI Pro to draw a label for
every map object, regardless of whether the labels overlap, specify Overlap On. The
Duplicates clause controls whether MI Pro draws a new label for an object that has already
been labeled. This setting defaults to Off (duplicates not allowed). The AutoLabel statement
uses whatever font and position settings are in effect. Set label options by choosing Map >
Layer Control. To control font and position settings through MapBasic, issue a Set Map
statement.
Example
Open Table ”world” Interactive
Open Table ”worldcap” Interactive
Map From world, worldcap
AutoLabel
Window FrontWindow()
Layer world
See Also
Set Map
Beep statement
Purpose
Makes a beeping sound.
Syntax
Beep
Description
The Beep statement sends a sound to the speaker.
Browse statement
Purpose
Opens a new Browser window.
Syntax
Browse expression_list From table
[ Position ( x , y ) [ Units paperunits ] ]
[ Width window_width [ Units unitname ] ]
[ Height window_height [ Units unitname ] ]
[ Row n ]
[ Column n ]
[ Min | Max ]
expression_list is either an asterisk or a comma-separated list of column expressions
table is the name of an open table
unitname is a String representing the name of a paper unit (e.g., “mm”)
x , y specifies the position of the upper left corner of the Browser, in paper units
window_width and window_height specify the size of the Browser, in paper units
n is a positive integer value
Description
The Browse statement opens a Browse window to display a table.
If the expression_list is simply an asterisk (*), the new Browser includes all fields in the table.
Alternately, the expression_list clause can consist of a comma-separated list of expressions, each
of which defines one column that is to appear in the Browser. Expressions in the list can contain
column names, operators, functions, and variables. Each column’s name is derived from the
expression that defines the column. Thus, if a column is defined by the expression population
/ area(obj, “acre”) , that expression will appear on the top row of the Browser, as the column
“name.” To assign an alias to an expression, follow the expression with a String; see example
below.
An optional Position clause lets you specify where on the screen to display the Browser. The x
coordinate specifies the distance (in paper units) from the left edge of the MapInfo Professional
application window to the left edge of the Browser. The y coordinate specifies the distance from
the top of the MI Pro window down to the top of the Browser. The optional Width and Height
clauses specify the size of the Browser window, in paper units. If no Width and Height clauses
are provided, MI Pro assigns the Browser window a default size which depends on the table in
question: the Browser height will generally be one quarter of the screen height, unless the table
does not have enough rows to fill a Browser window that large; and the Browser width will
depend on the widths of the fields in the table.
If the Browse statement includes the optional Max keyword, the resultant Browser window is
maximized, taking up all of the screen space available to MapInfo. Conversely, if the Browse
statement includes the Min keyword, the Browser window is minimized immediately; note
that certain hardware platforms do not support minimized windows.
The Row clause dictates which row of the table should appear at the top of the Browser. If the
Browse statement does not include a Row clause, the first row of the table will be the top row
in the Browser.
Similarly, the Column clause dictates which of the table’s columns should appear at the left
edge of the Browser. If the Browse statement does not include a Column clause, the table’s first
column will appear at the left edge of the Browser window.
Example
The following example opens the World table and displays all columns from the table in a
Browser window.
Open Table ”world”
Browse * From world
The next example specifies exactly which column expressions from the World table should be
displayed in the Browser.
Open Table ”world”
Browse
country,
population,
population/area(obj, ”sq km”) ”Density”
From world
The resultant Browser has three columns. The first two columns represent data as it is stored in
the World table, while the third column is derived. Through the third expression, MapBasic
divides the population of each country record with the geographic area of the region associated
with that record. The derived column expression has an alias (“Density”) which appears on the
top row of the Browse window.
See Also
Set Browse, Set Window
Brush clause
Purpose
Specifies a fill style for graphic objects.
Syntax
Brush brush_expr
brush_expr is a Brush expression, such as MakeBrush( pattern, fgcolor, bgcolor )
Description
The Brush clause specifies a brush style - in other words, a set of color and pattern settings that
dictate the appearance of a filled object, such as a circle or rectangle. Brush is a clause, not a
complete MapBasic statement. Various object-related statements, such as Create Ellipse, allow
you to specify a brush value. The keyword Brush may be followed by an expression which
evaluates to a Brush value. This expression can be a Brush variable:
Brush br_var
or a call to a function which returns a Brush value:
Brush MakeBrush(64, CYAN, BLUE)
With some MapBasic statements (e.g., Set Map), the keyword Brush can be followed
immediately by the three parameters that define a Brush style ( pattern, foreground color, and
background color) within parentheses:
Brush(64, CYAN, BLUE)
Some MapBasic statements take a Brush expression as a parameter (e.g., the name of a Brush
variable), rather than a full Brush clause (the keyword Brush followed by the name of a Brush
variable). The Alter Object statement is one example.
The following table summarizes the three components (pattern, foreground color, background
color) that define a Brush:
Component Description
pattern Integer value from 1 to 8 or from 12 to 71; see table below.
foreground color Integer RGB color value; see the RGB( ) function. The definitions
file, MAPBASIC.DEF, includes Define statements for BLACK,
WHITE, RED, GREEN, BLUE, CYAN, MAGENTA, and
YELLOW.
background color Integer RGB color value.
To specify a transparent background, use pattern 3 or larger, and omit the background color
from the Brush clause. For example, specify Brush( 5, BLUE) to see thin blue stripes with no
background fill color. Omitting the background parameter is like clearing the Background
check box in MapInfo Professional’s Region Style dialog.
To specify a transparent background when calling MakeBrush( ), specify -1 as the background
color.
The available patterns appear below. Pattern 2 produces a solid fill; pattern 1 produces no fill.
See Also
CurrentBrush( ), MakeBrush( ), Pen, Font, Symbol
Buffer( ) function
Purpose
Returns a region object that represents a buffer region (the area within a specified buffer
distance of an existing object).
Syntax
Buffer ( inputobject, resolution, width, unit_name )
inputobject is an object expression
resolution is a SmallInt value representing the number of nodes per circle at each corner
width is a Float value representing the radius of the buffer; if width is negative, and if
inputobject is a closed object, the object returned represents an object smaller than the original
object. If the width is negative, and the object is a linear object (line, polyline, arc) or a point,
then the absolute value of width is used to produce a positive buffer
unit_name is the name of the distance unit (e.g., “mi” for miles, “km” for kilometers) used by
width
Return Value
Returns a region object
Description
The Buffer( ) function returns a region representing a buffer.
The Buffer( ) function operates on one single object at a time. To create a buffer around a set of
objects, use the Create Object As Buffer statement. The object will be created using the current
MapBasic coordinate system. The method used to calculate the buffer depends on the
coordinate system. If it is NonEarth, then a cartesioan method will be used. Otherwise, a
spherical method will be used.
Example
The following program creates a line object, then creates a buffer region surrounding the line.
The buffer region extends ten miles in all directions from the line.
Dim o_line, o_region As Object
o_line = CreateLine(-73.5, 42.5, -73.6, 42.8)
o_region = Buffer( o_line, 20, 10, ”mi”)
See Also
Create Object
ButtonPadInfo( ) function
Purpose
Returns information about a ButtonPad.
Syntax
ButtonPadInfo ( pad_name , attribute )
pad_name is a string representing the name of an existing ButtonPad; use “Main”, “Drawing”,
“Tools” or “Standard” to query the standard pads, or specify the name of a custom pad.
attribute is a code indicating which information to return; see table below.
Return Value
Depends on the attribute parameter specified
Description
The attribute parameter specifies what information to return.
Call statement
Purpose
Calls a sub procedure or an external routine (DLL, XCMD).
Restrictions
You cannot issue a Call statement through the MapBasic window.
Syntax
Call subproc [ ( [ parameter ] [ , ... ] ) ]
subproc is the name of a sub procedure
parameter is a parameter expression to pass to the sub procedure
Description
The Call statement calls a procedure. The procedure is usually a conventional MapBasic sub
procedure (defined through the Sub statement). Alternately, a program running under
MapInfo Professional for Windows can call a Windows Dynamic Link Library (DLL) routine
through the Call statement.
When a Call statement calls a conventional MapBasic procedure, MapBasic begins executing
the statements in the specified sub procedure, and continues until encountering an End Sub or
an Exit Sub statement. At that time, MapBasic returns from the sub procedure, then executes
the statements following the Call statement. The Call statement can only access sub procedures
which are part of the same application.
A MapBasic program must issue a Declare statement to define the name and parameter list of
any procedure which is to be called. This requirement is independent of whether the procedure
is a conventional MapBasic Sub procedure, a DLL procedure or an XCMD.
Parameter Passing
Sub procedures may be defined with no parameters. If a particular sub procedure has no
parameters, then calls to that sub procedure may appear in either of the following forms:
Call subroutine
or
Call subroutine( )
By default, each sub procedure parameter is defined “by reference.” When a sub procedure has
a by-reference parameter, the caller must specify the name of a variable to pass as the
parameter. If the procedure then alters the contents of the by-reference parameter, the caller’s
variable is automatically updated to reflect the change. This allows the caller to examine the
results returned by the sub procedure.
Alternately, any or all sub procedure parameters may be passed “by value” if the keyword
ByVal appears before the parameter name in the Sub and Declare Sub declarations. When a
parameter is passed by value, the sub procedure receives a copy of the value of the parameter
expression; thus, the caller can pass any expression, rather than having to pass the name of a
variable.
A sub procedure can take an entire array as a single parameter. When a sub procedure expects
an array as a parameter, the caller should specify the name of an array variable, without the
parentheses.
CartesianArea( ) function
Purpose
Returns the area as calculated in a flat, projected coordinate system using a Cartesian
algorithm.
Syntax
CartesianArea( expr, unit_name )
expr is an object expression
unit_name is a string representing the name of an area unit (e.g., ”sq km”)
Return Value
Float
Description
The CartesianArea( ) function returns the Cartesion area of the geographical object specified by
obj_expr.
The function returns the area measurement in the units specified by the unit_name parameter;
for example, to obtain an area in acres, specify ”acre” as the unit_name parameter. See the Set
Area Units statement for the list of available unit names.
The CartesianArea()function will always return the area using a cartesian algorithm. A value of
-1 will be returned for data that is in a Latitude/Longitude since the datais not projected.
Only regions, ellipses, rectangles, and rounded rectangles have any area. By definition, the
CartesianArea( ) of a point, arc, text, line, or polyline object is zero. The CartesianArea( )
function returns approximate results when used on rounded rectangles. MapBasic calculates
the area of a rounded rectangle as if the object were a conventional rectangle.
Examples
The following example shows how the CartesianArea( ) function can calculate the area of a
single geographic object. Note that the expression tablename.obj (as in states.obj) represents
the geographical object of the current row in the specified table.
Dim f_sq_miles As Float
Open Table ”counties”
Fetch First From counties
f_sq_miles = CartesianArea(counties.obj, ”sq mi”)
You can also use the CartesianArea( ) function within the SQL Select statement, as shown in
the following example.
Select lakes, CartesianArea(obj, ”sq km”)
From lakes Into results
See Also
Area ( ), SphericalArea ( )
CartesianBuffer( ) function
Purpose
Returns a region object that represents a buffer region (the area within a specified buffer
distance of an existing object).
Syntax
CartesianBuffer ( inputobject, resolution, width, unit_name )
inputobject is an object expression
resolution is a SmallInt value representing the number of nodes per circle at each corner
width is a Float value representing the radius of the buffer; if width is negative, and if
inputobject is a closed object, the object returned represents an object smaller than the original
object
unit_name is the name of the distance unit (e.g., ”mi” for miles, ”km” for kilometers) used by
width
Return Value
Region Object
Description
The CartesianBuffer( ) function returns a region representing a buffer and operates on one
single object at a time.
To create a buffer around a set of objects, use the Create Object As Buffer statement. If the
width is negative, and the object is a linear object (line, polyline, arc) or a point, then the
absolute value of width is used to produce a positive buffer.
The CartesianBuffer( ) function will calculate the buffer by assuming the object is in a flat
projection and using the width to calculate a cartesian distance calculated buffer around the
object.
If the inputobject is in a Latitude/Longitude Projection, then Spherical calculations will be used
regardless of the Buffer function used.
Example
The following program creates a line object, then creates a buffer region that extends 10 miles
surrounding the line.
Dim o_line, o_region As Object
o_line = CreateLine(-73.5, 42.5, -73.6, 42.8)
o_region = CartesianBuffer( o_line, 20, 10, ”mi”)
See Also
Buffer( ), Creating Map objects
CartesianDistance( ) function
Purpose
Returns the distance between two locations.
Syntax
CartesianDistance ( x1 , y1 , x2 , y2 , unit_name )
x1 and x2 are x-coordinates
y1 and y2 are y-coordinates
unit_name is a string representing the name of a distance unit (e.g., ”km”)
Return Value
Float
Description
The CartesianDistance( ) function calculates the Cartesian distance between two locations. It
returns the distance measurement in the units specified by the unit_name parameter; for
example, to obtain a distance in miles, specify ”mi” as the unit_name parameter. See the Set
Distance Units statement for the list of available unit names.
The CartesianDistance( ) function will always return a value using a cartesian algorithm. A
value of -1 will be returned for data that is in a Latitude/longitude coodinate system, since
Latitude/Longitude data is not projected and not cartesian.
The x- and y-coordinate parameters must use MapBasic’s current coordinate system. By
default, MapInfo Professional expects coordinates to use a longitude, latitude coordinate
system. You can reset MapBasic’s coordinate system through the Set CoordSys statement.
Example
Dim dist, start_x, start_y, end_x, end_y As Float
Open Table ”cities”
Fetch First From cities
start_x = CentroidX(cities.obj)
start_y = CentroidY(cities.obj)
Fetch Next From cities
end_x = CentroidX(cities.obj)
end_y = CentroidY(cities.obj)
dist = CartesianDistance(start_x,start_y,end_x,end_y,”mi”)
See Also
Math functions, CartesianDistance( ), Distance( )
CartesianObjectLen( ) function
Purpose
Returns the geographic length of a line or polyline object.
Syntax
CartesianObjectLen( expr , unit_name )
obj_expr is an object expression
unit_name is a string representing the name of a distance unit (e.g., ”km”)
Return Value
Float
Description
The CartesianObjectLen( ) function returns the length of an object expression. Note that only
line and polyline objects have length values greater than zero; to measure the circumference of
a rectangle, ellipse, or region, use the Perimeter( ) function.
The CartesianObjectLen( ) function will always return a value using a cartesian algorithm. A
value of -1 will be returned for data that is in a Latitude/Longitude coodinate system, since
Latitude/Longitude data is not projected and not cartesian.
The CartesianObjectLen( ) function returns a length measurement in the units specified by the
unit_name parameter; for example, to obtain a length in miles, specify ”mi” as the unit_name
parameter. See the Set Distance Units statement for the list of valid unit names.
Example
Dim geogr_length As Float
Open Table ”streets”
Fetch First From streets
geogr_length = CartesianObjectLen(streets.obj, ”mi”)
’ geogr_length now represents the length of the
’ street segment, in miles
See Also
SphericalObjectLen( ), CartesianObjectLen( ), ObjectLen( )
CartesianPerimeter( ) function
Purpose
Returns the perimeter of a graphical object.
Syntax
CartesianPerimeter( obj_expr , unit_name )
obj_expr is an object expression
unit_name is a string representing the name of a distance unit (e.g., ”km”)
Return Value
Float
Description
The CartesianPerimeter( ) function calculates the perimeter of the obj_expr object. The
Perimeter( ) function is defined for the following object types: ellipses, rectangles, rounded
rectangles, and polygons. Other types of objects have perimeter measurements of zero.
The CartesianPerimeter( ) function will always return a value using a cartesian algorithm. A
value of -1 will be returned for data that is in a Latitude/longitude coodinate system, since
Latitude/Longitude data is not projected and not cartesian.
Returns a length measurement in the units specified by the unit_name parameter; for example,
to obtain a length in miles, specify ”mi” as the unit_name parameter. See the Set Distance
Units statement for the list of valid unit names. Returns approximate results when used on
rounded rectangles. MapBasic calculates the perimeter of a rounded rectangle as if the object
were a conventional rectangle.
Example
The following example shows how you can use the CartesianPerimeter( ) function to
determine the perimeter of a particular geographic object.
Dim perim As Float
Open Table ”world”
Fetch First From world
perim = CartesianPerimeter(world.obj, ”km”)
’ The variable perim now contains
’ the perimeter of the polygon that’s attached to
’ the first record in the World table.
You can also use the CartesianPerimeter( ) function within the SQL Select statement. The
following Select statement extracts information from the States table, and stores the results in a
temporary table called Results. Because the Select statement includes the
CartesianPerimeter( ) function, the Results table will include a column showing each state’s
perimeter.
Open Table ”states”
Select state, CartesianPerimeter(obj, ”mi”)
From states
Into results
See Also
CartesianPerimeter( ), SphericalPerimeter( ), Perimeter( )
Centroid( ) function
Purpose
Returns the centroid (center point) of an object.
Syntax
Centroid ( obj_expr )
obj_expr is an object expression
Return Value
Point object
Description
The Centroid( ) function returns a point object, which is located at the centroid of the specified
obj_expr object. A region’s centroid does not represent its center of mass. Instead, it represents
the location used for automatic labeling, geocoding, and placement of thematic pie and bar
charts. If you edit a map in reshape mode, you can reposition region centroids by dragging
them.
If the obj_expr parameter represents a point object, the Centroid( ) function returns the position
of the point. If the obj_expr parameter represents a line object, the Centroid( ) function returns
the point midway between the ends of the line.
If the obj_expr parameter represents a polyline object, the Centroid( ) function returns a point
located at the mid point of the middle segment of the polyline.
If the obj_expr parameter represents any other type of object, the Centroid( ) function returns a
point located at the true centroid of the original object. For rectangle, arc, text, and ellipse
objects, the centroid position is halfway between the upper and lower extents of the object, and
halfway between the left and right extents. For region objects, however, the centroid position is
always “on” the object in question, and therefore may not be located halfway between the
object’s extents.
Example
Dim pos As Object
Open Table ”world”
Fetch First From world
pos = Centroid(world.obj)
See Also
CentroidX( ), CentroidY( ), Alter Object statement
CentroidX( ) function
Purpose
Returns the x-coordinate of the centroid of an object.
Syntax
CentroidX( obj_expr )
obj_expr is an object expression
Return Value
Float
Description
The CentroidX( ) function returns the X coordinate (e.g., Longitude) component of the centroid
of the specified object. See the Centroid( ) function for a discussion of what the concept of a
centroid position means with respect to different types of graphical objects (lines vs. regions,
etc.).
The coordinate information is returned in MapBasic’s current coordinate system; by default,
MapBasic uses a longitude, latitude coordinate system. The Set CoordSys statement allows
you to change the coordinate system used.
Examples
The following example shows how the CentroidX( ) function can calculate the longitude of a
single geographic object.
Dim x As Float
Open Table ”world”
Fetch First From world
x = CentroidX(world.obj)
You can also use the CentroidX( ) function within the SQL Select statement. The following
Select statement extracts information from the World table, and stores the results in a
temporary table called Results. Because the Select statement includes the CentroidX( ) and
CentroidY( ) functions, the Results table will include columns which display the longitude and
latitude of the centroid of each country.
Open Table ”world”
Select country, CentroidX(obj), CentroidY(obj)
From world Into results
See Also
Centroid( ), CentroidY( ), Set CoordSys
CentroidY( ) function
Purpose
Returns the y-coordinate of the centroid of an object.
Syntax
CentroidY( obj _expr )
obj_expr is an object expression
Return Value
Float
Description
The CentroidY( ) function returns the Y-coordinate (e.g., latitude) component of the centroid of
the specified object. See the Centroid( ) function for a discussion of what the concept of a
centroid position means, with respect to different types of graphical objects (lines vs. regions,
etc.).
The coordinate information is returned in MapBasic’s current coordinate system; by default,
MapBasic uses a longitude, latitude coordinate system. The Set CoordSys statement allows
you to change the coordinate system used.
Example
Dim y As Float
Open Table ”world”
Fetch First From world
y = CentroidY(world.obj)
See Also
Centroid( ), CentroidX( ), Set CoordSys
CharSet clause
Purpose
Specifies which character set MapBasic uses for interpreting character codes.
Syntax
CharSet char_set
char_set is a String that identifies the name of a character set; see table below
Description
The CharSet clause specifies which character set MapBasic should use when reading or writing
files or tables. Note that CharSet is a clause, not a complete statement. Various file-related
statements, such as Open File, can incorporate optional CharSet clauses.
What Is A Character Set?
Every character on a computer keyboard corresponds to a numeric code. For example, the letter
“A” corresponds to the character code 65. A character set is a set of characters that appear on a
computer, and a set of numeric codes that correspond to those characters.
Different character sets are used in different countries. For example, in the version of Windows
for North America and Western Europe, character code 176 corresponds to a degrees symbol;
however, if Windows is configured to use a different character set, character code 176 may
represent a different character. Furthermore, different types of computer systems use different
character sets. On a Windows system, character code 176 may correspond to the degrees
symbol, but on a Macintosh system, character code 176 represents a different character.
Call SystemInfo(SYS_INFO_CHARSET) to determine the character set in use at run-time.
How Do Character Sets Affect MapBasic Programs?
If your files use only standard ASCII characters in the range of 32 (space) to 126 (tilde), you do
not need to worry about character set conflicts, and you do not need to use the CharSet clause.
Even if your files include “special” characters (i.e. characters outside the range 32 to 126), if you
do all of your work within one environment (e.g., Windows) using only one character set, you
do not need to use the CharSet clause.
If your program needs to read an existing file that contains “special” characters, and if the file
was created in a character set that does not match the character set in use when you run your
program, your program should use the CharSet clause. The CharSet clause should indicate
what character set was in use when the file was created.
The CharSet clause takes one parameter: a String expression which identifies the name of the
character set to use. The following table lists all character sets available.
ChooseProjection$( ) function
Purpose
Displays the Choose Projection dialog and returns the coordinate system selected by the user.
Syntax
ChooseProjection$( initial_coordsys, get_bounds )
initial_coordsys is a string value in the form of a Coordsys clause. It is used to set which
coordinate system is selected when the dialog is first displayed. If initial_coordsys is empty or
an invalid coordsys clause, then the default longitude-latitude coordinate system is used as the
initial selection.
get_bounds is a logical value that determines whether the users is prompted for boundary
values when a non-earth projection is selected. If get_bounds is true then the boundary dialog
is displayed. If false, then the dialog is not displayed and the default boundary is used.
Description
This function displays the Choose Projection dialog and returns the selected coordinate system
as a string. The returned string is in the same format as the CoordSys clause. Use this function if
you wish to allow the user to set a projection within your application.
Example
Dim strNewCoordSys As String
Chr$( ) function
Purpose
Returns a one-character string corresponding to a specified character code.
Syntax
Chr$( num_expr )
num_expr is an Integer value from 0 to 255 (or, if a double-byte character set is in use, from 0 to
65,535), inclusive
Return Value
String
Description
The Chr$( ) function returns a string, one character long, based on the character code specified
in the num_expr parameter. On most systems, num_expr should be a positive Integer value
between 0 and 255. On systems that support double-byte character sets (e.g., Windows
Japanese), num_expr can have a value from 0 to 65,535.
Note: All MapInfo Professional environments have common character codes within the range
of 32 (space) to 126 (tilde).
If the num_expr parameter is fractional, MapBasic rounds to the nearest integer.
Character 12 is the form-feed character. Thus, you can use the statement Print Chr$(12) to clear
the Message window. Character 10 is the line-feed character; see example below.
Character 34 is the double-quotation mark (”). If a string expression includes the function call
Chr$(34), MapBasic embeds a double-quote character in the string.
Error Conditions
ERR_FCN_ARG_RANGE error generated if an argument is outside of the valid range
Example
Dim s_letter As String * 1
s_letter = Chr$(65)
Note s_letter ’ This displays the letter ”A”
Note ”This message spans” + Chr$(10) + ”two lines.”
See Also
Asc( )
ColumnInfo( ) function
Purpose
Returns information about a column in an open table.
Syntax
ColumnInfo ( { tablename | tablenum } ,
{ columnname | “COLn”} ,
attribute )
tablename is a string representing the name of an open table
tablenum is an integer representing the number of an open table
columnname is the name of a column in that table
n is the number of a column in the table
attribute is a code indicating which aspect of the column to read
Return Value
Depends on the attribute parameter specified
Description
The ColumnInfo( ) function returns information about one column in an open table.
The function’s first parameter specifies either the name or the number of an open table. The
second parameter specifies which column to query. The attribute parameter dictates which of
the column’s attributes the function should return. The attribute parameter can be any value
from the table below.
Combine( ) function
Purpose
Returns a region or polyline representing the union of two objects. The objects cannot be Text
objects
Syntax
Combine ( object1, object2 )
object1, object2 are two object expressions; both objects can be closed (e.g., a region and a circle),
or both objects can be linear (e.g., a line and a polyline)
Return Value
An object that is the union of object1 and object2.
Description
The Combine( ) function returns an object representing the geographical union of two object
expressions. The union of two objects represents the entire area that is covered by either object.
The Combine() MapBasic function has been updated to allow heterogeneous combines, and to
allow Points, MultiPoints, and Collections as input objects. Previously, both objects had to be
either linear objects (Lines, Polylines, or Arcs) and produce Polylines as output; or both input
objects had to be closed (Regions, Rectangles, Rounded Rectangles, or Ellipses) and produce
Regions as output. Heterogeneous combines are not allowed, as are combines containing Point,
MultiPoint and Collection objects. Text objects are still not allowed as input to Combine( ).
MultiPoint and Collection objects, introduced in MapInfo Professional 6.5, extend the Combine
operation. The following table details the possible combine options available and the output
results:
CommandInfo( ) function
Purpose
Returns information about recent events.
Syntax
CommandInfo( attribute )
attribute is an Integer code indicating what type of information to return
Return Value
Logical, Float, Integer, or String, depending on circumstances
Description
The CommandInfo( ) function returns information about recent events that affect MapInfo
Professional—for example, whether the “Selection” table has changed, where the user clicked
with the mouse, or whether it was a simple click or a “shift click.”
After Displaying a Dialog Box
When you call CommandInfo( ) after displaying a custom dialog box, the attribute parameter
can be one of these codes:
Hotlink Support
MapBasic applications launched via the Hotlink Tool can use the CommandInfo function to
obtain information about the object that was activated. The following is a table of the attributes
that can be queried:
See Also
FrontWindow( ), SelectionInfo( ), Set Command Info, WindowInfo( )
To save the table under a new name, specify the new name in the filespec string. To save the
table in a new directory path, specify the directory path at the start of the filespec string.
To save the table using a new file type, include a Type clause within the As clause. By default,
the type of the new table is NATIVE, but can also be saved as DBF.
The CharSet clause specifies a character set. The char_set parameter should be a string constant,
such as “MacRoman” or “WindowsLatin1”. If no CharSet clause is specified, MapBasic uses
the default character set for the hardware platform that is in use at runtime. See the discussion
of the CharSet clause for more information.
To save the table using a different coordinate system or projection, include a CoordSys clause
within the As clause. Note that only a mappable table may have a coordinate system or a
projection.
To save a Query use the QUERY type for the table. Only queries made from the user interface
and queries created from Run Command statements in MapBasic can be saved. The Commit
Table statement will create a .TAB file and a .QRY file.
The Version clause controls the table’s format. If you specify Version 100, MI Pro stores the
table in a format readable by versions of MI Pro. If you specify Version 300, MI Pro stores the
table in MI Pro 3.0 format. Note that region and polyline objects having more than 8,000 nodes
and multiple-segment polyline objects require version 300. If you omit the Version clause, the
table is saved in the version 300 format.
Note: If a MapBasic application issues a Commit Table...As statement affecting a table which
has memo fields, the memo fields will not be retained in the new table. No warning will
be displayed. If the table is saved to a new table through MI Pro’s user interface (by
choosing File > Save Copy As), MI Pro warns the user about the loss of the memo fields.
However, when the table is saved to a new table name through a MapBasic program, no
warning appears.
Saving Linked Tables
Saving a linked table can generate a conflict, when another user may have edits the same data
in the same table MI Pro will detect if there were any conflicts and allows the user to resolve
them. The following clauses let you control what happens when there is a conflict. (These
clauses have no effect on saving a conventional MapInfo table.)
Interactive
In the event of a conflict, MI Pro displays the Conflict Resolution dialog. After a successful
Commit Table Interactive statement, MI Pro displays a dialog allowing the user to refresh.
Automatic NoCollision
In the event of a conflict, MI Pro does not perform the save. (This is the default behavior if the
statement does not include an Interactive clause or an Automatic clause.)
Automatic ApplyUpdates
In the event of a conflict, MI Pro saves the local updates. (This is analogous to ignoring conflicts
entirely.)
Automatic DiscardUpdates
In the event of a conflict, MI Pro saves the local updates already in the RDBMS (discards your
local updates).
You can copy a linked table by using the As clause; however, the new copy is not a linked table
and no changes are updated to the server.
ODBC Connection
The length of tablename varies with databases. We recommend 14 or fewer characters for a table
name in order to work correctly for all databases. The statement limits the length of the
tablename to a maximum of 31 characters.
If the AS clause is used and ODBC is the Type, a copy of the table will be saved on the database
specifed by ConnectionNumber and named as tablename. If the source table is mappable, three
more columns, Key column, Object column, and Style column, may be added to the
destination database table, tablename, whether or not the source table has those columns. If the
source table is not mappable, one more column, Key column, may be added to the database
table, tablename, even if the source table does not have a Key column. The Key column will be
used to create a unique index.
A spatial index will be created on the Object column if one is present. Unsupported object types
will not be saved to the destination table, but the rest of the attributes will be saved. The
supported databases include Oracle, SQL Server, IIS (Informix Universal Server), and Microsoft
Access. However, to save a table with a spatial geometry/object, (including saving a point-only
table) the SpatialWare/Blade is required for SQL Server and IUS, in addition to the spatial
option for Oracle. The XY schema is not supported in this statement.
Example
The following example opens the table STATES, then uses the Commit statement to make a
copy of the states table under a new name (ALBERS). The optional CoordSys clause causes the
ALBERS table to be saved using the Albers equal-area projection.
Open Table ”STATES”
Commit Table STATES
As ”ALBERS”
CoordSys Earth
Projection 9,7, ”m”, -96.0, 23.0, 20.0, 60.0, 0.0, 0.0
The following example illustrates an ODBC connection:
dim hodbc as integer
hodbc = server_connect("ODBC", "dlg=1")
Open table "C:\MapInfo\USA"
Commit Table USA
as "c:\temp\as\USA"
Type ODBC Connection hodbc Table "USA"
See Also
Rollback
Continue statement
Purpose
Resumes the execution of a MapBasic program (following a Stop statement).
Syntax
Continue
Restrictions
The Continue statement may only be issued from the MapBasic window; it may not be
included as part of a compiled program.
Description
The Continue statement resumes the execution of a MapBasic application which was
suspended because of a Stop statement.
You can include Stop statements in a program for debugging purposes. When a MapBasic
program encounters a Stop statement, the program is suspended, and the File menu
automatically changes to include a Continue Program option instead of a Run option. You can
resume the suspended application by choosing File > Continue Program. Typing the Continue
statement into the MapBasic window has the same effect as choosing Continue Program.
The first call to ReadControlValue( ) returns the number of the first selected item; the second
call to ReadControlValue( ) returns the number of the second selected item; etc. When
ReadControlValue( ) returns zero, you have exhausted the list of selected items. If the first call
to ReadControlValue( ) returns zero, there are no list items selected.
Processing Double-click events
If you assign a handler procedure to a list control, MapBasic calls the procedure every time the
user clicks or double-clicks an item in the list. In some cases, you may want to provide special
handling for double-click events. For example, when the user double-clicks a list item, you may
want to dismiss the dialog as if the user had clicked on a list item and then clicked OK.
To see an example, click here: Letting the user double-click
To determine whether the user clicked or double-clicked, call the CommandInfo( ) function
within the list control’s handler procedure, as shown in the following sample handler
procedure:
Sub lb_handler
Dim i As SmallInt
If CommandInfo(CMD_INFO_DLG_DBL) Then
’ ... then the user double-clicked.
i = ReadControlValue( TriggerControl( ) )
Dialog Remove
’ at this point, the variable i represents
’ the selected list item...
End If
End Sub
Example
Control ListBox
Title ”1st Quarter;2nd Quarter;3rd Quarter;4th Quarter”
ID 3
Value 1
Into i_quarter
Position 10, 92 Height 40
See Also
Alter Control, Dialog, ReadControlValue( )
Into i_map_scope
Position 10, 150
See Also
Alter Control, Dialog, ReadControlValue( )
Calling rg_handler
Position 15, 42
See Also
Alter Control, Dialog, ReadControlValue( )
ConvertToPline( ) function
Purpose
Returns a polyline object that approximates the shape of another object.
Syntax
ConvertToPline( object )
object is the object to convert; may not be a point object or a text object
Return Value
A polyline object
Description
The ConvertToPline( ) function returns a polyline object which approximates the object
parameter. Thus, if the object parameter represents a region object, ConvertToPline( ) returns a
polyline that has the same shape and same number of nodes as the region.
The results obtained by calling ConvertToPline( ) are similar to the results obtained by
choosing MapInfo Professional’s Objects > Convert To Polyline command. However, the
function ConvertToPline( ) does not alter the original object.
See Also
ObjectsEnclose
ConvertToRegion( ) function
Purpose
Returns a region object that approximates the shape of another object.
Syntax
ConvertToRegion ( object )
object is the object to convert; may not be a point, line, or text object
Return Value
A region object
Description
Retains most style attributes. Other attributes are determined by the current pens or brushes. A
polyline whose first and last nodes are identical will not have the last node duplicated.
Otherwise, MapInfo Professional adds a last node whose vertices are the same as the first node.
The ConvertToRegion( ) function returns a region object which approximates the object
parameter. Thus, if the object parameter represents a rectangle, ConvertToRegion( ) returns a
region that looks like a rectangle.
The results obtained by calling ConvertToRegion( ) are similar to the results obtained by
choosing MapInfo Professional’s Objects > Convert To Region command. However, the
ConvertToRegion( ) function does not alter the original object.
See Also
ObjectsEnclose
ConvexHull( ) function
Purpose
Returns a region object that represents the convex hull polygon based on the nodes from the
input object. The convex hull polygon can be thought of as an operator that places a rubber
band around all of the points. It will consist of the minimal set of points such that all other
points lie on or inside the polygon. The polygon will be convex - no interior angle can be
greater than 180 degrees.
Syntax
ConvexHull ( inputobject)
inputobject is an object expression.
Return Value
Returns a region object.
Description
The ConvexHull() function returns a region representing the convex hull of the set of points
comprising the input object. The ConvexHull() function operates on one single object at a time.
To create a convex hull around a set of objects, use the Create Object As ConvexHull
statement.
Example
The following program selects New York from the States file, then creates a ConvexHull
surrounding the selection.
Dim Resulting_object as object
select * from States
where State_Name = ”New York”
Resulting_object = ConvexHull(selection.obj)
Insert Into States(obj) Values (Resulting_object)
See Also:
Create Object
CoordSys clause
Purpose
Specifies a coordinate system.
Syntax1
CoordSys Earth
[ Projection type,
datum,
unitname
[ , origin_longitude]
[ , origin_latitude ]
[ , standard_parallel_1 [ , standard_parallel_2 ] ]
[ , azimuth ]
[ , scale_factor ]
[ , false_easting ]
[ , false_northing ]
[ , range ] ]
[ Affine Units unitname, A, B C, D, E, F ]
[ Bounds ( minx, miny) ( maxx, maxy) ]
Syntax2
CoordSys Nonearth
[ Affine Units unitname, A, B C, D, E, F ]
Units unitname
Bounds ( minx, miny) ( maxx, maxy)
Syntax3
CoordSys Layout Units paperunitname
Syntax4
CoordSys Table tablename
Syntax5
CoordSys Window window_id
type is a positive integer value representing which coordinate system to use
datum is a positive integer value identifying which datum to reference
unitname is a string representing a distance unit of measure (e.g., “m” for meters); for a list of
unit names, see Set Distance Units
origin_longitude is a float longitude value, in degrees
origin_latitude is a float latitude value, in degrees
standard_parallel_1 and standard_parallel_2 are float latitude values, in degrees
azimuth is a float angle measurement, in degrees
scale_factor is a float scale factor
range is a float value from 1 to 180, dictating how much of the Earth will be seen
minx is a float specifying the minimum x value
miny is a float specifying the minimum y value
maxx is a float specifying the maximum x value
maxy is a float specifying the maximum y value
paperunitname is a string representing a paper unit of measure (e.g., “in” for inches); for a list of
unit names, see Set Paper Units
The Bounds clause defines the map’s limits; objects may not be created outside of those limits.
When specifying an Earth coordinate system, you may omit the Bounds clause, in which case
MI Pro uses default bounds that encompass the entire Earth.
Note: In a Create Map statement, you can increase the precision of the coordinates in the map
by specifying narrower Bounds.
Every map projection is defined as an equation; and since the different projection equations
have different sets of parameters, different CoordSys clauses may have varying numbers of
parameters in the optional Projection clause. For example, the formula for a Robinson
projection uses the Datum, Units, and Origin Latitude parameters, while the formula for a
Transverse Mercator projection uses the Datum, Units, Origin Longitude, Origin Latitude, Scale
Factor, False Easting, and False Northing parameters.
For more information on projections and coordinate systems, see the MapInfo Professional
documentation.
Each MapBasic application has its own CoordSys setting that specifies the coordinate system
used by the application. If a MapBasic application issues a Set CoordSys statement, other
MapBasic applications which are also in use will not be affected.
Examples
The Set Map statement controls the settings of an existing Map window. The Set Map
statement below tells MI Pro to display the Map window using the Robinson projection:
Set Map CoordSys Earth Projection 12, 12, ”m”, 0.
The first 12 specifies the Robinson projection; the second 12 specifies the Sphere datum; the
“m” specifies that the coordinate system should use meters; and the final zero specifies that the
origin of the map should be at zero degrees longitude.
The following statement tells MI Pro to display the Map window without any projection.
Set Map CoordSys Earth
The following example opens the table World, then uses a Commit statement to save a copy of
World under the name RWorld. The new RWorld table will be saved with the Robinson
projection.
Open Table ”world” As World
Commit Table world As ”RWORLD.TAB”
CoordSys Earth Projection 12, 12, ”m”, 0.
The following example sets one Map window’s projection to match the projection of another
Map window. This example assumes that two Integer variables (first_map_id and
second_map_id) already contain the window IDs of the two Map windows.
Set Map
Window second_map_winid
CoordSys Window first_map_winid
The following example defines a coordinate system called DCS that is derived from UTM Zone
10 coordinate system using the affine transformation
x1 = 1.57x - 0.21y + 84120.5
CoordSys Earth
Projection 8, 74, ”m”, -123, 0, 0.9996, 500000, 0
Affine Units ”ft”, 1.57, -0.21, 84120.5, 0.19, 2.81, -20318.0
See Also
Commit Table, Set CoordSys, Set Map
Cos( ) function
Purpose
Returns the cosine of a number.
Syntax
Cos ( num_expr )
num_expr is a numeric expression representing an angle in radians
Return Value
Float
Description
The Cos( ) function returns the cosine of the numeric num_expr value, which represents an
angle in radians. The result returned from Cos( ) will be between one and minus one.
To convert a degree value to radians, multiply that value by DEG_2_RAD. To convert a radian
value into degrees, multiply that value by RAD_2_DEG. (Note that your program will need to
Include “MAPBASIC.DEF” in order to reference DEG_2_RAD or RAD_2_DEG).
Example
Include ”MAPBASIC.DEF”
Dim x, y As Float
x = 60 * DEG_2_RAD
y = Cos(x)
DrawMode dm_code specifies whether the user can click and drag, or only click with the tool;
dm_code is a code (e.g., DM_CUSTOM_LINE) from ICONS.DEF. DrawMode clause applies
only to ToolButtons.
HelpMsg msg specifies the button’s status bar help and, optionally, ToolTip help. The first part
of the msg string is the status bar help message. If the msg string includes the letters \n then the
text following the \n is used as the button’s ToolTip help.
ModifierKeys clause controls whether the shift and control keys affect “rubber-band”
drawing if the user drags the mouse while using a ToolButton. Default is Off, meaning that the
shift and control keys have no effect.
Description
Use the Create ButtonPad statement to create a custom ButtonPad. Once you have created a
custom ButtonPad, you can modify it using Alter Button and Alter ButtonPad statements.
Each toolbar can be hidden. To create a toolbar in the hidden state, include the Hide
keyword.Each toolbar can be floating or fixed to the top of the screen (“docked”). A floating
toolbar resembles a window, such as the Info tool window. To create a fixed toolbar, include the
keyword Fixed. To create a floating toolbar, include the keyword Float. When a toolbar is
floating, its position is controlled by the Position clause; when it is docked, its position is
controlled by the ToolbarPosition clause.
For more information on ButtonPads, see the MapBasic User’s Guide. For additional
information about the capabilities of ToolButtons, see Alter ButtonPad.
Calling Clause Options
The Calling clause specifies what should happen when the user acts on the custom button. The
following table describes the available syntax.
Example
Create ButtonPad ”Utils” As
PushButton
HelpMsg ”Choose this button to display query dialog”
Calling button_sub_proc
Icon MI_ICON_ZOOM_QUESTION
ToolButton
HelpMsg ”Use this tool to draw a new route”
Calling tool_sub_proc
Icon MI_ICON_CROSSHAIR
DrawMode DM_CUSTOM_LINE
ToggleButton
HelpMsg ”Turn proximity checking on/off”
Calling toggle_prox_check
Icon MI_ICON_RULER
Check
Title ”Utilities”
Width 3
Show
See Also
Alter Button, Alter ButtonPad
The Position, Title, SubTitle, Border Pen, and Style clauses at the frame level are used only for
map layers. They are not used for thematic layers. For a thematic layer, this information is
gotten automatically from the theme.
The Font clause specifies a text style. If a default frame title, subtitle or style name font is
defined, then it will become the default for the frame. If a frame level title, subtitle or style
clause exists and includes a font clause, then the frame level font will be used. If no font is
specified at any level, then the current text style is used and the point sizes are 10, 9 and 8 for
title, subtitle and style name respectively.
The Style clause and the NoRefresh keyword allow you to create custom frames that will not
be overwritten when the legend is refreshed. If the NoRefresh keyword is used in the Style
clause, then the table is not scanned for styles. Instead, the Style clause must contain your
custom list of definitions for the styles displayed in the frame. This is done with the Text clause
and appropriate Line, Region, or Symbol clause. Multipoint objects are treated as Point
objects.
Collection objects are treated separately. When we create Legend based on object types, we
draw Point symbols first, then Lines, then Regions. Collection objects are drawn last. Inside
collection objects we draw point, then line and then region samples.
If a Column is defined, it must be an attribute column name from the frame layer’s table, or the
’object’ column (meaning that legend styles are based on the unique styles in the mapfile). The
default is ’object’.
If a Label is defined, it is either a valid expression or ’default’ (meaning that the default frame
style pattern is used when creating each style’s text, unless the style clause contains text). The
default is default.
Initially, each frame layer’s TAB file will be searched for metadata values for Title, Subtitle,
Column and Label. If no metadata value exists for Column, the default is object. If no metadata
value exists for Label, the default is the default frame style pattern.
If legend metadata keys exist and you want to override them, you must use the corresponding
mapbasic syntax.
Example
The following example shows how to create a frame for a Map window's Cartographic legend.
Legend windows are a special case: To create a frame for a Legend window, you must use the
Title clause instead of the From Window clause.
Dim i_layout_id, i_map_id As Integer
Dim s_title As String
This will create a frame for a Cartographic legend window. To create a frame for a thematic
legend window, change the title to the following.
S_title="Theme Legend of " + WindowInfo (I_map_id, WW_INFO_NAME)
See Also
Set Cartographic Legend, Alter Cartographic Frame, Add Cartographic Frame, Remove
Cartographic Frame, Create Legend, Set Window, WindowInfo()
CreateCircle( ) function
Purpose
Returns an Object value representing a circle.
Syntax
CreateCircle( x , y , radius )
x is a Float value, indicating the x-position (e.g., Longitude) of the circle’s center
y is a Float value, indicating the y-position (e.g., Latitude) of the circle’s center
radius is a Float value, indicating the circle radius
Return Value
Object
Description
The CreateCircle( ) function returns an Object value representing a circle.
The x and y parameters use whatever coordinate system MapBasic is currently using. By
default, MapBasic uses a longitude, latitude coordinate system, although the Set CoordSys
statement can re-configure MapBasic to use a different coordinate system.
Note: MapBasic’s coordinate system is independent of the coordinate system of any Map
window.
The radius parameter specifies the circle radius, in whatever distance unit MapBasic is currently
using. By default, MapBasic uses miles as the distance unit, although the Set Distance Units
statement can re-configure MapBasic to use a different distance unit.
The circle will use whatever Brush style is currently selected. To create a circle object with a
specific Brush, you could issue the Set Style statement before calling CreateCircle( ).
Alternately, instead of calling CreateCircle( ), you could issue a Create Ellipse statement,
which has optional Pen and Brush clauses.
The circle object created through the CreateCircle( ) function could be assigned to an Object
variable, stored in an existing row of a table (through the Update statement), or inserted into a
new row of a table (through an Insert statement).
Note: Before creating objects on a Layout window, you must issue a Set CoordSys Layout
statement.
Error Conditions
ERR_FCN_ARG_RANGE error generated if an argument is outside of the valid range
Examples
The following example uses the Insert statement to insert a new row into the table Sites. The
CreateCircle( ) function is used within the body of the Insert statement to specify the graphic
object that will be attached to the new row.
Open Table ”sites”
Insert Into sites (obj)
Values ( CreateCircle(-72.5, 42.4, 20) )
The following example assumes that the table Towers has three columns: Xcoord, Ycoord, and
Radius. The Xcoord column contains longitude values, the Ycoord column contains latitude
values, and the Radius column contains radius values. Each row in the table describes a radio
broadcast tower, and the Radius column indicates each tower’s broadcast area.
The Update statement uses the CreateCircle( ) function to build a circle object for each row in
the table. Following this Update statement, each row in the Towers table will have a circle
object attached. Each circle object will have a radius derived from the Radius column, and each
circle will be centered at the position indicated by the Xcoord, Ycoord columns.
Open Table ”towers”
Update towers
Set obj = CreateCircle(xcoord, ycoord, radius)
See Also
Create Ellipse, Insert, Update
dim a as object
create collection into variable a multipoint 2 (0,0) (1,1) region 1 3
(1,1) (2,2) (3,4) pline 3 (-1,1) (3,-2) (4,3)
insert into test (obj) values (a)
Example
The following examples show how to create a frame for a Map window’s thematic legend, or
cartographic legend window.
Theme Legend windows are a special case. To create a frame for a Theme Legend window, you
must use the Title clause instead of the From Window clause.:
Dim i_layout_id, i_map_id As Integer
Dim s_title As String
Create Frame
Into Window i_layout_id
(1,2) (4, 5)
From Window i_cartlgnd_id
See Also
Brush, Insert, Layout, Pen, Set CoordSys, Set Layout, Update
create grid
from Us_elev
with Elevation_FT
into ”C:\Us_elev_grid”
clipping table States
inflect 5 at
RGB(0, 0, 255) : 13
RGB(0, 255, 255) : 3632.5
RGB(0, 255, 0) : 7252
RGB(255, 255, 0) : 10871.5
RGB(255, 0, 0) : 14491
cell min 200
interpolate
with ”IDW” version ”100”
using 4
”EXPONENT”: ”2”
”MAX POINTS”: ”25”
”MIN POINTS”: ”1”
”SEARCH RADIUS”: ”100”
See Also
Set Map
CreateLine( ) function
Purpose
Returns an Object value representing a line.
Syntax
CreateLine( x1 , y1, x2 , y2 )
x1 is a Float value, indicating the x-position (e.g., Longitude) of the line’s starting point
y1 is a Float value, indicating the y-position (e.g., Latitude) of the line’s starting point
x2 is a Float value, indicating the x-position of the line’s ending point
y2 is a Float value, indicating the y-position of the line’s ending point
Return Value
Object
Description
The CreateLine( ) function returns an Object value representing a line. The x and y parameters
use the current coordinate system. By default, MapBasic uses a longitude, latitude coordinate
system. Use the Set CoordSys statement to choose a new system.
The line object will use whatever Pen style is currently selected. To create a line object with a
specific Pen style, you could issue the Set Style statement before calling CreateLine( ) or you
could issue a Create Line statement, with an optional Pen clause.
The line object created through the CreateLine( ) function could be assigned to an Object
variable, stored in an existing row of a table (through the Update statement), or inserted into a
new row of a table (through an Insert statement). If you need to create objects on a Layout
window, you must first issue a Set CoordSys Layout statement.
Example
The following example uses the Insert statement to insert a new row into the table Routes. The
CreateLine( ) function is used within the body of the Insert statement.
Open Table ”Routes”
Insert Into routes (obj)
Values (CreateLine(-72.55, 42.431, -72.568, 42.435))
See Also
Create Line, Insert, Update
Provide the name of an already open mappable table as the from_table portion of the Using
clause. In this case, the coordinate system used will be identical to that used in the
from_table. The from_table must be a currently open table, and must be mappable or an
error will occur.
Explicitly supply the coordinate system information through a CoordSys clause (set in
preferences).
If you omit both the CoordSys clause and the Using clause, the table will use the current
MapBasic coordinate system.
Note that the CoordSys clause affects the precision of the map. The CoordSys clause includes a
Bounds clause, which sets limits on the minimum and maximum coordinates that can be stored
in the map. If you omit the Bounds clause, MapInfo Professional uses default bounds that
encompass the entire Earth (in which case, coordinates are precise to one millionth of a degree,
or approximately 4 inches). If you know in advance that the map you are creating will be
limited to a finite area (e.g., a specific metropolitan area), you can increase the precision of the
map's coordinates by specifying bounds that confine the map to that area.
For a complete listing of the CoordSys syntax, see the separate discussion of the CoordSys
clause.
See Also
Commit, CoordSys, Create Table, Drop Map, Map, Server Create Map, Set Map
Description
Once it is created, the 3DMap window is a standalone window. Since it is based on the same
tables as the original Map window, if these tables are changed and the 3DMap window is
manually “refreshed” or re-created from a workspace, these changes will be displayed on the
grid.
The creation will fail if the window_id is not a Map window or if the Map window does not
contain a Grid layer. If there are multiple grids in the Map window, each will be represented in
the 3DMap window.
A 3DMap keeps a Mapper creation string as its texture generator. This string will also be
prevalent in the workspace when the 3DMap window is persisted. The initialization will read
in the grid layer to create 3D geometry and topology objects.
Example
Create Map3D Resolution(75,75)
Creates a 3DMap window of the most recent Map window. It will fail if the window does not
contain any Continuous Grid layers. Another example is:
Create Map3D From Window FrontWindow() Resolution(100,100) Scale 2
Background RGB(255,0,0) Units “ft”.
Creates a 3DMap window with a Red background, the z units set to feet, a Z scale factor of 2,
and the grid resolution set to 100x100.
See Also
Set Map3D statement
but not all, of the custom menus that your application has added, you can issue a
statement of the form Create Menu menuname As Default.
After altering a standard MI Pro menu (e.g., “File”), you can restore the menu to its original
state by issuing a Create Menu menuname As Default statement.
Calling Clause Options
The Calling clause specifies what should happen when the user chooses the custom menu
command. The following table describes the available syntax.
Sub Main
Create Menu ”DataEntry” As
”Add” Calling addsub,
”Edit” Calling editsub,
”Delete” Calling delsub
The following example creates an abbreviated version of the File menu. The “(” control
character specifies that the Close, Save, and Print options will be disabled initially. The Open
and Save options have Windows accelerator key sequences (Ctrl+O and Ctrl+S, respectively).
Note that both the Open and Save options use the function Chr$(9) to insert a Tab character into
the menu item name, so that the remaining text is shifted to the right.
Include ”MENU.DEF”
If you want to prevent the user from having access to MI Pro’s shortcut menus, use a Create
Menu statement to re-create the appropriate menu, and define the menu as just a separator
control code: “(-”. The following example uses this technique to disable the Map window’s
shortcut menu.
Create Menu ”MapperShortcut” As ”(-”
See Also
Create Menu Bar, Alter Menu Item
The following example creates a custom menu, called DataEntry, and then redefines the menu
bar so that it includes only the File, Edit, and DataEntry menus.
Declare Sub AddSub
Declare Sub EditSub
Declare Sub DelSub
Syntax:
Create Multipoint
[ Into { Window window_id | Variable var_name } ]
[ num_points ]
( x1, y1) ( x2, y2) [ ... ]
[ Symbol . . . ]
window_id is a window identifier
var_name is the name of an existing object variable
num_points - number of points inside Multipoint object.
x y specifies the location of the point
The Symbol clause specifies a symbol style. NOTE: one symbol is used for all points contained
in a Multipoint object.
Currently MapInfo Professional uses the following four different syntaxes to define a symbol
used for points:
Syntax 4
Symbol symbol_expr
symbol_expr is a Symbol expression, which can either be the name of a Symbol variable, or a
function call that returns a Symbol value, e.g., MakeSymbol
Example:
Create Multipoint 7 (0,0) (1,1) (2,2) (3,4) (-1,1) (3,-2) (4,3)
The union and merge operations are similar, but they behave very differently in cases where
objects are completely contained within other objects. In this case, the merge operation removes
the area of the smaller object from the larger object, leaving a hole where the smaller object was.
The union operation does not remove the area of the smaller object.
Create Objects As Union is similar to the Objects Combine statement. Objects Combine will
delete the input and insert a new combined object. Create Objects As Union will only insert the
new combined object, it will not delete the input objects. Combining using a Target and
potentially different tables is only available with Objects Combine. The Combine Objects using
Column functionality is only available using Create Objects As Union using the Group By
clause.
If a Create Object As Union statement does not include a Group By clause, MapInfo
Professional creates one combined object for all objects in the table. If the statement includes a
Group By clause, it must name a column in the table to allow MI Pro to group the source objects
according to the contents of the column and produce a combined object for each group of
objects.
If you specify a Group By clause, MI Pro groups all records sharing the same value, and
performs an operation (e.g., merge) on the group.
If you specify a Data clause, MI Pro performs data aggregation. For example, if you perform
merge or union operations, you may want to use the Data clause to assign data values based on
the Sum( ) or Avg( ) aggregate functions.
Use Type is the method used to calculate the buffer width around the object. It can either be
Spherical or Cartesian. Note that if the Coordsys of the intotable is NonEarth, then the
calculations will be performed using Cartesian methods regardless of the option chosen, and if
the Coordsys of the intotable is Latitude/Longitude, then calculations will be performed using
Spherical methods regardless of the option chosen.
Convex Hull Geographic Operation for the Create Object statement
Create Object As { Buffer |Union | Intersect | Merge | ConvexHull }
The Create Object statement creates one or more new region objects, by performing a
geographic operation (Buffer, Merge, Intersect, Union, or ConvexHull) on one or more
existing objects.
The ConvexHull operator will create a polygon representing a convex hull around a set of
points. The convex hull polygon can be thought of as an operator that places a rubber band
around all of the points. It will consist of the minimal set of points such that all other points lie
on or inside the polygon. The polygon will be convex—no interior angle can be greater than
180 degrees.
The points used to construct the convex hull will be any nodes from Regions, Polylines, or
Points in the From table. If a Create Object As ConvexHull statement does not include a
Group By clause, MI Pro creates one convex hull polygon. If the statement includes a Group By
clause that names a column in the table, MI Pro groups the source objects according to the
contents of the column, then creates one convex hull polygon for each group of objects. If the
statement includes a Group By RowID clause, MI Pro creates one convex hull polygon for each
object in the source table.
Buffering
If the Create Object statement performs a Buffer operation, the statement can include Width
and Resolution clauses. The Width clause specifies the width of the buffer. The optional Units
sub-clause lets you specify a distance unit name (such as “km” for kilometers) to apply to the
Width clause. If the Width clause does not include the Units sub-clause, the buffer width will
be interpreted in MapBasic’s current distance unit. By default, MapBasic uses miles as the
distance unit; to change this unit, see the Set Distance Units statement.
The optional Type sub-clause lets you specify the type of distance calculation used to create the
buffer. If the Spherical type is used, then the calculation will be done by mapping the data into
a Latitude/Longitude On Earth projection and using widths measured using Spherical
distance calculations. If the Cartesian type is used, then the calculation is done by considering
the data to be projected to a flat surface and widths are measured using cartesian distance
calculations. If the Width clause does not include the Type sub-clause, then the default distance
calculation type Spherical is used. If the data is in a Latitude/Longitude Projection, then
Sperical calculations will be used regardless of the Type setting. If the data is in a NonEarth
Projection, the Cartesian calculations will be used regardless of the Type setting.
The smoothness parameter lets you specify the number of segments comprising each circle of the
buffer region. By default, a buffer object has a smoothness value of twelve, meaning that there
will be twelve segments in a simple ring-shaped buffer region. By specifying a larger
smoothness value, you can produce smoother buffer regions. Note, however, that the larger the
smoothness value, the longer the Create Object statement takes, and the more disk space the
resultant object occupies.
If a Create Object As Buffer statement does not include a Group By clause, MI Pro creates one
buffer region. If the statement includes a Group By clause which names a column in the table,
MI Pro groups the source objects according to the contents of the column, then creates one
buffer region for each group of objects. If the statement includes a Group By RowID clause, MI
Pro creates one buffer region for each object in the source table.
Voronoi
Specify Voronoi to create regions that represent the Voronoi solutions of the input points. The
data values from the original input points can be assigned to the resultant polygon for that
point by specifying data clauses.
Example
The following example merges region objects from the Parcels table, and stores the resultant
regions in the table Zones. Since the Create Object statement includes a Group By clause,
MapBasic will group the Parcel regions, then perform one merge operation for each group.
Thus, the Zones table will end up with one region object for each group of objects in the Parcels
table. Each group will consist of all parcels having the same value in the zone_id column.
Following the Create Object statement, the parcelcount column in the Zones table will indicate
how many parcels were merged to produce that zone. The zonevalue column in the Zones table
will indicate the sum of the values from the parcels that comprised that zone.
Open Table ”PARCELS”
Open Table ”ZONES”
Create Object As Merge
From PARCELS Into Table ZONES Data
parcelcount=Count(*),zonevalue=Sum(parcelvalue)
Group By zone_id
The next example creates a region object, representing a quarter-mile buffer around whatever
objects are currently selected. The buffer object will be stored in the Object variable, corridor. A
subsequent Update or Insert statement could then copy the object to a table.
CreatePoint( ) function
Purpose
Returns an Object value representing a point.
Syntax
CreatePoint( x , y )
x is a Float value, representing an x-position (e.g., Longitude)
y is a Float value, representing a y-position (e.g., Latitude)
Return Value
Object
Description
The CreatePoint( ) function returns an Object value representing a point.
The x and y parameters should use whatever coordinate system MapBasic is currently using.
By default, MapBasic uses a longitude, latitude coordinate system, although the Set CoordSys
statement can re-configure MapBasic to use a different coordinate system. Note that
MapBasic’s coordinate system is independent of the coordinate system of any Map window.
The point object will use whatever Symbol style is currently selected. To create a point object
with a specific Symbol style, you could issue the Set Style statement before calling
CreatePoint( ). Alternately, instead of calling CreatePoint( ), you could issue a Create Point
statement, which has an optional Symbol clause.
The point object created through the CreatePoint( ) function could be assigned to an Object
variable, stored in an existing row of a table (through the Update statement), or inserted into a
new row of a table (through an Insert statement).
Note: If you need to create objects on a Layout window, you must first issue a Set CoordSys
Layout statement.
Examples
The following example uses the Insert statement to insert a new row into the table Sites. The
CreatePoint() function is used within the body of the Insert statement to specify the graphic
object that will be attached to the new row.
Open Table ”sites”
Insert Into sites (obj)
Values ( CreatePoint(-72.5, 42.4) )
The following example assumes that the table Sites has Xcoord and Ycoord columns, which
indicate the longitude and latitude positions of the data. The Update statement uses the
CreatePoint( ) function to build a point object for each row in the table. Following the Update
operation, each row in the Sites table will have a point object attached. Each point object will be
located at the position indicated by the Xcoord, Ycoord columns.
Open Table ”sites”
Update sites
Set obj = CreatePoint(xcoord, ycoord)
The above example assumes that the Xcoord, Ycoord columns contain actual longitude and
latitude degree values. Note that MapInfo for DOS pointfiles store coordinates in millionths of
degrees, not whole degrees. Also, most MapInfo for DOS pointfiles store longitude coordinates
in the “NorthWest quadrant,” meaning that longitudes increase as you move westward. Thus,
to perform the Update operation on a MapInfo for DOS pointfile, you would need to divide the
Xcoord and Ycoord fields by one million, and multiply the Xcoord field by negative one:
Update sites
Set obj = CreatePoint(-xcoord/1000000,ycoord/1000000)
See Also
Create Point, Insert, Update
Syntax
Create PrismMap
[ From Window window_ID |
MapString mapper_creation_string ]
{ layer_id | layer_name }
With expr
[ Camera [ Pitch angle | Roll angle | Yaw angle | Elevation angle ] |
[ Position (x,y,z) | FocalPoint (x,y,z) ] |
[ Orientation (vu_1, vu_2, vu_3, vpn_1, vpn_2, vpn_3,
clip_near, clip_far) ] ]
[ Light Color lightcolor ] ]
[ Scale grid_scale ]
[ Background backgroundcolor ]
window_id is a window identifier a for a Map window which contains a region layer. An error
message is displayed if a layer with regions is not found.
mapper_creation_string specifies a command string that creates the mapper textured on the
Prism map.
layer_id is the layer identifier of a layer in the map (one or larger)
layer_name is the name of a layer in the map.
Camera specifies the camera position and orientation.
angle is an angle measurement in degrees. The horizontal angle in the dialog ranges from 0-360
degrees and rotates the maps around the center point of the grid. The vertical angle in the
dialog ranges from 0-90 and measures the rotation in elevation from the start point directly
over the map.
Pitch adjusts the camera's current rotation about the X-Axis centered at the camera's origin.
Roll adjusts the camera's current rotation about the Z-Axis centered at the camera's origin.
Yaw adjusts the camera's current rotation about the Y-Axis centered at the camera's origin.
Elevation adjusts the current camera's rotation about the X-Axis centered at the camera's focal
point.
Position indicates the camera and/or light position.
FocalPoint indicates the camera and/or light focal point.
Orientation specifies the cameras ViewUp, ViewPlane Normal and Clipping Range (used
specifically for persistence of view).
grid_scale is the amount to scale the grid in the Z direction. A value >1 will exaggerate the
topology in the Z direction, a value <1 will scale down the topological features in the Z
direction.
backgroundcolor is a color to be used to set the background and is specified using the RGB
function.
Description
The Create PrismMap statement creates a Prism Map window. The Prism Map is a way to
associate multiple variables for a single object in one visual. For example, the color associated
with a region may be the result of thematic shading while the height the object is extruded
through may represent a different value. The Create PrismMap statement corresponds to MI
Pro’s Map > Create Prism Map menu item.
Between sessions, MapInfo Professional preserves Prism Maps settings by storing a Create
PrismMap statement in the workspace file. Thus, to see an example of the Create PrismMap
statement, you could create a map, choose the Map > Create Thematic Map command, save the
workspace (e.g., PRISM.WOR), and examine the workspace in a MapBasic text edit window.
You could then copy the Create PrismMap statement in your MapBasic program. Similarly,
you can see examples of the Create PrismMap statement by opening MIPro’s MapBasic
Window before you choose Map > Create Thematic Map.
The optional window_id clause identifies which map layer to use in the prism map; if no
window_id is provided, MapBasic uses the topmost Map window. The Create PrismMap
statement must specify which layer to use, even if the Map window has only one layer. The
layer may be identified by number (layer_id), where the topmost map layer has a layer_id
value of one, the next layer has a layer_id value of two, etc. Alternately, the Create PrismMap
statement can identify the map layer by name (e.g., “world”).
Each Create PrismMap statement must specify an expr expression clause. MI Pro evaluates this
expression for each object in the layer; following the Create PrismMap statement, MI Pro
chooses each object’s display style based on that record’s expr value. The expression typically
includes the names of one or more columns from the table being shaded.
Example
Open Table "STATES.TAB" Interactive
Map From STATES
Create PrismMap From Window FrontWindow() STATES With Pop_1980
Background RGB(192,192,192)
See Also
Set PrismMap, PrismMapInfo()
Quantiled ranges are best illustrated by example. The following statement creates ranges of
buying power index (BPI) values, and uses state population statistics to perform quantiling to
set the range limits.
Create Ranges From states
With BPI_1990 Quantile Using Pop_1990
Number 5
Into Variable f_ranges
Because of the Number 5 clause, this example creates a set of five ranges.
Because of the With BPI_1990 clause, states with the highest BPI values will be placed in the
highest range (the deepest color), and states with the lowest BPI values will be placed in the
lowest range (the palest color).
Because of the Quantile Using clause, the range limits for the intermediate ranges are
calculated by quantiling, using a method that takes state population (Pop_1990) into account.
Since the Quantile Using clause specifies the Pop_1990 column, MI Pro calculates the total 1990
population for the table (which, for the United States, is roughly 250 million). MapInfo
Professional divides that total by the number of ranges (in this case, five ranges), producing a
result of fifty million. MI Pro then tries to define the ranges in such a way that the total
population for each range approximates, but does not exceed, fifty million.
MapInfo Professional retrieves rows from the States table in order of BPI values, starting with
the states having low BPI values. MI Pro assigns rows to the first range until adding another
row would cause the cumulative population to match or exceed fifty million. At that time, MI
Pro considers the first range “full” and then assigns rows to the second range. MI Pro places
rows in the second range until adding another row would cause the cumulative total to match
or exceed 100 million; at that point, the second range is full, etc.
Example
Include ”mapbasic.def”
Create Styles
From Brush(2, CYAN, 0) ’style for LOW range
To Brush (2, BLUE, 0) ’style for HIGH range
Vary Color By ”RGB”
Number 5
Into Variable brush_styles
Shade states
With col_name
Ranges
From Variable range_limits
Style Variable brush_styles
distance from the top edge of the page. By default, MapBasic uses inches as the default paper
unit. To use a different paper unit, see the Set Paper Units statement. Note: if you need to create
objects on a Layout window, you must first issue a Set CoordSys Layout statement.
The optional Pen clause specifies a line style used to draw the outline of the object; see the Pen
discussion for more details. If no Pen clause is specified, the Create Region statement uses the
current line style (the style which appears in the Options > Line Style dialog). Similarly, the
optional Brush clause specifies a fill style; see the Brush discussion for more details.
A single-polygon region can contain up to 1,048,572 nodes. For a multiple-polygon region, the
limit is smaller: for each additional polygon, reduce the number of nodes by three. There can be
a maximum of 32,000 polygons per region (multipolygon region).
Example
Dim obj_region As Object
Dim x(100), y(100) As Float
Dim i, node_count As Integer
Next
in various shades of green, while regions that have shown a loss appear in various shades of
red. Inflection only works when varying the color attribute.
The Into Variable clause specifies the name of the array variable that will hold the styles. You
do not need to pre-size the array; MI Pro automatically enlarges the array, if necessary, to make
room for the set of styles. The array variable (Pen, Brush, or Symbol) must match the style type
specified in the From and To clauses.
Example
The following example demonstrates the syntax of the Create Styles statement.
Dim brush_styles() As Brush
Create Styles
From Brush(2, CYAN, 0) ’style for LOW range
To Brush (2, BLUE, 0) ’style for HIGH range
Vary Color By ”RGB”
Number 5
Into Variable brush_styles
This Create Styles statement defines a set of five Brush styles, and stores the styles in the
b_ranges array. A subsequent Shade statement could create a thematic map which reads the
Brush styles from the b_ranges array. For an example, see the discussion of the Create Ranges
statement.
See Also
Create Ranges, Set Shade, Shade
Description
The Create Table statement creates a new empty table with up to 250 columns. Specify ODBC
to create new tables on a DBMS server.
The Using clause allows you to create a new table as part of the "Combine Objects Using
Column" functionality. The from_table must be a base table, and must contain column data.
Query tables and raster tables can't be used and will produce an error. The column structure of
the new table being created will be identical to this table.
The optional filespec clause specifies where to create the new table. If no filespec clause is used,
the table is created in the current directory or folder.
The optional Type clause specifies the table’s data format. The default type is NATIVE, but can
alternately be DBF. The NATIVE format takes up less disk space than the DBF format, but the
DBF format produces base files that can be read in any dBASE-compatible database manager.
Also, create new tables on DBMS Servers from the ODBC Type clause in the Create Table
statement.
The CharSet clause specifies a character set. The char_set parameter should be a string constant,
such as “MacRoman” or “WindowsLatin1”. If no CharSet clause is specified, MapBasic uses
the default character set for the hardware platform that is in use at runtime. See the CharSet
clause discussion for more information.
The SmallInt column type reserves two bytes for each value; thus, the column can contain
values from -32,767 to +32,767. The Integer column type reserves four bytes for each value;
thus, the column can contain values from -2,147,483,647 to +2,147,483,647.
The Version clause controls the table’s format. If you specify Version 100, MI Pro creates a table
in a format that can be read by versions of MI Pro. If you specify Version 300, MI Pro creates a
table in the format used by MI Pro 3.0. Note that region and polyline objects having more than
8,000 nodes and multiple-segment polyline objects require version 300. If you omit the Version
clause, the table is created in the version 300 format.
Example
The following example shows how to create a table called Towns, containing 3 fields: a character
field called townname, an integer field called population, and a decimal field called
median_income. The file will be created in the subdirectory C:\MAPINFO\DATA. Since an
optional Type clause is used, the table will be built around a dBASE file.
Create Table Towns
( townname Char(30),
population SmallInt,
median_income Decimal(9,2) )
File ”C:\MAPINFO\TEMP\TOWNS”
Type DBF
See Also
Import, Export, Open, Drop, Alter Table, Create Index, Create Map
CreateText( ) function
Purpose
Returns a text object created for a specific map window.
Syntax
CreateText( window_id , x , y , text , angle , anchor , offset )
window_id is an Integer window identifier that represents a Map window
x , y are Float values, representing the x/y location where the text is anchored
text is a String value, representing the text that will comprise the text object
angle is a Float value, representing the angle of rotation; for horizontal text, specify zero
anchor is an Integer value from 0 to 8, controlling how the text is placed relative to the anchor
location. Specify one of the following codes; codes are defined in MAPBASIC.DEF.
LAYER_INFO_LBL_POS_CC (0)
LAYER_INFO_LBL_POS_TL (1)
LAYER_INFO_LBL_POS_TC (2)
LAYER_INFO_LBL_POS_TR (3)
LAYER_INFO_LBL_POS_CL (4)
LAYER_INFO_LBL_POS_CR (5)
LAYER_INFO_LBL_POS_BL (6)
LAYER_INFO_LBL_POS_BC (7)
LAYER_INFO_LBL_POS_BR (8)
The two-letter suffix indicates the label orientation: T=Top, B=Bottom, C=Center, R=Right,
L=Left. For example, to place the text below and to the right of the anchor location, specify the
define code LAYER_INFO_LBL_POS_BR, or specify the value 8.
offset is an Integer from zero to 50, representing the distance (in points) the text is offset from
the anchor location; offset is ignored if anchor is zero (centered).
Return Value
Object
Description
The CreateText( ) function returns an Object value representing a text object.
The text object uses the current Font style. To create a text object with a specific Font style, issue
the Set Style statement before calling CreateText( ).
At the moment the text is created, the text height is controlled by the current Font. However,
after the text object is created, its height depends on the Map window’s zoom; zooming in will
make the text appear larger.
The object returned could be assigned to an Object variable, stored in an existing row of a table
(through the Update statement), or inserted into a new row of a table (through an Insert
statement).
Example
The following example creates a text object and inserts it into the map’s Cosmetic layer (given
that the variable i_map_id is an integer containing a Map window’s ID).
See Also
Autolabel, Create Text, Font, Insert, Update
CurDate( ) function
Purpose
Returns the current date in YYYYMMDD format.
Syntax
CurDate( )
Return Value
Date
Description
The Curdate( ) function returns a Date value representing the current date. The format will
always be YYYYMMDD. To change the value to a string in the local system format use the
FormatDate$( ) or Srt$( ) functions.
Example
Dim d_today As Date
d_today = CurDate()
See Also
Day( ), FormatDate$( ), Month( ), StringToDate( ), Timer( ), Weekday( ), Year( )
CurrentBorderPen( ) function
Purpose
Returns the current border pen style currently in use.
Syntax
CurrentBorderPen( )
Return Value
Pen
Description
The CurrentBorderPen( ) function returns the current border pen style. MapInfo Professional
assigns the current style to the border of any region objects drawn by the user. If a MapBasic
program creates an object through a statement such as Create Region, but the statement does
not include a Pen clause, the object uses the current BorderPen style.
The return value can be assigned to a Pen variable, or may be used as a parameter within a
statement that takes a Pen setting as a parameter (such as Set Map).
To extract specific attributes of the Pen style (such as the color), call the StyleAttr( ) function.
For more information about Pen settings, see the Pen clause.
Example
Dim p_user_pen As Pen p_user_pen = CurrentBorderPen( )
See Also
Pen, CurrentLinePen(), Set Style, StyleAttr( )
CurrentBrush( ) function
Purpose
Returns the Brush (fill) style currently in use.
Syntax
CurrentBrush( )
Return Value
Brush
Description
The CurrentBrush( ) function returns the current Brush style. This corresponds to the fill style
displayed in the Options > Region Style dialog. MapInfo Professional assigns the current Brush
value to any filled objects (ellipses, rectangles, rounded rectangles, or regions) drawn by the
user. If a MapBasic program creates a filled object through a statement such as Create Region,
but the statement does not include a Brush clause, the object will be assigned the current Brush
value.
The return value of the CurrentBrush( ) function can be assigned to a Brush variable, or may be
used as a parameter within a statement that takes a Brush setting as a parameter (such as Set
Map or Shade).
To extract specific Brush attributes (such as the color), call StyleAttr( ).
For more information about Brush settings, see the Brush clause.
Example
Dim b_current_fill As Brush
b_current_fill = CurrentBrush()
See Also
Brush, MakeBrush( ), Set Style, StyleAttr( )
CurrentFont( ) function
Purpose
Returns the Font style currently in use for Map and Layout windows.
Syntax
CurrentFont( )
Return Value
Font
Description
The CurrentFont( ) function returns the current Font style. This corresponds to the text style
displayed in the Options > Text Style dialog when a Map or Layout window is the active
window. MapInfo Professional will assign the current Font value to any text object drawn by
the user. If a MapBasic program creates a text object through the Create Text statement, but the
statement does not include a Font clause, the text object will be assigned the current Font value.
The return value of the CurrentFont( ) function can be assigned to a Font variable, or may be
used as a parameter within a statement that takes a Font setting as a parameter (such as Set
Legend).
To extract specific attributes of the Font style (such as the color), call the StyleAttr( ) function.
For more information about Font settings, see the Font clause.
Example
Dim f_user_text As Font
f_user_text = CurrentFont( )
See Also
Font, MakeFont( ), Set Style, StyleAttr( )
CurrentLinePen( ) function
Purpose
Returns the Pen (line) style currently in use.
Syntax
CurrentLinePen( )
Return Value
Pen
Description
The CurrentLinePen( ) function returns the current Pen style. MapInfo Professional assigns the
current style to any line or polyline objects drawn by the user. If a MapBasic program creates an
object through a statement such as Create Line, but the statement does not include a Pen clause,
the object uses the current Pen style. The return value can be assigned to a Pen variable, or may
be used as a parameter within a statement that takes a Pen setting as a parameter (such as Set
Map).
To extract specific attributes of the Pen style (such as the color), call the StyleAttr( ) function.
For more information about Pen settings, see the Pen clause.
Example
Dim p_user_pen As Pen p_user_pen = CurrentPen( )
See Also
Pen, CurrentBorderPen(), Set Style, StyleAttr( )
CurrentPen( ) function
Purpose
Returns the Pen (line) style currently in use and sets the border pen to the same style as the line
pen.
Syntax
CurrentPen( )
Return Value
Pen
Description
The CurrentPen( ) function returns the current Pen style. MapInfo Professional assigns the
current style to any line or polyline objects drawn by the user. If a MapBasic program creates an
object through a statement such as Create Line, but the statement does not include a Pen
clause, the object uses the current Pen style. If you want to use the current line pen without re-
setting the border pen, use the CurrentLinePen() function.
The return value can be assigned to a Pen variable, or may be used as a parameter within a
statement that takes a Pen setting as a parameter (such as Set Map).
To extract specific attributes of the Pen style (such as the color), call the StyleAttr( ) function.
For more information about Pen settings, see the Pen clause.
Example
Dim p_user_pen As Pen
p_user_pen = CurrentPen()
See Also
MakePen( ), Pen, Set Style, StyleAttr( )
CurrentSymbol( ) function
Purpose
Returns the Symbol style currently in use.
Syntax
CurrentSymbol( )
Return Value
Symbol
Description
The CurrentSymbol( ) function returns the current symbol style. This is the style displayed in
the Options > Symbol Style dialog. MapInfo Professional assigns the current Symbol style to
any point objects drawn by the user. If a MapBasic program creates a point object through a
Create Point statement, but the statement does not include a Symbol clause, the object will be
assigned the current Symbol value.
The return value of the CurrentSymbol( ) function can be assigned to a Symbol variable, or
may be used as a parameter within a statement that takes a Symbol setting as a parameter (such
as Set Map or Shade).
To extract specific attributes of the Symbol style (such as the color), call the StyleAttr( )
function.
For more information about Symbol settings, see the Symbol clause.
Example
Dim sym_user_symbol As Symbol
sym_user_symbol = CurrentSymbol( )
See Also
MakeSymbol( ), Set Style, StyleAttr( ), Symbol
DateWindow( ) function
Purpose
Returns the current date window setting as an integer in the range 0 to 99, or (-1) if date
windowing is off.
Syntax
DateWindow(context)
context is a SmallInt that can either be DATE_WIN_CURPROG or DATE_WIN_SESSION.
Description
This depends on which context is passed. If context is DATE_WIN_SESSION, then the current
session setting in effect is returned. If context is DATE_WIN_CURPROG, then the current
MapBasic program’s local setting is returned, if a program is not running the session setting is
returned.
MBX’s compiled before v5.5 will still convert 2-digit years to the current century (5.0 and
earlier behavior). To get the new behavior, they must be recompiled with MapBasic v5.5 or
later.
Example
In the following example the variable Date1 = 19890120, Date2 = 20101203 and MyYear = 1990.
DIM Date1, Date2 as Date
DIM MyYear As Integer
Set Format Date ”US”
Set Date Window 75
Date1 = StringToDate(”1/20/89”)
Date2 = StringToDate(”12/3/10”)
MyYear = Year(”12/30/90”)
See Also
SetDateWindow statement
Day( ) function
Purpose
Returns the day component from a Date expression.
Syntax
Day( date_expr )
date_expr is a Date expression
Return Value
SmallInt from 1 to 31
Description
The Day( ) function returns an integer value from one to thirty-one, representing the day-of-
the-month component of the specified date. For example, if the specified date is 12/17/93, the
Day( ) function returns a value of 17.
Example
Dim day_var As SmallInt, date_var As Date
date_var = StringToDate(”05/23/1985”)
day_var = Day(date_var)
See Also
CurDate( ), Month( ), Timer( ), Year( )
DDEExecute statement
Purpose
Issues a command across an open DDE channel.
Syntax
DDEExecute channel , command
channel is an Integer channel number returned by DDEInitiate( )
command is a String representing a command for the DDE server to execute
Description
The DDEExecute statement sends a command string to the server application in a DDE
conversation.
The channel parameter must correspond to the number of a channel opened through a
DDEInitiate( ) function call.
The command parameter string must represent a command which the DDE server (the passive
application) is able to carry out. Different applications have different requirements regarding
what constitutes a valid command; to learn about the command format for a particular
application, see the documentation for that application.
Error Conditions
ERR_CMD_NOT_SUPPORTED error generated if not running on Windows
ERR_NO_RESPONSE_FROM_APP error if server application does not respond
Example
Through MapBasic, you can open a DDE channel with Microsoft Excel as the server
application. If the conversation specifies the “System” topic, you can use the DDEExecute
statement to send Excel a command string. Provided that the command string is equivalent to
an Excel macro function, and provided that the command string is enclosed in square brackets,
Excel can execute the command. The example below instructs Excel to open the worksheet
“TRIAL.XLS”.
Dim i_chan As Integer
i_chan = DDEInitiate(”Excel”, ”System”)
DDEExecute i_chan, ”[OPEN(””C:\DATA\TRIAL.XLS””)]”
See Also
DDEInitiate, DDEPoke, DDERequest$( )
DDEInitiate( ) function
Purpose
Initiates a new DDE conversation, and returns the associated channel number.
Syntax
DDEInitiate( appl_name , topic_name )
appl_name is a String representing an application name (e.g., “MapInfo”)
topic_name is a string representing a topic name (e.g., “System”)
Return Value
Integer
Description
The DDEInitiate( ) function initiates a DDE (Dynamic Data Exchange) conversation, and
returns the number that identifies that conversation’s channel.
A DDE conversation allows two Microsoft Windows applications to exchange information.
Once a DDE conversation has been initiated, a MapBasic program can issue DDERequest$( )
function calls (to read information from the other application) and DDEPoke statements (to
write information to the other application). Once a DDE conversation has served its purpose
and is no longer needed, the MapBasic program should terminate the conversation through the
DDETerminate or DDETerminateAll statements.
Note: DDE conversations are a feature specific to Microsoft Windows; therefore, MapBasic
generates an error if a program issues DDE-related function calls when running on a
non-Windows platform. To determine the current hardware platform at run-time, call
the SystemInfo( ) function.
The appl_name parameter identifies a Windows application. For example, to initiate a
conversation with Microsoft Excel, you should specify the appl_name parameter “Excel.” The
application named by the appl_name parameter must already be running before you can initiate
a DDE conversation; note that the MapBasic Run Program statement allows you to run another
Windows application.
Not all Windows applications support DDE conversations. To determine if an application
supports DDE conversations, see the documentation for that application.
The topic_name parameter is a string that identifies the topic for the conversation. Each
application has its own set of valid topic names; for a list of topics supported by a particular
application, refer to the documentation for that application. With many applications, the name
of a file that is in use is a valid topic name. Thus, if Excel is currently using the worksheet file
“ORDERS.XLS”, you could issue the following MapBasic statements:
Dim i_chan As Integer
i_chan = DDEInitiate(”Excel”, ”C:\ORDERS.XLS”)
to initiate a DDE conversation with that Excel worksheet.
Many applications support a special topic called “System”. If you initiate a conversation using
the “System” topic, you can then use the DDERequest$( ) function to obtain a list of the strings
which the application accepts as valid topic names (i.e. a list of the files that are currently in
use). Knowing what topics are available, you can then initiate another DDE conversation with a
specific document. See the example below.
The following table lists some sample application and topic names which you could use with
the DDEInitiate( ) function.
’ ”: Sheet1 System”
’ (if spreadsheet is still ”unnamed”),or like:
’ ”: C:Orders.XLS Sheet1 System”
’
’ If Excel 5 is running, topiclist might look like:
’ ”[Book1]Sheet1 [Book2]Sheet2 ...”
’
’ Next,extract just the first topic (e.g.,”Sheet1”)
’ by extracting the text between the 1st & 2nd tabs;
’ or, in the case of Excel 5, by extracting the text
’ that appears before the first tab.
DDEPoke statement
Purpose
Sends a data value to an item in a DDE server application.
Syntax
DDEPoke channel, itemname, data
channel is an Integer channel number returned by DDEInitiate( )
itemname is a String value representing the name of an item
data is a character string to be sent to the item named in the itemname parameter
Description
The DDEPoke statement stores the data text string in the specified DDE item.
The channel parameter must correspond to the number of a channel which was opened through
the DDEInitiate( ) function.
The itemname parameter should identify an item which is appropriate for the specified channel.
Different DDE applications support different item names; to learn what item names are
supported by a particular Windows application, refer to the documentation for that
application.
In a DDE conversation with Excel, a string of the form R1C1 (for Row 1, Column 1) is a valid
item name. In a DDE conversation with another MapBasic application, the name of a global
variable in the application is a valid item name.
Error Conditions
ERR_CMD_NOT_SUPPORTED error generated if not running on Windows
ERR_INVALID_CHANNEL error generated if the specified channel number is invalid
Example
If Excel is already running, the following example stores a simple message (”Hello from
MapInfo!”) in the first cell of an Excel worksheet.
Dim i_chan_num As Integer
i_chan_num = DDEInitiate(”EXCEL”, ”Sheet1”)
DDEPoke i_chan_num, ”R1C1”, ”Hello from MapInfo!”
The following example assumes that there is another MapBasic application currently in use -
“Dispatch.mbx” - and assumes that the Dispatch application has a global variable called
Address. The example below uses DDEPoke to modify the Address global variable.
i_chan_num = DDEInitiate(”MapInfo”,”C:\DISPATCH.MBX”)
DDEPoke i_chan_num, ”Address”, ”23 Main St.”
See Also
DDEExecute, DDEInitiate, DDERequest$( )
DDERequest$( ) function
Purpose
Returns a data value obtained from a DDE conversation.
Syntax
DDERequest$( channel , itemname )
channel is an Integer channel number returned by DDEInitiate( )
itemname is a String representing the name of an item in the server application
Return Value
String
Description
The DDERequest$( ) function returns a string of information obtained through a DDE
conversation. If the request is unsuccessful, the DDERequest$() function returns a null string.
The channel parameter must correspond to the number of a channel which was opened through
the DDEInitiate( ) function.
The itemname parameter should identify an item which is appropriate for the specified channel.
Different DDE applications support different item names; to learn what item names are
supported by a particular Windows application, refer to the documentation for that
application.
The following table lists some topic and item combinations that can be used when conducting a
DDE conversation with Microsoft Excel as the server:
Note: Through the DDERequest$( ) function, one MapBasic application can observe the
current values of global variables in another MapBasic application. The following table
lists the topic and item combinations that can be used when conducting a DDE
conversation with MapInfo Professional as the server.
DDETerminate statement
Purpose
Closes a DDE conversation.
Syntax
DDETerminate channel
channel is an Integer channel number returned by DDEInitiate( )
Description
The DDETerminate statement closes the DDE channel specified by the channel parameter.
The channel parameter must correspond to the channel number returned by the DDEInitiate()
function call (which initiated the conversation). Once a DDE conversation has served its
purpose and is no longer needed, the MapBasic program should terminate the conversation
through the DDETerminate or DDETerminateAll statements.
Note: Multiple MapBasic applications can be in use simultaneously, and each application can
open its own DDE channels. However, a given MapBasic application may only close the
DDE channels which it opened. A MapBasic application may not close DDE channels
which were opened by another MapBasic application.
Error Conditions
ERR_CMD_NOT_SUPPORTED error generated if not running on Windows
ERR_INVALID_CHANNEL error generated if the specified channel number is invalid
Example
DDETerminate i_chan_num
See Also
DDEInitiate, DDETerminateAll
DDETerminateAll statement
Purpose
Closes all DDE conversations which were opened by the same MapBasic program.
Syntax
DDETerminateAll
Description
The DDETerminateAll statement closes all open DDE channels which were opened by the
same MapBasic application. Note that multiple MapBasic applications can be in use
simultaneously, and each application can open its own DDE channels. However, a given
MapBasic application may only close the DDE channels which it opened. A MapBasic
application may not close DDE channels which were opened by another MapBasic application
Once a DDE conversation has served its purpose and is no longer needed, the MapBasic
program should terminate the conversation through the DDETerminate or DDETerminateAll
statements.
Error Conditions
ERR_CMD_NOT_SUPPORTED error generated if not running on Windows
See Also
DDEInitiate, DDETerminate
If the Declare Function statement declares an external function, the file_name parameter must
specify the name of the file containing the external function. The external file must be present at
run-time.
Every external function has an explicitly assigned name. Ordinarily, the Declare Function
statement’s fname parameter matches the explicit routine name from the external file.
Alternately, the Declare Function statement can include an Alias clause, which lets you call the
external function by whatever name you choose. The Alias clause lets you override an external
function’s explicit name, in situations where the explicit name conflicts with the name of a
standard MapBasic function.
If the Declare Function statement includes an Alias clause, the function_alias parameter must
match the external function’s original name, and the fname parameter indicates the name by
which MapBasic will call the routine.
Restrictions on Windows DLL parameters
You can pass a custom variable type as a parameter to a DLL. However, the DLL must be
compiled with “structure packing” set to the tightest packing. See the MapBasic User’s Guide
for more information.
Restrictions on Macintosh XFCN parameters
You cannot pass arrays or custom variable types as parameters when calling XFCNs.
Example
The following example defines a custom function, CubeRoot, which returns the cube root of a
number (the number raised to the one-third power).
Declare Sub Main
Declare Function CubeRoot(ByVal x As Float) As Float
Sub Main
Note Str$( CubeRoot(23) )
End Sub
Function CubeRoot(ByVal x As Float) As Float
CubeRoot = x ^ (1 / 3)
End Function
See Also
Declare Sub, Function...End Function
name you choose. The Alias clause lets you override an external routine’s explicit name, in
situations where the explicit name conflicts with the name of a standard MapBasic function.
If the Declare Sub statement includes an Alias clause, the sub_alias parameter must match the
external routine’s original name, and the sub_proc parameter indicates the name by which
MapBasic will call the routine. You can pass a custom variable type as a parameter to a DLL.
However, the DLL must be compiled with “structure packing” set to the tightest packing. For
information on custom variable types, see Type.
Example
Declare Sub Main
Declare Sub Cube(ByVal original As Float, cubed As Float)
Sub Main
Dim x, result As Float
Call Cube(2, result)
’ result now contains the value: 8 (2 x 2 x 2)
x = 1
Call Cube(x + 2, result)
’ result now contains the value: 27 (3 x 3 x 3)
End Sub
Sub Cube (ByVal original As Float, cubed As Float)
’
’ Cube the ”original” parameter value, and store
’ the result in the ”cubed” parameter.
’
cubed = original ^ 3
End Sub
See Also
Call, Sub ... End Sub
Define statement
Purpose
Defines a custom keyword with a constant value.
Restrictions
You cannot issue a Define statement through the MapBasic window.
Syntax
Define identifier definition
identifier is an identifier up to 31 characters long, beginning with a letter or underscore (_)
definition is the text MapBasic should substitute for each occurrence of identifier
Description
The Define statement defines a new identifier. For the remainder of the program, whenever
MapBasic encounters the same identifier the original definition will be substituted for the
identifier. For examples of Define statements, see the standard MapBasic definitions file,
MAPBASIC.DEF.
An identifier defined through a Define statement is not case-sensitive. If you use a Define
statement to define the token FOO, your program can refer to the identifier as Foo or foo. You
cannot use the Define statement to re-define a MapBasic keyword, such as Set or Create. For a
list of reserved keywords, see the discussion of the Dim statement.
Examples
Your application may need to reference the mathematic value known as Pi, which has a value
of approximately 3.141593. Accordingly, you might want to use the following definition:
Define PI 3.141593
Following such a definition, you could simply type PI wherever you needed to reference the
value 3.141593.
The definition portion of a Define statement can include quotes. For example, the following
statement creates a keyword with a definition including quotes:
Define FILE_NAME ”World.tab”
The following define is part of the standard definitions file, mapbasic.def. This define provides
an easy way of clearing the Message window:
Define CLS Print Chr$(12)
DeformatNumber$( ) function
Purpose
Removes formatting from a string that represents a number.
Syntax
DeformatNumber$ ( numeric_string )
numeric_string is a string that represents a numeric value, such as “12,345,678”
Return Value
String
Description
Returns a string that represents a number. The return value does not include thousands
separators, regardless of whether the numeric_string argument included thousands separators.
The return value uses a period as the decimal separator, regardless of whether the user’s
computer is set up to use another character as the decimal separator.
Examples
The following example calls Val( ) to determine the numeric value of a string. Before calling
Val( ), this example calls DeformatNumber$( ) to remove thousands separators from the string.
(The string that you pass to Val( ) cannot contain thousands separators.)
Dim s_number As String
Dim f_value As Float
s_number = ”1,222,333.4”
s_number = DeformatNumber$(s_number)
f_value = Val(s_number)
Print f_value
See Also
FormatNumber$( ), Val( )
Delete statement
Purpose
Deletes one or more graphic objects, or one or more entire rows, from a table.
Syntax
Delete [Object] From table [ Where Rowid = id_number ]
table is the name of an open table
id_number is the number of a single row (an integer value of one or more)
Description
The Delete statement deletes graphical objects or entire records from an open table.
By default, the Delete statement deletes all records from a table. However, if the statement
includes the optional Object keyword, MapBasic only deletes the graphical objects that are
attached to the table, rather than deleting the records themselves.
By default, the Delete statement affects all records in the table. However, if the statement
includes the optional Where Rowid = ... clause, then only the specified row is affected by the
Delete statement.
There is an important difference between a Delete Object From statement and a Drop Map
statement. A Delete Object From statement only affects objects or records in a table, it does not
affect the table structure itself. A Drop Map statement actually modifies the table structure, so
that graphical objects may not be attached to the table.
Examples
The following Delete statement deletes all of the records from a table. At the conclusion of this
operation, the table still exists, but it is completely empty - as if the user had just created it by
choosing File > New.
Open Table ”clients”
Delete From clients
Commit Table clients
The following Delete statement deletes only the object from the tenth row of the table:
Open Table ”clients”
Delete Object From clients Where Rowid = 10
Commit Table clients
See Also
Drop Map, Insert
Dialog statement
Purpose
Displays a custom dialog box.
Restrictions
You cannot issue a Dialog statement through the MapBasic window.
Syntax
Dialog
[ Title title ]
[ Width w ] [ Height h ] [ Position x , y ]
[ Calling handler ]
Control control_clause
[ Control control_clause . . . ]
title is a String expression that appears in the title bar of the dialog
h specifies the height of the dialog, in dialog units (8 dialog height units represent the height of
one character)
w specifies the width of the dialog, in dialog units (4 dialog height units represent the width of
one character)
x, y specifies the dialog’s initial position, in pixels, representing distance from the upper-left
corner of MapInfo Professional’s work area; if the Position clause is omitted, the dialog appears
centered
handler is the name of a procedure to call before the user is allowed to use the dialog; this
procedure is typically used to issue Alter Control statements
Each control_clause can specify one of the following types of controls:
Button GroupBox
OKButton RadioGroup
CancelButton PenPickerm
EditText BrushPicker
StaticText FontPicker
PopupMenu SymbolPicker
CheckBox ListBox
MultiListBox
See the separate discussions of those control types for more details (e.g., for details on
CheckBox controls, see Control CheckBox; for details on Picker controls, see Control
PenPicker; etc.).
Each control_clause can specify one of the following control types:
EditText
StaticText
PenPicker / BrushPicker / SymbolPicker / FontPicker
ListBox / MultiListBox
PopupMenu
Description
The Dialog statement creates a dialog box, displays it on the screen, and lets the user interact
with the dialog. The dialog box is modal; in other words, the user must dismiss the dialog box
(e.g., by clicking OK or Cancel) before doing anything else in MI Pro. For an introduction to
custom dialogs, see the MapBasic User’s Guide.
Anything that can appear on a dialog is known as a control. Each dialog must contain at least
one control (e.g., an OKButton control). Individual control clauses are discussed in separate
entries (e.g., see Control CheckBox for a discussion of check-box controls). As a general rule,
every dialog should include an OKButton control and/or a CancelButton control, so that the
user has a way of dismissing the dialog.
The Dialog statement lets you create a custom dialog box. If you want to display a standard
dialog box (e.g., a File > Open dialog), use one of the following statements or functions: Ask( ),
Note, ProgressBar, FileOpenDlg( ), FileSaveAsDlg( ), or GetSeamlessSheet( ).
For an introduction to the concepts behind MapBasic dialog boxes, see the MapBasic User’s
Guide.
Sizes and Positions of Dialogs and Dialog Controls
Within the Dialog statement, sizes and positions are stated in terms of dialog units. A width of
four dialog units equals the width of one character, and a height of eight dialog units equals the
height of one character. Thus, if a dialog control has a height of 40 and a width of 40, that
control is roughly ten characters wide and 5 characters tall.
Control positions are relative to the upper left corner of the dialog. To place a control at the
upper-left corner of a dialog, use x- and y-coordinates of zero and zero.
The Position, Height and Width clauses are all optional. If you omit these clauses, MapBasic
places the controls at default positions in the dialog, with subsequent control clauses appearing
further down in the dialog.
Custom dialogs appear larger on the Macintosh than on Windows, because the Macintosh
system font is larger.
Terminating a Dialog
After a MapBasic program issues a Dialog statement, the user will continue interacting with
the dialog until one of four things happens:
• The user clicks the OKButton control (if the dialog has one);
• The user clicks the CancelButton control (if the dialog has one);
• The user clicks a control with a handler that issues a Dialog Remove statement;
or
• The user otherwise dismisses the dialog (e.g., by pressing Esc on a dialog that has
a CancelButton).
To force a dialog to remain on the screen after the user has clicked OK or Cancel, assign a
handler procedure to the OKButton or CancelButton control and have that handler issue a
Dialog Preserve statement.
Reading the User’s Input
After a Dialog statement, call CommandInfo( ) to determine whether the user clicked OK or
Cancel to dismiss the dialog. If the user clicked OK, the following function call returns TRUE:
CommandInfo(CMD_INFO_DLG_OK)
There are two ways to read values entered by the user: Include Into clauses in the Dialog
statement, or call the ReadControlValue( ) function from a handler procedure.
If a control specifies the Into clause, and if the user clicks the OKButton, MI Pro stores the
control’s final value in a program variable. Note: MI Pro only updates the variable if the user
clicks OK. Also, MI Pro only updates the variable after the dialog terminates.
To read a control’s value from within a handler procedure, call ReadControlValue( ).
Specifying Hotkeys for Controls
When a MapBasic application runs on MapInfo, dialogs can assign hotkeys to the various
controls. A hotkey is a convenience allowing the user to choose a dialog control by pressing key
sequences rather than clicking with the mouse.
To specify a hotkey for a control, include the ampersand character (&) in the title for that
control. Within the Title clause, the ampersand should appear immediately before the character
which is to be used as a hotkey character. Thus, the following Button clause defines a button
which the user can choose by pressing Alt-R:
Control Button
Title ”&Reset”
Although an ampersand appears within the Title clause, the final dialog does not show the
ampersand. If you need to display an ampersand character in a control (e.g., if you want a
button to read “Find & Replace”), include two successive ampersand characters in the Title
clause:
Title ”Find && Replace”
If you position a StaticText control just before or above an EditText control, and you define the
StaticText control with a hotkey designation, the user is able to jump to the EditText control by
pressing the hotkey sequence.
Hotkey designations are ignored on platforms (e.g., Macintosh) that do not support dialog
hotkeys.
Specifying the Tab Order
The user can press the Tab key to move the keyboard focus through the dialog. The focus
moves from control to control according to the dialog’s tab order.
Tab order is defined by the order of the Control clauses in the Dialog statement. When the
focus is on the third control, pressing Tab moves the focus to the fourth control, etc. If you want
to change the tab order, change the order of the Control clauses.
Examples
The following example creates a simple dialog with an EditText control. In this example, none
of the Control clauses use the optional Position clause; therefore, MapBasic places each control
in a default position.
Dialog
Title ”Search”
Control StaticText
Title ”Enter string to find:”
Control EditText
Value gs_searchfor ’this is a Global String variable
Into gs_searchfor
Control OKButton
Control CancelButton
If CommandInfo(CMD_INFO_DLG_OK) Then
’ ...then the user clicked OK, and the variable
’ gs_searchfor contains the text the user entered.
End If
The following program demonstrates the syntax of all of MapBasic’s control types.
Include ”mapbasic.def”
Declare Sub reset_sub ’ resets dialog to default settings
Declare Sub ok_sub ’ notes values when user clicks OK.
Declare Sub Main
Sub Main
Dim s_title As String ’the title of the map
Dim l_showlegend As Logical ’TRUE means include legend
Dim i_details As SmallInt ’1 = full details; 2 = partial
Dim i_quarter As SmallInt ’1=1st qrtr, etc.
Dim i_scope As SmallInt ’1=Town;2=County; etc.
Dim sym_variable As Symbol
Dialog
Title ”Map Franchise Locations”
Control StaticText
Title ”Enter Map Title:”
Position 5, 10
Control EditText
Value ”New Franchises, FY 95”
Into s_title
ID 1
Position 65, 8 Width 90
Control GroupBox
Title ”Level of Detail”
Position 5, 30 Width 70 Height 40
Control RadioGroup
Title ”&Full Details;&Partial Details”
Value 2
Into i_details
ID 2
Position 12, 42 Width 60
Control StaticText
Title ”Show Franchises As:” Position 95, 30
Control SymbolPicker
Position 95, 45
Into sym_variable
ID 3
Control StaticText
Title ”Show Results For:”
Position 5, 80
Control ListBox
Title ”First Qrtr;2nd Qrtr;3rd Qrtr;4th Qrtr”
Value 4
Into i_quarter
ID 4
Position 5, 90 Width 65 Height 35
Control StaticText
Title ”Include Map Layers:”
Position 95, 80
Control MultiListBox
Title ”Streets;Highways;Towns;Counties;States”
Value 3
ID 5
Position 95, 90 Width 65 Height 35
Control StaticText
Title ”Scope of Map:”
Position 5, 130
Control PopupMenu
Title ”Town;County;Territory;Entire State”
Value 2
Into i_scope
ID 6
Position 5, 140
Control CheckBox
Title ”Include &Legend”
Into l_showlegend
ID 7
Position 95, 140
Control Button
Title ”&Reset”
Calling reset_sub
Position 10, 165
Control OKButton
Position 65, 165
Calling ok_sub
Control CancelButton
Position 120, 165
If CommandInfo(CMD_INFO_DLG_OK) Then
’ ... then the user clicked OK.
Else
’ ... then the user clicked Cancel.
End If
End Sub
Sub reset_sub
’ here, you could use Alter Control statements
’ to reset the controls to their original state.
End Sub
Sub ok_sub
’ Here, place code to handle user clicking OK
End Sub
The preceding program produces the following dialog box.
See Also
Alter Control, Ask( ), Dialog Preserve, Dialog Remove, FileOpenDlg( ), FileSaveAsDlg( ),
Note, ReadControlValue( )
Dialog Preserve
End If
End Sub
See Also
Alter Control, Dialog, Dialog Remove, ReadControlValue( )
Dim statement
Purpose
Defines one or more variables.
Restrictions
When you issue Dim statements through the MapBasic window, you can only define one
variable per Dim statement, although a Dim statement within a compiled program may define
multiple variables. You cannot define array variables using the MapBasic window.
Syntax
Dim var_name [ , var_name ... ] As var_type
[ , var_name [ , var_name ... ] As var_type ... ]
var_name is the name of a variable to define
var_type is a standard or custom variable Type
Description
A Dim statement declares one or more variables. The following table summarizes the types of
variables which you can declare through a Dim statement.
Array Variables
MapBasic supports one-dimensional array variables. To define an array variable, add a pair of
parentheses immediately after the variable name. To specify an initial array size, include a
constant integer expression between the parentheses.
The following example declares an array of ten Float variables, then assigns a value to the first
element in the array:
Dim f_stats(10) As Float
f_stats(1) = 17.23
The number that appears between the parentheses is known as the subscript. The first element
of the array is the element with a subscript of one (as shown in the example above).
To re-size an array, use the ReDim statement. To determine the current size of an array, use the
UBound( ) function. If the Dim statement does not specify an initial array size, the array will
initially contain no members; in such a case, you will not be able to store any data in the array
until re-sizing the array with a ReDim statement.A MapBasic array can have up to 32,767
items.
String Variables
A String variable can contain a text string up to 32 kilobytes in length. However, there is a limit
to how long a string constant you can specify in a simple assignment statement. The following
example performs a simple String variable assignment, where a constant string expression is
assigned to a String variable:
Dim status As String
status = ”This is a string constant ... ”
In this type of assignment, the constant string expression to the right of the equal sign has a
maximum length of 256 characters.
MapBasic, like other BASIC languages, pads fixed-length String variables with blanks. In other
words, if you define a 10-byte String variable, then assign a five-character string to that
variable, the variable will actually be padded with five spaces so that it fills the space allotted.
(This feature makes it easier to format text output in such a way that columns line up).
Variable-length String variables, however, are not padded in this fashion. This difference can
affect comparisons of strings; you must exercise caution when comparing fixed-length and
variable-length String variables. In the following program, the If...Then statement would
determine that the two strings are not equal:
Dim s_var_len As String
Dim s_fixed_len As String * 10
s_var_len = ”testing”
s_fixed_len = ”testing”
If s_var_len = s_fixed_len Then
Note ”strings are equal” ’ this won’t happen
Else
Note ”strings are NOT equal” ’ this WILL happen
End If
Example
’ Below is a custom Type definition, which creates
’ a new data type known as Person
Type Person
Name As String
Age As Integer
Phone As String
End Type
Distance( ) function
Purpose
Returns the distance between two locations.
Syntax
Distance ( x1 , y1 , x2 , y2 , unit_name )
x1 and x2 are x-coordinates (e.g., longitude)
y1 and y2 are y-coordinates (e.g., latitude)
unit_name is a string representing the name of a distance unit (e.g., “km”)
Return Value
Float
Description
The Distance( ) function calculates the distance between two locations.
The function returns the distance measurement in the units specified by the unit_name
parameter; for example, to obtain a distance in miles, specify “mi” as the unit_name parameter.
See the Set Distance Units statement for the list of available unit names.
The x- and y-coordinate parameters must use MapBasic’s current coordinate system. By
default, MapInfo Professional expects coordinates to use a longitude, latitude coordinate
system. You can reset MapBasic’s coordinate system through the Set CoordSys statement.
If the current coordinate system is an earth coordinate system, Distance( ) returns the great-
circle distance between the two points. A great-circle distance is the shortest distance between
two points on a sphere. (A great circle is a circle that goes around the earth, with the circle’s
center at the center of the earth; a great-circle distance between two points is the distance along
the great circle which connects the two points.)
For the most part, MI Pro performs a Cartesian or Spherical operation. Generally, a spherical
operation is performed unless the coordinate system is nonEarth, in which case, a Cartesian
operation is performed.
Example
Dim dist, start_x, start_y, end_x, end_y As Float
Open Table ”cities”
Fetch First From cities
start_x = CentroidX(cities.obj)
start_y = CentroidY(cities.obj)
Fetch Next From cities
end_x = CentroidX(cities.obj)
end_y = CentroidY(cities.obj)
dist = Distance(start_x,start_y,end_x,end_y,”mi”)
See Also
Area( ), ObjectLen( ), Set CoordSys, Set Distance Units
Do...Loop statement
Purpose
Defines a loop which will execute until a specified condition becomes TRUE (or FALSE).
Restrictions
You cannot issue a Do Loop statement through the MapBasic window.
Syntax 1
Do
statement_list
Loop [ { Until | While } condition ]
Syntax 2
Do [ { Until | While } condition ]
statement_list
Loop
statement_list is a group of statements to be executed zero or more times
condition is a conditional expression which controls when the loop terminates
Description
The Do ... Loop statement provides loop control. Generally speaking, the Do ... Loop
repeatedly executes the statements in a statement_list as long as a While condition remains
TRUE (or, conversely, the loop repeatedly executes the statement_list until the Until condition
becomes TRUE).
If the Do ... Loop does not contain the optional Until / While clause, the loop will repeat
indefinitely. In such a case, a flow control statement, such as Goto or Exit Do, will be needed to
halt or exit the loop. The Exit Do statement halts any Do ... Loop immediately (regardless of
whether the loop has an Until / While clause), and resumes program execution with the first
statement following the Loop clause.
As indicated above, the optional Until / While clause may either follow the Do keyword or the
Loop keyword. The position of the Until / While clause dictates whether MapBasic tests the
condition before or after executing the statement_list. This is of particular importance during the
first iteration of the loop. A loop using the following syntax :
Do
statement_list
Loop While condition
will execute the statement_list and then test the condition. If the condition is TRUE, MapBasic will
continue to execute the statement_list until the condition becomes FALSE. Thus, a Do ... Loop
using the above syntax will execute the statement_list at least once.
By contrast, a Do ... Loop of the following form will only execute the statement_list if the
condition is TRUE.
Do While condition
statement_list
Loop
Example
The following example uses a Do..Loop statement to read the first ten records of a table.
Dim sum As Float, counter As Integer
Open Table ”world”
Fetch First From world
counter = 1
Do
sum = sum + world.population
Fetch Next From world
counter = counter + 1
Loop While counter <= 10
See Also
Exit Do, For ... Next
EndHandler procedure
Purpose
A reserved procedure name, called automatically when an application terminates.
Syntax
Declare Sub EndHandler
Sub EndHandler
statement_list
End Sub
statement_list is a list of statements to execute when the application terminates
Description
EndHandler is a special-purpose MapBasic procedure name.
If the user runs an application containing a sub procedure named EndHandler, the EndHandler
procedure is called automatically when the application ends. This happens whether the user
exited MapInfo Professional or another procedure in the application issued an End Program
statement.
Note: Multiple MapBasic applications can be “sleeping” at the same time. When MI Pro
terminates, MapBasic automatically calls all sleeping EndHandler procedures, one after
another.
See Also
RemoteMsgHandler, SelChangedHandler, ToolHandler, WinChangedHandler,
WinClosedHandler
EOF( ) function
Purpose
Returns TRUE if MapBasic tried to read past the end of a file, FALSE otherwise.
Syntax
EOF( filenum )
filenum is the number of a file opened through the Open File statement
Return Value
Logical
Description
The EOF( ) function returns a logical value indicating whether the End-Of-File condition exists
for the specified file. The integer filenum parameter represents the number of an open file.
If a Get statement tries to read past the end of the specified file, the EOF( ) function returns a
value of TRUE; otherwise, EOF( ) returns a value of FALSE.
The EOF( ) function works with open files; when you wish to check the current position of an
open table, use the EOT( ) function.
For an example of calling EOF( ), see the sample program NVIEWS.MB (Named Views).
Error Conditions
ERR_FILEMGR_NOTOPEN error generated if the specified file is not open
See Also
EOT( ), Open File
EOT( ) function
Purpose
Returns TRUE if MapBasic has reached the end of the specified table, FALSE otherwise.
Syntax
EOT ( table )
table is the name of an open table
Return Value
Logical
Description
The EOT( ) function returns TRUE or FALSE to indicate whether MapInfo Professional has
tried to read past the end of the specified table. The table parameter represents the name of an
open table.
Error Conditions
ERR_TABLE_NOT_FOUND error generated if the specified table is not available
Example
The following example uses the logical result of the EOT( ) function to decide when to
terminate a loop. The loop repeatedly fetches the next record in a table, until the point when the
EOT( ) function indicates that the program has reached the end of the table.
Dim f_total As Float
Open Table ”customer”
Fetch First From customer
Do While Not EOT(customer)
f_total = f_total + customer.order
Fetch Next From customer
Loop
See Also
Fetch, EOF( ), Open File, Open Table
Erase( ) function
Purpose
Returns an object created by erasing part of another object.
Syntax
Erase ( source_object , eraser_object )
source_object is an object, part of which is to be erased; cannot be a point or text object
eraser_object is a closed object, representing the area that will be erased
Return Value
Returns an object representing what remains of source_object after erasing eraser_object.
Description
The Erase( ) function erases part of an object, and returns an object expression representing
what remains of the object.
The source_object parameter can be a linear object (line, polyline, or arc) or a closed object
(region, rectangle, rounded rectangle, or ellipse), but cannot be a point object or text object. The
eraser_object must be a closed object.
The object returned retains the color and pattern styles of the source_object.
Example
’ In this example, o1 and o2 are Object variables
’ that already contain Object expressions.
If o1 Intersects o2 Then
If o1 Entirely Within o2 Then
Note ”Cannot Erase; nothing would remain.”
Else
o3 = Erase( o1, o2 )
End If
Else
Note ”Cannot Erase; objects do not intersect.”
End If
See Also
Objects Erase, Objects Intersect
Err( ) function
Purpose
Returns a numeric code, representing the current error.
Syntax
Err( )
Return Value
Integer
Description
The Err( ) function returns the numeric code indicating which error occurred most recently.
By default, a MapBasic program which generates an error will display an error message and
then halt. However, by issuing an OnError statement, a program can set up an error handling
routine to respond to error conditions. Once an error handling routine is specified, MapBasic
jumps to that routine automatically in the event of an error. The error handling routine can then
call the Err( ) function to determine which error occurred.
The Err( ) function can only return error codes while within the error handler. Once the
program issues a Resume statement to return from the error handling routine, the error
condition is reset. This means that if you call the Err( ) function outside of the error handling
routine, it returns zero.
Some statement and function descriptions within this document contain an Error Conditions
heading (just before the Example heading), listing error codes related to that statement or
function. However, not all error codes are identified in the Error Conditions heading.
Some MapBasic error codes are only generated under narrowly-defined, specific
circumstances; for example, the ERR_INVALID_CHANNEL error is only generated by DDE-
related functions or statements. If a statement might generate such an “unusual” error, the
discussion for that statement will identify the error under the Error Conditions heading.
However, other MapBasic errors are “generic”, and might be generated under a variety of
broadly-defined circumstances. For example, many functions, such as Area( ) and
ObjectInfo( ), take an Object expression as a parameter. Any such function will generate the
ERR_FCN_OBJ_FETCH_FAILED error if you pass an expression of the form tablename.obj as a
parameter, when the current row from that table has no associated object. In other words, any
function which takes an Object parameter might generate the ERR_FCN_OBJ_FETCH_FAILED
error. Since the ERR_FCN_OBJ_FETCH_FAILED error can occur in so many different places,
individual functions do not explicitly identify the error.
Similarly, there are two math errors - ERR_FP_MATH_LIB_DOMAIN and
ERR_FP_MATH_LIB_RANGE - which can occur as a result of an invalid numeric parameter.
These errors might be generated by calls to any of the following functions: Asin( ), Acos( ),
Atn( ), Cos( ), Exp( ), Log( ), Sin( ), Sqr( ), or Tan( ).
The complete list of potential MapBasic error codes is included in the file ERRORS.DOC.
See Also
Error, Error$( ), OnError
Error statement
Purpose
Simulates the occurrence of an error condition.
Syntax
Error error_num
error_num is an Integer error number
Description
The Error statement simulates the occurrence of an error.
If an error-handling routine has been enabled through an OnError statement, the simulated
error will cause MapBasic to perform the appropriate error-handling routine. If no error
handling routine has been enabled, the error simulated by the Error statement will cause the
MapBasic application to halt after displaying an appropriate error message.
See Also
Err( ), Error$( ), OnError
Error$( ) function
Purpose
Returns a message describing the current error.
Syntax
Error$( )
Return Value
String
Description
The Error$( ) function returns a character string describing the current run-time error, if an
error has occurred. If no error has occurred, the Error$( ) function returns a null string.
The Error$( ) function should only be called from within an error handling routine. See the
discussion of the Err( ) function for more information.
See Also
Err( ), Error, OnError
Exit Do statement
Purpose
Exits a Do loop prematurely.
Restrictions
You cannot issue an Exit Do statement through the MapBasic window.
Syntax
Exit Do
Description
An Exit Do statement terminates a Do...Loop statement. Upon encountering an Exit Do
statement, MapBasic will jump to the first statement following the Do...Loop statement. Note
that the Exit Do statement is only valid within a Do...Loop statement.
Do...Loop statements can be nested; that is, a Do...Loop statement can appear within the body
of another, “outer” Do...Loop statement. An Exit Do statement only halts the iteration of the
nearest Do...Loop statement. Thus, in an arrangement of this sort:
Do While condition1
:
Do While condition2
:
If error_condition
Exit Do
End If
:
Loop
:
Loop
the Exit Do statement will halt the inner loop (Do While condition2) without necessarily
affecting the outer loop (Do While condition1).
See Also
Do...Loop, Exit For, Exit Sub
Exp( ) function
Purpose
Returns the number e raised to a specified exponent.
Syntax
Exp( num_expr )
num_expr is a numeric expression
Return Value
Float
Description
The Exp( ) function raises the mathematical value e to the power represented by num_expr. e has
a value of approximately 2.7182818.
Note: MapBasic supports general exponentiation through the caret operator ( ^ ).
Example
Dim e As Float
e = Exp(1)
’ the local variable e now contains
’ approximately 2.7182818
See Also
Cos( ), Sin( ), Log ()
Export statement
Purpose
Exports a table to another file format.
Syntax 1 (for exporting MIF/MID files, DBF files, or ASCII text files)
Export table
Into file_name
[ Type
{ “MIF” |
“DBF” [ Charset char_set ] |
“ASCII” [ Charset char_set ] [ Delimiter “d ” ] [ Titles ] } ]
[ Overwrite ]
Syntax 2 (for exporting DXF files)
Export table
Into file_name
[ Type “DXF” ]
[ Overwrite ]
[ Preserve
[ AttributeData ] [ Preserve ] [ MultiPolygonRgns [ As Blocks ] ] ]
[ { Binary | ASCII [ DecimalPlaces decimal_places ] } ]
[ Version { 12 | 13 } ]
[ Transform
( MI_x1 , MI_y1 ) ( MI_x2 , MI_y2 )
( DXF_x1 , DXF_y1 ) ( DXF_x2 , DXF_y2 ) ]
table is the name of an open table; do not use quotation marks around this name
file_name is a String specifying the filename to contain the exported data; if the file name does
not include a path, the export file is created in the current working directory
char_set is a String that identifies a character set, such as “MacRoman” or “WindowsLatin1”;
see the separate CharSet discussion for details
d is a character used as a delimiter when exporting an ASCII file
decimal_places is a small integer (from 0 to 16, default value is 6), which controls the number of
decimal places used when exporting floating-point numbers in ASCII
MI_x1, MI_y1, etc. are numbers that represent bounds coordinates in the MapInfo Professional
table
DXF_x1, DXF_y1, etc. are numbers that represent bounds coordinates in the DXF file
Description
The Export statement copies the contents of a MapInfo table to a separate file, using a file
format which other packages could then edit or import. For example, you could export the
contents of a table to a DXF file, then use a CAD software package to import the DXF file. The
Export statement does not alter the original table.
Version 12 or Version 13
This clause controls whether MI Pro creates a DXF file compliant with AutoCAD 12 or 13. If
you omit the clause, MI Pro creates a version 12 DXF file.
Transform
Specifies a coordinate transformation. In the Transform clause, you specify the minimum and
maximum x- and y- bounds coordinates of the MapInfo table, and then specify the minimum
and maximum coordinates that you want to have in the DXF file.
Example
The following example takes an existing MapInfo table, Facility, and exports the table to a DXF
file called “FACIL.DXF”.
Open Table ”facility”
Export facility
Into ”FACIL.DXF”
Type ”DXF”
Overwrite
Preserve AttributeData
Preserve MultiPolygonRgns As Blocks
ASCII DecimalPlaces 3
Transform (0, 0) (1, 1) (0, 0) (1, 1)
See Also
Import
ExtractNodes( ) function
Purpose
Returns a polyline or region created from a subset of the nodes in an existing object.
Syntax
ExtractNodes( object, polygon_index, begin_node, end_node, b_region )
object is a polyline or region object
polygon_index is an SmallInt value, 1 or larger: for region objects, this indicates which polygon
to query; for polylines, which section
begin_node is a SmallInt node number, 1 or larger; indicates the beginning of the range of nodes
to return
end_node is a SmallInt node number, 1 or larger; indicates the end of the range of nodes to
return
b_region is a Logical value that controls whether a region or polyline object is returned; use
TRUE for a region object or FALSE for a polyline object
Return Value
Returns an object with the specified nodes. MapBasic applies all styles (color, etc.) of the
original object; then, if necessary, MapBasic applies the current drawing styles.
Description
If the beginnode is equal to or greater than endnode, the nodes are returned in the following
order:
begin_node through the next-to-last node in the polygon;
Fetch statement
Purpose
Sets a table’s cursor position (i.e., which row is the current row).
Syntax
Fetch { First | Last | Next | Prev | Rec n } From table
n is the number of the record to read
table is the name of an open table
Description
Use the Fetch statement to retrieve records from an open table. By issuing a Fetch statement,
your program places the table cursor at a certain row position in the table; this dictates which of
the records in the table is the “current” record.
Note: The term “cursor” is used here to signify a row’s position in a table. This has nothing to
do with the on-screen mouse cursor.
After you issue a Fetch statement, you can retrieve data from the current row by using one of
the following expression types:
Syntax Example
table.column World.Country
table.col# World.col1
table.col( number ) World.col( variable_name )
A Fetch First statement positions the cursor at the first un-deleted row in the table.
A Fetch Last statement positions the cursor at the last un-deleted row in the table.
A Fetch Next statement moves the cursor forward to the next un-deleted row.
A Fetch Prev statement moves the cursor backward to the previous un-deleted row.
A Fetch Rec n statement positions the cursor on a specific row, even if that row is deleted. Note:
If the specified record is deleted, the statement generates run-time error 404.
Various MapInfo Professional and MapBasic operations (e.g., Select, Update, and screen
redraws) automatically reset the current row. Accordingly, Fetch statements should be issued
just before any statements that make assumptions about which row is current.
Reading Past the End of the Table
After you issue a Fetch statement, you may need to call the EOT( ) function to determine
whether you fetched an actual row.
If the Fetch statement placed the cursor on an actual row, the EOT( ) function returns FALSE
(meaning, there is not an end-of-table condition).
If the Fetch statement attempted to place the cursor past the last row, the EOT( ) function
returns TRUE (meaning, there is an end-of-table condition; therefore there is no “current row”).
The following example shows how to use a Fetch Next statement to loop through all rows in a
table. As soon as a Fetch Next statement attempts to read past the final row, EOT( ) returns
TRUE, causing the loop to halt.
Dim i As Integer
i = 0
Fetch First From world
Do While Not EOT(world)
i = i + 1
Fetch Next From world
Loop
FileAttr( ) function
Purpose
Returns information about an open file.
Syntax
FileAttr( filenum , attribute )
filenum is the number of a file opened through an Open File statement
attribute is a code indicating which file attribute to return; see table below
Return Value
Integer
Description
The FileAttr( ) function returns information about an open file.
The attribute parameter must be one of the codes in this table:
Error Conditions
ERR_FILEMGR_NOTOPEN error generated if the specified file is not open
See Also
EOF( ), Get, Open File, Put
FileExists( ) function
Purpose
Returns a logical value indicating whether or not a file exists.
Syntax
FileExists( filespec )
filespec is a string that specifies the file path and name.
Return Value
Logical: TRUE if the file already exists
Example
If FileExists(”C:\MapInfo\TODO.TXT”) Then
End If
See Also
TempFileName$( )
FileOpenDlg( ) function
Purpose
Displays a File Open dialog, and returns the name of the file the user selected.
Syntax
FileOpenDlg( path , filename , filetype , prompt )
path is a String value, indicating the directory or folder to choose files from
filename is a String value, indicating the default file name for the user to choose; on the
Macintosh, this parameter should be an empty string (“”)
filetype is a String value, three or four characters, indicating a file type (e.g., “TAB” to specify
tables)
prompt is a String title that appears on the bar at the top of the dialog
Return Value
String value, representing the name of the file the user chose (or an empty string if the user
cancelled).
Description
The FileOpenDlg( ) function displays a dialog similar to the one that displays when the user
chooses File > Open.
To choose a file from the list that appears in the dialog, the user can either click a file in the list
and click the OK button, or simply double-click a file in the list. In either case, the
FileOpenDlg( ) function returns a character string representing the full path and name of the
file the user chose. Alternately, if the user clicks the Cancel button instead of picking a file, the
dialog returns a null string (“”).
The FileOpenDlg( ) function does not actually open any files; it merely presents the user with a
dialog, and lets the user choose a filename. If your application then needs to actually open the
file chosen by the user, the application must issue a statement such as Open Table. If you want
your application to display an Open dialog, and then you want MapInfo Professional to
automatically open the selected file, you can issue a statement such as Run Menu Command
M_FILE_OPEN or Run Menu Command M_FILE_ADD_WORKSPACE.
The path parameter specifies the directory or folder from which the user will choose an existing
file. Note that the path parameter only dictates the initial directory, it does not prevent the user
from changing directories once the dialog appears. If the path parameter is blank (a null string),
the dialog will present a list of files in the current working directory.
The filename parameter specifies the default filename for the user to choose.
The filetype parameter is a string, usually three or four characters long, which indicates the type
of files that should appear in the dialog. Some filetype settings have special meaning; for
example, if the filetype parameter is “TAB”, the dialog will present a list of MapInfo tables, and
if the filetype parameter is “WOR”, the dialog will present a list of MapInfo workspace files.
There are also a variety of other three-character filetype values, summarized in the table below.
Iif you specify one of the special type values from the table below, the dialog will include a
control that lets the user choose between seeing a list of table files or a list of all files (“*.*”).
FileSaveAsDlg( ) function
Purpose
Displays a Save As dialog, and returns the name of the file the user entered.
Syntax
FileSaveAsDlg ( path , filename, filetype, prompt )
path is a String value, indicating the default destination directory
filename is a String value, indicating the default file name
filetype is a String value, indicating the type of file that the dialog should let the user choose; on
the Macintosh, this parameter should be an empty string (“”)
prompt is a String title that appears at the top of the dialog
Return Value
String value, representing the name of the file the user entered (or an empty string if the user
cancelled).
Description
The FileSaveAsDlg( ) function displays a Save As dialog, similar to the dialog that displays
when the user chooses File > Save Copy As.
The user can type in the name of the file they want to save. Alternately, the user can double-
click from the list of grayed-out filenames that appears in the dialog. Since each filename in the
list represents an existing file, MapBasic asks the user to verify that they want to overwrite the
existing file.
If the user specifies a filename and clicks OK, the FileSaveAsDlg( ) function returns a character
string representing the full path and name of the file the user chose. If the user clicks the Cancel
button instead of picking a file, the function returns a null string (“”).
The path parameter specifies the initial directory path. The user can change directories once the
dialog appears. If the path parameter is blank (a null string), the dialog presents a list of files in
the current directory.
The filename parameter specifies the default filename for the user to choose.
The filetype parameter is a three-character (or shorter) string which identifies the type of files
that should appear in the dialog. To display a dialog that lists workspaces, specify the string
“WOR” as the filetype parameter; to display a dialog that lists table names, specify the string
“TAB.” See the discussion of the FileOpenDlg( ) function for more information about three-
character filetype codes. On the Macintosh, this parameter does not apply; specify “”.
The FileSaveAsDlg( ) function does not actually save any files; it merely presents the user with
a dialog, and lets the user choose a filename to save. To save data under the filename chosen by
the user, issue a statement such as Commit Table As.
See Also
Commit Table, FileOpenDlg( )
Find statement
Purpose
Finds a location in a mappable table.
Syntax
Find address [ , region ] [ Interactive ]
address is a String expression representing the name of a map object to find; to find the
intersection of two streets, use the syntax: streetname && streetname
region is the name of a region object which refines the search
Description
The Find statement searches a mappable table for a named location (represented by the address
parameter). MapBasic stores the search results in system variables, which a program can then
access through the CommandInfo( ) function. If the Find statement includes the optional
Interactive keyword, and if MapBasic is unable to locate the specified address, a dialog
displays a list of “near matches.”
The Find statement can only search a mappable table (e.g., a table which has graphic objects
attached). The table must already be open. The Find statement operates on whichever column
is currently chosen for searching. A MapBasic program can issue a Find Using statement to
identify a specific table column to search. If the Find statement is not preceded by a Find Using
statement, MapBasic searches whichever table was specified the last time the user chose MI
Pro’s Query > Find command.
The Find statement can optionally refine a search by specifying a region name in addition to
the address parameter. In other words, you could simply try to find a city name (e.g., “Albany”)
by searching a table of cities; or you could refine the search by specifying both a city name and
a region name (e.g., “Albany”, “CA”). The Find statement does not automatically add a
symbol to the map to mark where the address was found. To create such a symbol, call the
CreatePoint( ) function or the Create Point statement; see example below.
Determining Whether the Address Was Found
Following a Find statement, a MapBasic program can issue the function call
CommandInfo(CMD_INFO_FIND_RC) to determine if the search was successful. If the
search was successful, call CommandInfo(CMD_INFO_X) to determine the x-coordinate of the
queried location, and call CommandInfo(CMD_INFO_Y) to determine the y-coordinate. To
determine the row number that corresponds to the “found” address, call
CommandInfo(CMD_INFO_FIND_ROWID).
The Find statement may result in an exact match, an approximate match, or a failure to match.
If the Find statement results in an exact match, the function call
CommandInfo(CMD_INFO_FIND_RC) returns a value of one. If the Find statement results in
an approximate match, the function call returns a value greater than one. If the Find statement
fails to match the address, the function call returns a negative value.
The table below summarizes the Find-related information represented by the
CommandInfo(CMD_INFO_FIND_RC) return value. The return value has up to three digits,
and that each of the three digits indicates the relative success or failure of a different part of the
search.
value of 301. The 1 digit signifies that the city name matched exactly, while the 3 digit indicates
that MapBasic was only partly successful in locating a correct refining region.
If a table of streets contains “Main St”, and a Find statement attempts to locate “Main Street”,
MapBasic considers the result to be an approximate match (assuming that abbreviation file
processing has been enabled; see the Find Using statement). Strictly speaking, the string “Main
Street” does not match the string “Main St”. However, MapBasic is able to match the two
strings after substituting possible abbreviations from the MapInfo abbreviations file
(MAPINFOW.ABB). Following the Find statement, the CommandInfo(CMD_INFO_FIND_RC)
function call returns a value of 2.
If the Find operation presents the user with a dialog, and the user enters text in the dialog in
order to complete the find, then the return code will have a 1 (one) in the millions place. For
more information on geocoding, see the MapInfo Professional Reference.
Example
Include ”mapbasic.def”
Dim x, y As Float, win_id As Integer
Open Table ”states” Interactive
Map From States
win_id = FrontWindow()
Find Using states(state)
Find ”NY”
If CommandInfo(CMD_INFO_FIND_RC) >= 1 Then
x = CommandInfo(CMD_INFO_X)
y = CommandInfo(CMD_INFO_Y)
Set Map
Window win_id
Center (x, y)
’ Now create a symbol at the location we found.
’ Create the object in the Cosmetic layer.
Insert Into
WindowInfo( win_id, WIN_INFO_TABLE) (Object)
Values ( CreatePoint(x, y) )
Else
Note ”Location not found.”
End If
See Also
Find Using
The optional OtherBdy clause dictates whether MapBasic will match to a record found in a
refining region other than the refining region specified. By default, this option is disabled (Off);
to enable the option, specify the clause OtherBdy On.
MapInfo Professional saves the Inset and Offset settings specified the last time the user chose
Query > Find Options. Table > Geocode Options or executed a Find Using statement. Thus, the
last specified inset/offset options becomes the default settings for the next time.
Example
Find Using city_1k(city)
Refine Using states(state)
Fix( ) function
Purpose
Returns an integer value, obtained by removing the fractional part of a decimal value.
Syntax
Fix ( num_expr )
num_expr is a numeric expression
Return Value
Integer
Description
The Fix( ) function removes the fractional portion of a number, and returns the resultant integer
value.
The Fix( ) function is similar to, but not identical to, the Int( ) function. The two functions differ
in the way that they treat negative fractional values. When passed a negative fractional
number, Fix( ) returns the nearest integer value greater than or equal to the original value; thus,
the function call:
Fix(-2.3)
returns a value of -2. But when the Int( ) function is passed a negative fractional number, it
returns the nearest integer value that is less than or equal to the original value. Thus, the
function call:
Int(-2.3)
returns a value of -3.
Example
Dim i_whole As Integer
i_whole = Fix(5.999)
’ i_whole now has the value 5.
i_whole = Fix(-7.2)
’ i_whole now has the value -7.
See Also
Int( ), Round( )
Font clause
Purpose
Specifies a text style.
Syntax
Font font_expr
font_expr is a Font expression, e.g., MakeFont( fontname, style, size, fgcolor, bgcolor )
Description
The Font clause specifies a text style. Font is a clause, not a complete MapBasic statement.
Various object-related statements, such as Create Text, allow you to specify a Font setting; this
lets you choose the typeface and point size of the new text object. If you omit the Font
expression from a Create Text statement, the new object uses MapInfo Professional’s current
Font. The keyword Font may be followed by an expression that evaluates to a Font value. This
expression can be a Font variable:
Font font_var
or a call to a function (e.g., CurrentFont( ) or MakeFont( ) ) which returns a Font value:
Font MakeFont(”Helvetica”, 1, 12, BLACK, WHITE)
With some MapBasic statements (e.g., Set Legend), the keyword Font can be followed
immediately by the five parameters that define a Font style (font name, style, point size,
foreground color, and background color) within parentheses:
Font(”Helvetica”, 1, 12, BLACK, WHITE)
The following table summarizes the components that define a font:
Component Description
fontname A string that identifies a font. The set of available fonts depends
on the user’s system and the hardware platform in use.
style Integer value. Controls text attributes such as bold, italic, and
underline. See table below for details.
size Integer value representing a point size. A point size of twelve is
one-sixth of an inch tall.
foreground color Integer RGB color value, representing the color of the text. See the
RGB( ) function.
background color Integer RGB color value. If the halo style is used, this is the halo
color; otherwise, this is the background fill color.
To specify a transparent background style in a Font clause, omit
the background color. For example: Font( “Helvetica”, 1, 12,
BLACK). To specify a transparent fill when calling the MakeFont(
) function, specify -1 as the background color.
The following table shows how the style parameter corresponds to font styles.
For...Next statement
Purpose
Defines a loop which will execute for a specific number of iterations.
Restrictions
You cannot issue a For...Next statement through the MapBasic window.
Syntax
For var_name = start_expr To end_expr [ Step inc_expr ]
statement_list
Next
var_name is the name of a numeric variable
start_expr is a numeric expression
end_expr is a numeric expression
inc_expr is a numeric expression
statement_list is the group of statements to execute with each iteration of the For loop
Description
The For statement provides loop control. This statement requires a numeric variable (identified
by the var_name parameter). A For statement either executes a group of statements (the
statement_list) a number of times, or else skips over the statement_list completely. The start_expr,
end_expr, and inc_expr values dictate how many times, if any, the statement_list will be carried
out.
Upon encountering a For statement, MapBasic assigns the start_expr value to the var_name
variable. If the variable is less than or equal to the end_expr value, MapBasic executes the group
of statements in the statement_list, and then adds the inc_expr increment value to the variable. If
no Step clause was specified, MapBasic uses a default increment value of one. MapBasic then
compares the current value of the variable to the end_expr expression; if the variable is currently
less than or equal to the end_expr value, MapBasic once again executes the statements in the
statement_list. If, however, the var_name variable is greater than the end_expr, MapBasic stops
the For loop, and resumes execution with the statement which follows the Next statement.
Conversely, the For statement can also count downwards, by using a negative Step value. In
this case, each iteration of the For loop decreases the value of the var_name variable, and
MapBasic will only decide to continue executing the loop as long as var_name remains greater
than or equal to the end_expr.
Each For statement must be terminated by a Next statement. Any statements which appear
between the For and Next statements comprise the statement_list; this is the list of statements
which will be carried out upon each iteration of the loop.
The Exit For statement allows you to exit a For loop regardless of the status of the var_name
variable. The Exit For statement tells MapBasic to jump out of the loop, and resume execution
with the first statement which follows the Next statement.
MapBasic permits you to modify the value of the var_name variable within the body of the For
loop; this can affect the number of times that the loop is executed. However, as a matter of
programming style, you should try to avoid altering the contents of the var_name variable
within the loop.
Example
Dim i As Integer
ForegroundTaskSwitchHandler procedure
Purpose
A reserved procedure name, called automatically when MapInfo Professional receives the
focus (becoming the active application) or loses the focus (another application becomes active).
Syntax
Declare Sub ForegroundTaskSwitchHandler
Sub ForegroundTaskSwitchHandler
statement_list
End Sub
statement_list is a list of statements
Description
If the user runs an application containing a procedure named ForegroundTaskSwitchHandler,
MI Pro calls the procedure automatically whenever MI Pro receives or loses the focus. Within
the procedure, call CommandInfo( ) to determine whether MI Pro received or lost the focus.
Example
Sub ForegroundTaskSwitchHandler
If CommandInfo(CMD_INFO_TASK_SWITCH)
= SWITCHING_INTO_MAPINFO Then
End Sub
See Also
CommandInfo( )
Format$( ) function
Purpose
Returns a string representing a custom-formatted number.
Syntax
Format$ ( value , pattern )
value is a numeric expression
pattern is a string which specifies how to format the results
Return Value
String
Description
The Format$( ) function returns a string representing a formatted number. Given a numeric
value such as 12345.67, Format$( ) can produce formatted results such as “$12,345.67”.
The value parameter specifies the numeric value that you want to format.
The pattern parameter is a string of code characters, chosen to produce a particular type of
formatting. The pattern string should include one or more special format characters, such as #,
0, % , the comma character, the period, or the semi-colon; these characters control how the
results will look. The table below summarizes the format characters.
Error Conditions
ERR_FCN_INVALID_FMT error generated if the pattern string is invalid
Examples
The following examples show the results you can obtain by using various pattern strings. The
results are shown as comments in the code. Note: you will obtain slightly different results if
your computer is set up with non-US number formatting.
Format$( 12345, ”,#”) ’ returns ”12,345”
Format$(-12345, ”,#”) ’ returns ”-12,345”
Format$( 12345, ”$#”) ’ returns ”$12345”
Format$(-12345, ”$#”) ’ returns ”-$12345”
FormatDate$ function
Purpose
Returns a date formatted in the short date style specified by the Control Panel.
Syntax
FormatDate$( value )
value is a number or string representing the date in a YYYYMMDD format.
Return Value
String
Description
The FormatDate$( ) function returns a string representing a date in the local system format as
specified by the Control Panel.
If you specify the year as a two-digit number(e.g., 96), MapInfo Professional uses the current
century or the century as determined by the Set Date Window statement.
Year can now take two-digit year expressions. Use the Date window to determine which
century should be used. See DateWindow( ) function
Examples
Assuming Control Panel settings are d/m/y for date order, ’-’ for date separator, and “dd-
MMM-yyyy” for short date format:
Dim d_Today As Date
d_Today = CurDate()
Print d_Today ‘returns ”19970910”
Print FormatDate$(d_Today) ‘returns ”10-Sep-1997”
Dim s_EnteredDate As String
s_EnteredDate = “03-02-61”
Print FormatDate$(s_EnteredDate) ‘returns “03-Feb-1961”
s_EnteredDate = “12-31-61”
Print FormatDate$( s_EnteredDate ) ‘ returns ERROR: not d/m/y
ordering
s_EnteredDate = “31-12-61”
Print FormatDate$( s_EnteredDate ) ‘ returns 31-Dec-1961”
See Also
DateWindow( ), Set DateWindow
FormatNumber$( ) function
Purpose
Returns a string representing a number, including thousands separators and decimal-place
separators that match the user’s system configuration.
Syntax
FormatNumber$ ( num )
num is a numeric value or a string that represents a numeric value, such as “1234.56”
Return Value
String
Description
Returns a string that represents a number. If the number is large enough to need a thousands
separators, this function inserts thousands separators. MapInfo Professional reads the user’s
system configuration to determine which characters to use as the thousands separator and
decimal separator.
Examples
The following table demonstrates how the FormatNumber$( ) function with a comma as the
thousands separator and period as the decimal separator (United States defaults):
See Also
DeformatNumber$( )
FrontWindow( ) function
Purpose
Returns the Integer identifier of the active window.
Syntax
FrontWindow( )
Return Value
Integer
Description
The FrontWindow( ) function returns the integer id of the foremost document window (Map,
Browse, Graph, or Layout). Note that immediately following a statement which creates a new
window (e.g., Map, Browse, Graph, Layout), the new window is the foremost window.
Example
Dim map_win_id As Integer
Open Table ”states”
Map From states
map_win_id = FrontWindow()
See Also
NumWindows( ), WindowID( ), WindowInfo( )
You cannot pass arrays, custom Type variables, or Alias variables as ByVal parameters to
custom functions. However, you can pass any of those data types as by-reference parameters.
If your custom function takes no parameters, your Function...End Function statement can
either include an empty pair of parentheses, or omit the parentheses entirely. However, every
function call must include a pair of parentheses, regardless of whether the function takes
parameters. For example, if you wish to define a custom function called Foo, your
Function...End Function statement could either look like this:
Function Foo()
’ ... statement list goes here ...
End Function
or like this:
Function Foo
’ ... statement list goes here ...
End Function
but all calls to the function would need to include the parentheses, in this fashion:
var_name = Foo()
Availability of Custom Functions
The user may not incorporate calls to user-defined functions when filling in standard MapInfo
Professional dialog boxes. A custom function may only be called from within a compiled
MapBasic application. Thus, a user may not specify a user-defined function within the SQL
Select dialog box; however, a compiled MapBasic program may issue a Select statement which
does incorporate calls to user-defined functions.
A custom function definition is only available from within the application that defines the
function. If you write a custom function which you wish to include in each of several MapBasic
applications, you must copy the Function...End Function definition to each of the program
files.
Function Names
The Function statement’s name parameter can match the name of a standard MapBasic
function, such as Abs or Chr$. Such a custom function will replace the standard MapBasic
function by the same name (within the confines of that MapBasic application). If a program
defines a custom function named Abs, any subsequent calls to the Abs function will execute
the custom function instead of MapBasic’s standard Abs( ) function.
When a MapBasic application redefines a standard function in this fashion, other applications
are not affected. Thus, if you are writing several separate applications, and you want each of
your applications to use your own, customized version of the Distance function, each of your
applications must include the appropriate Function statement.
When a MapBasic application redefines a standard function, the re-definition applies
throughout the entire application. In every procedure of that program, all calls to the redefined
function will use the custom function, rather than the original.
Example
The following example defines a custom function, CubeRoot, which returns the cube root of a
number (the number raised to the one-third power). Because the call to CubeRoot appears
earlier in the program than the CubeRoot Function...End Function definition, this example
uses the Declare Function statement to pre-define the CubeRoot function parameter list.
Declare Function CubeRoot(ByVal x As Float) As Float
Declare Sub Main
Sub Main
Dim f_result As Float
f_result = CubeRoot(23)
Note Str$(f_result)
End Sub
Get statement
Purpose
Reads from a file opened in Binary or Random access mode.
Syntax
Get [#] filenum , [ position ] , var_name
filenum is the number of a file opened through an Open File statement
position is the file position to read from
var_name is the name of a variable where MapBasic will store results
Description
The Get statement reads from an open file. The behavior of the Get statement and the set of
parameters which it expects are affected by the options specified in the preceding Open File
statement.
If the Open File statement specified Random file access, the Get statement’s Position clause
can be used to indicate which record of data to read. When the file is opened, the file position
points to the first record of the file (record 1). A Get automatically increments the file position,
and thus the Position clause does not need to be used if sequential access is being performed.
However, you can use the Position clause to set the record position before the record is read.
If the Open File statement specified Binary file access, one variable can be read at a time. What
data is read depends on the byte-order format of the file and the var_name variable being used
to store the results. If the variable type is Integer, then 4 bytes of the binary file will be read, and
converted to a MapBasic variable. Variables are stored the following way:
With Binary file access, the Position parameter is used to position the file pointer to a specific
offset in the file. When the file is opened, the position is set to one (the beginning of the file). As
a Get is performed, the position is incremented by the same amount read. If the Position clause
is not used, the Get reads from where the file pointer is positioned.
Note: The Get statement requires two commas, even if the optional position parameter is
omitted.
If a file was opened in Binary mode, the Get statement cannot specify a variable-length String
variable; any String variable used in a Get statement must be fixed-length.
See Also
Open File, Put
GetFolderPath$( ) function
Purpose
Return the path of a special MapInfo Professional or Windows folder.
Syntax
GetFolderPath$( folder_id )
folder_id is one of the following values:
FOLDER_MI_APPDATA
FOLDER_MI_LOCAL_APPDATA
FOLDER_MI_PREFERENCE
FOLDER_MI_COMMON_APPDATA
FOLDER_APPDATA
FOLDER_LOCAL_APPDATA
FOLDER_COMMON_APPDATA
FOLDER_COMMON_DOCS
FOLDER_MYDOCS
FOLDER_MYPICS
Return Value
String
Description
Given the id of a special MapInfo or Windows folder, GetFolderPath$() function returns the
path of the folder. An example of a special Windows folder is the My Documents folder. An
example of a special MapInfo folder is the preference folder; the default location to which MI
Pro writes out the preference file.
The location of many of these folders varies between versions of Windows. They can also vary
depending on which user is logged in. Note that FOLDER_MI_APPDATA,
FOLDER_MI_LOCAL_APPDATA and FOLDER_MI_COMMON_APPDATA may not exist.
Before attempting to access those folders, test for their existence by using FileExists().
FOLDER_MI_PREFERENCE always exists
Ids beginning in FOLDER_MI return the path for folders specific to MI Pro. The rest of the ids
return the path for Windows folders and correspond to the ids defined for WIN32 API function
SHGetFolderPath. The most common of these ids have been defined for easy use in MapBasic
applications. Any id valid to SHGetFolderPath will work with GetFolderPath$().
Example
include "mapbasic.def"
declare sub main
sub main
dim sMiPrfFile as string
sMiPrfFile = GetFolderPath$(FOLDER_MI_PREFERENCE)
Print sMiPrfFile
end subet128
See Also
LocateFiles( )
GetMetadata$( ) function
Purpose
Retrieves metadata from a table.
Syntax
GetMetadata$( table_name , key_name )
table_name is the name of an open table, specified either as an explicit table name (e.g., World)
or as a string representing a table name (e.g., “World”).
key_name is a string representing the name of a metadata key.
Return Value
String, up to 239 bytes long. If the key does not exist, or if there is no value for the key, MapInfo
Professional returns an empty string.
Description
This function returns a metadata value from a table. For more information about querying a
table’s metadata, see the Metadata statement, or see the MapBasic User’s Guide.
Example
If the Parcels table has a metadata key called “\Copyright” then the following statement reads
the key’s value:
Print GetMetadata$(Parcels, ”\Copyright”)
See Also
Metadata
GetSeamlessSheet( ) function
Purpose
Prompts the user to select one sheet from a seamless table, and then returns the name of the
chosen sheet.
Syntax
GetSeamlessSheet( table_name )
table_name is the name of a seamless table that is open.
Return Value
String, representing a table name (or an empty string if user cancels).
Description
This function displays a dialog box listing all of the sheets that make up a seamless table. If the
user chooses a sheet and clicks OK, this function returns the table name the user selected. If the
user cancels, this function returns an empty string.
Example
Sub Browse_A_Table(ByVal s_tab_name As String)
Dim s_sheet As String
End Sub
See Also
Set Table, TableInfo( )
Global statement
Purpose
Defines one or more global variables.
Syntax
Global var_name [ , var_name ... ] As var_type
[ , var_name ... As var_type ... ]
var_name is the name of a global variable to define
var_type is Integer, Float, Date, Logical, String, or a custom variable Type
Description
A Global statement defines one or more global variables. Global statements may only appear
outside of a sub procedure.
The syntax of the Global statement is identical to the syntax of the Dim statement; the
difference is that variables defined through a Global statement are global in scope, while
variables defined through a Dim statement are local. A local variable may only be examined or
modified by the sub procedure which defined it, whereas any sub procedure in a program may
examine or modify any global variable.
A sub procedure may define local variables with names which coincide with the names of
global variables. In such a case, the sub procedure’s own local variables take precedence (i.e.
within the sub procedure, any references to the variable name will utilize the local variable, not
the global variable by the same name). Global array variables may be re-sized with the ReDim
statement. Windows, global variables are “visible” to other Windows applications through
DDE conversations.
Example
Declare Sub testing()
Declare Sub Main()
Global gi_var As Integer
Sub Main()
Call testing
Note Str$(gi_var) ’ this displays ”23”
End Sub
Sub testing()
gi_var = 23
End Sub
See Also
Dim, ReDim, Type, UBound( )
Goto statement
Purpose
Jumps to a different spot (in the same procedure), identified by a label.
Restrictions
You cannot issue a Goto statement through the MapBasic window.
Syntax
Goto label
label is a label appearing elsewhere in the same procedure
Description
The Goto statement performs an unconditional jump. Program execution continues at the
statement line identified by the label. The label itself should be followed by a colon; however,
the label name should appear in the Goto statement without the colon.
Generally speaking, the Goto statement should not be used to exit a loop prematurely. The Exit
Do and Exit For statements provide the ability to exit a loop. Similarly, you should not use a
Goto statement to jump into the body of a loop.
A Goto statement may only jump to a label within the same procedure.
Example
Goto endproc
...
Graph statement
Purpose
Opens a new Graph window.
Syntax (5.5 and later)
Graph
label_column , expr [ , ... ]
From table
[ Position ( x , y ) [ Units paperunits ] ]
[ Width width [ Units paperunits ] ]
[ Height height [ Units paperunits ] ]
[ Min | Max ]
[ Using template_file [ Restore ] [ Series In Columns ] ]
label_column is the name of the column to use for labelling the y-axis
expr is an expression providing values to be graphed
table is the name of an open table
paperunits is the name of a paper unit (e.g., ”in”)
x , y specifies the position of the upper left corner of the Grapher, in paper units
window_width and window_height specify the size of the Grapher, in paper units
template file is a valid graph template file
Syntax (pre-version 5.5)
Graph
label_column , expr [ , ... ]
From table
[ Position ( x , y ) [ Units paperunits ] ]
[ Width width [ Units paperunits ] ]
[ Height height [ Units paperunits ] ]
[ Min | Max ]
label_column is the name of the column to use for labelling the y-axis
expr is an expression providing values to be graphed
table is the name of an open table
paperunits is the name of a paper unit (e.g., “in”)
x , y specifies the position of the upper left corner of the Grapher, in paper units
window_width and window_height specify the size of the Grapher, in paper units
Description
If the Using clause is present and template_file specifies a valid graph template file, then a graph
is created based on the specified template file. Otherwise a 5.0 graph is created. If the Restore
clause is included, then title text in the template file is used in the graph window. Otherwise
default text is used for each title in the graph. The Restore keyword is included when writing
the Graph command to a workspace, so when the workspace is opened the title text is restored
exactly as is was when the workspace was saved. The Restore keyword is not used in the
Graph command constructed by the Create Graph wizard, so the default text is used for each
title. If the Series In Columns is included, then the graph series are based on the table
columns. Otherwise the series are based on the table rows.
Graph commands in workspaces or programs that were created prior to version 5.5 will still
create a 5.0 graph window. When a 5.0 graph window is active in MapInfo Professional 5.5 or
later, the 5.0 graph menu will be also be active, so the user can modify the graph using the 5.0
editing dialogs. The Create Graph wizard will always created a 5.5 or later version graph
window.
The Graph statement adds a new Grapher window to the screen, displaying the specified table.
The graph will appear as a rotated bar chart; subsequent Set Graph statements can re-configure
the specifics of the graph (e.g., the graph rotation, graph type, title, etc.).
MI Pro ’s Window > Graph dialog is limited in that it only allows the user to choose column
names to graph. MapBasic’s Graph statement, however, is able to graph full expressions which
involve column names. Similarly, although the Graph dialog only allows the user to choose
four columns to graph, the Graph statement can construct a graph with up to 255 columns.
If the Graph statement includes the optional Max keyword, the resultant Grapher window is
maximized, taking up all of the screen space available to MI Pro. Conversely, if the Graph
statement includes the Min keyword, the window is minimized.
Example (5.5 and later graphs)
Graph State_Name, Pop_1980, Pop_1990, Num_Hh_80 From States Using
”C:\Program Files\MapInfo\GRAPHSUPPORT\Templates\Column\Percent.3tf”
Graph City, Tot_hu, Tot_pop From City_125 Using ”C:\Program
Files\MapInfo\GRAPHSUPPORT\Templates\Bar\Clustered.3tf” Series In
Columns
Example (pre-5.5 graphs)
Graph Country, Population From Selection
See Also
Set Graph
HomeDirectory$( ) function
Purpose
Returns a string indicating the user’s home directory path.
Syntax
HomeDirectory$( )
Return Value
String
Description
The HomeDirectory$( ) function returns a string which indicates the user’s home directory
path.
The significance of a home directory path depends on the hardware platform on which the user
is running. The table below summarizes the platform-dependent home directory path
definitions.
Example
Dim s_home_dir As String
s_home_dir = HomeDirectory$()
See Also
ApplicationDirectory$( ), ProgramDirectory$( ), SystemInfo( )
If...Then statement
Purpose
Decides which block of statements to execute (if any), based on the current value of one or more
expressions.
Syntax
If if_condition Then
if_statement_list
[ ElseIf elseif_condition Then
elseif_statement_list ]
[ ElseIf ... ]
[ Else
else_statement_list ]
End If
...condition is a condition which will evaluate to TRUE or FALSE
...statement_list is a list of zero or more statements
Restrictions
You cannot issue an If...Then statement through the MapBasic window.
Description
The If ... Then statement allows conditional execution of different groups of statements.
In its simplest form, the If statement does not include an ElseIf clause, nor an Else clause:
If if_condition Then
if_statement_list
End If
With this arrangement, MapBasic evaluates the if_condition at run-time. If the if_condition is
TRUE, MapBasic executes the if_statement_list; otherwise, MapBasic skips the statement_list.
An If statement may also include the optional Else clause:
If if_condition Then
if_statement_list
Else
else_statement_list
End If
With this arrangement, MapBasic will either execute the if_statement_list (if the condition is
TRUE) or the else_statement_list (if the condition is FALSE).
Additionally, an If statement may include one or more ElseIf clauses, following the If clause
(and preceding the optional Else clause) :
If if_condition Then
if_statement_list
ElseIf elseif_condition Then
elseif_statement_list
Else
else_statement_list
End If
With this arrangement, MapBasic tests a series of two or more conditions, continuing until
either one of the conditions turns out to be TRUE or until the Else clause or the End If is
reached. If the if_condition is TRUE, MapBasic will perform the if_statement_list, and then
jump down to the statement which follows the End If. But if that condition is FALSE, MapBasic
then evaluates the else_if_condition; if that condition is TRUE, MapBasic will execute the
elseif_statement_list.
An If statement may include two or more ElseIf clauses, thus allowing you to test any number
of possible conditions. However, if you are testing for one out of a large number of possible
conditions, the Do Case statement is more elegant than an If statement with many ElseIf
clauses.
Example
Dim today As Date
Dim today_mon, today_day, yearcount As Integer
Import statement
Purpose
Creates a new MapInfo Professional table by importing an exported file, such as a GML or DXF
file.
Syntax 1 (for MIF/MID files, PICT files, or MapInfo for DOS files)
Import file_name
[ Type file_type ]
[ Into table_name ]
[ Overwrite ]
Description
The Import statement creates a new MapInfo table by importing the contents of an existing file.
Note: To create a MapInfo table based on a spreadsheet or database file, use the Register Table
statement, not the Import statement.
The Into clause lets you override the name and location of the MapInfo table that is created. If
no Into clause is specified, the new table is created in the same directory location as the original
file, with a corresponding filename. For example, on Windows, if you import the text file
“WORLD.MIF”, the new table’s default name is “WORLD.TAB”.
The optional Type clause specifies the format of the file you want to import. The Type clause
can take one of the following forms:
Autoflip
Include this option if you want the map’s x-coordinates to be flipped around the center line of
the map. This option is only allowed if you specify a non-Earth coordinate system.
Transform
Specifies a coordinate transformation. In the Transform clause, you specify the minimum and
maximum x- and y-coordinates of the imported file, and you specify the minimum and
maximum coordinates that you want to have in the MapInfo table.
Read Integer As Decimal
Include this clause if you want to store whole numbers from the DXF file in a Decimal column
in the new table. This clause is only allowed when you include the Preserve AttributeData
clause.
Read Float As Decimal
Include this clause if you want to store floating-point numbers from the DXF file in a Decimal
column in the new table. This clause is only allowed when you include the Preserve
AttributeData clause.
Store [ Handles ] [ Elevation ] [ VisibleOnly ]
If you include Handles, the MapInfo table stores handles (unique ID numbers of objects in the
drawing) in a column called _DXFHandle. If you include Elevation, MI Pro stores each object’s
center elevation in a column called _DXFElevation. (For lines, MI Pro stores the elevation at the
center of the line; for regions, MI Pro stores the average of the object’s elevation values.) If you
include VisibleOnly, MI Pro ignores invisible objects.
Layer . . .
If you do not include any Layer clauses, all objects from the DXF file are imported into a single
MapInfo table. If you include one or more Layer clauses, each DXF layer that you name
becomes a separate MapInfo table.
If your DXF file contains multiple layers, and if your Import statement includes one or more
Layer clauses, MI Pro only imports the layers that you name. For example, suppose your DXF
file contains four layers (layers 0, 1, 2, and 3). The following Import statement imports all four
layers into a single MapInfo table:
Import ”FLOORS.DXF”
Into ”FLOORS.TAB”
Preserve AttributeData
The following statement imports layers 1 and 3, but does not import layers 0 or 2:
Import ”FLOORS.DXF”
Layer ”1”
Into ”FLOOR_1.TAB”
Preserve AttributeData
Layer ”3”
Into ”FLOOR_3.TAB”
Preserve AttributeData
a warning displays indicating that spatial objects cannot be imported. Access the Browser view
to see the display of attribute data.
Example
The following example imports a MIF (MapInfo Interchange Format) file:
Import ”WORLD.MIF”
Type ”MIF”
Into ”world_2.tab”
See Also
Export
Include statement
Purpose
Incorporates the contents of a separate text file as part of a MapBasic program.
Syntax
Include “filename”
filename is the name of an existing text file
Restrictions
You cannot issue an Include statement through the MapBasic window.
Description
When MapBasic is compiling a program file and encounters an Include statement, the entire
contents of the included file are inserted into the program file. The file specified by an Include
statement should be a text file, containing only legitimate MapBasic statements.
If the filename parameter does not specify a directory path, and if the specified file does not
exist in the current directory, the MapBasic compiler looks for the file in the program directory.
This arrangement allows you to leave standard definitions files, such as MAPBASIC.DEF, in
one directory, rather than copying the definitions files to the directories where you keep your
program files.
The most common use of the Include statement is to include the file of standard MapBasic
definitions, MAPBASIC.DEF. This file, which is provided with MapBasic, defines a number of
important identifiers, such as TRUE and FALSE.
Whenever you change the contents of a file that you use through an Include statement, you
should then recompile any MapBasic programs which Include that file.
Example
Include ”MAPBASIC.DEF”
Input # statement
Purpose
Reads data from a file, and stores the data in variables.
Syntax
Input # filenum, var_name [ , var_name ... ]
filenum is the number of a file opened through Open File
var_name is the name of a variable
Description
The Input # statement reads data from a file which was opened in a sequential mode (e.g.,
INPUT mode), and stores the data in one or more MapBasic variables.
The Input # statement reads data (up to the next end-of-line) into the variable(s) indicated by
the var_name parameter(s). MapInfo Professional treats commas and end-of-line characters as
field delimiters. To read an entire line of text into a single String variable, use Line Input #.
MapBasic automatically converts the data to the type of the variable(s). When reading data into
a String variable, the Input # statement treats a blank line as an empty string. When reading
data into a numeric variable, the Input # statement treats a blank line as a zero value.
After issuing an Input # statement, call the EOF( ) function to determine if MI Pro was able to
read the data. If the input was successful, EOF( ) returns FALSE; if the end-of-file was reached
before the input was completed, EOF( ) returns TRUE.
For an example of the Input # statement, see the sample program NVIEWS (Named Views).
The following data types are not available with the Input # statement: Alias, Pen, Brush, Font,
Symbol, and Object.
See Also
EOF( ), Line Input #, Open File, Write #
Insert statement
Purpose
Appends new rows to an open table.
Syntax
Insert Into table [ ( columnlist ) ]
{ Values ( exprlist ) | Select columnlist From table }
table is the name of an open table
columnlist is a list of column expressions, comma-separated
exprlist is a list of one or more expressions, comma-separated
Description
The Insert statement inserts new rows into an open table. There are two main forms of this
statement, allowing you to either add one row at a time, or insert groups of rows from another
table (via the Select clause). In either case, the number of column values inserted must match
the number of columns in the column list. If no column list is specified, all fields are assumed.
Note that you must use a Commit statement if you want to permanently save newly-inserted
records to disk.
If you know exactly how many columns are in the table you are modifying, and if you have
values to store in each of those columns, then you do not need to specify the optional
(columnlist) clause. In the following example, we know that the table has four columns (Name,
Address, City and State), and we provide MapBasic with a value for each of those columns.
Insert Into customers
Values (”Mary Ryan”, ”23 Main St”, ”Dallas”, ”TX”)
The preceding statement would generate an error at run-time if it turned out that the table had
fewer than (or more than) four columns. In cases where you do not know exactly how many
columns are in a table or the exact order in which the columns appear, you should use the
optional (columnlist) clause.
The following example inserts a new row into the customer table, while providing only one
column value for the new row; thus, all other columns in the new row will initially be blank.
Here, the one value specified by the Values clause will be stored in the “Name” column,
regardless of how many columns are in the table, and regardless of the position of the “Name”
column in the table structure.
Insert Into customers (Name)
Values (”Steve Harris”)
The following statement creates a point object and inserts the object into a new row of the Sites
table. Note that Obj is a special column name representing the table’s graphical objects.
Insert Into sites (Obj)
Values ( CreatePoint(-73.5, 42.8) )
The following example illustrates how the Insert statement can append records from one table
to another. In this example, we assume that the table NY_ZIPS contains ZIP code boundaries
for New York state, and NJ_ZIPS contains ZIP code boundaries for New Jersey. We want to put
all ZIP code boundaries into a single table, for convenience’s sake (since operations such as
Find can only work with one table at a time). Accordingly, the Insert statement below appends
all of the records from the New Jersey table into the New York table.
Insert Into NY_ZIPS
Select * From NJ_ZIPS
In the following example, we select the graphical objects from the table World, then insert each
object as a new record in the table Outline.
Open Table ”world”
Open Table ”outline”
Insert Into outline (Obj)
Select Obj From World
See Also
Commit, Delete, Rollback
InStr( ) function
Purpose
Returns a character position, indicating where a substring first appears within another string.
Syntax
InStr ( position, string, substring )
position is a positive integer, indicating the start position of the search
string is a string expression
substring is a string expression which we will try to locate in string
Return Value
Integer
Description
The InStr( ) function tests whether the string expression string contains the string expression
substring. MapBasic searches the string expression, starting at the position indicated by the
position parameter; thus, if the position parameter has a value of one, MapBasic will search
from the very beginning of the string parameter.
If string does not contain substring, the InStr( ) function returns a value of zero.
If string does contain substring, the InStr( ) function returns the character position where the
substring appears. For example, if the substring appears at the very start of the string, InStr( )
will return a value of one.
If the substring parameter is a null string, the InStr( ) function returns zero.
The InStr( ) function is case-sensitive. In other words, the InStr( ) function cannot locate the
substring “BC” within the larger string “abcde”, because “BC” is upper-case.
Error Conditions
ERR_FCN_ARG_RANGE error generated if an argument is outside of the valid range
Example
Dim fullname As String, pos As Integer
fullname = ”New York City”
pos = InStr(1, fullname, ”York”)
’ pos will now contain a value of 5 (five)
Int( ) function
Purpose
Returns an integer value obtained by removing the fractional part of a decimal value.
Syntax
Int ( num_expr )
num_expr is a numeric expression
Return Value
Integer
Description
The Int( ) function returns the nearest integer value that is less than or equal to the specified
num_expr expression.
The Fix( ) function is similar to, but not identical to, the Int( ) function. The two functions differ
in the way that they treat negative fractional values. When passed a negative fractional
number, Fix( ) will return the nearest integer value greater than or equal to the original value;
thus, the function call
Fix(-2.3)
will return a value of -2. But when the Int( ) function is passed a negative fractional number, it
returns the nearest integer value that is less than or equal to the original value. Thus, the
function call
Int(-2.3)
returns a value of -3.
Example
Dim whole As Integer
whole = Int(5.999)
’ whole now has the value 5
whole = Int(-7.2)
’ whole now has the value -8
See Also
Fix( ), Round( )
IntersectNodes( ) function
Purpose
Calculates the set of points at which two objects intersect, and returns a polyline object that
contains each of the points of intersection.
Syntax
IntersectNodes ( object1, object2, points_to_include )
object1 and object2 are object expressions; may not be point or text objects
points_to_include is one of the following SmallInt values:
INCL_CROSSINGS returns points where segments cross
INCL_COMMON returns end-points of segments that overlap
INCL_ALL returns points where segments cross and points where segments overlap
Return Value
A polyline object that contains the specified points of intersection.
Description
The IntersectNodes( ) function returns a polyline object that contains all nodes at which two
objects intersect.
IsPenWidthPixels( ) function
Purpose
The IsPenWidthPixels function determines if a pen width is in pixels or in points.
Syntax
IsPenWidthPixels ( penwidth )
penwidth is a small integer representing the pen width.
Return Value
True if the width value is in pixels. False if the width value is in points.
Description
The IsPenWidthPixels( ) function will return true if the given pen width is in pixels. The pen
width for a line may be determined using the StylAttr( ) function.
Example
Include “MAPBASIC.DEF”
Dim CurPen As Pen
Dim Width As Integer
Dim PointSize As Float
CurPen = CurrentPen()
Width = StyleAttr(CurPen, PEN_WIDTH)
If Not IsPenWidthPixels(Width) Then
PointSize = PenWidthToPoints(Width)
End If
See Also
CurrentPen(), MakePen(),Pen, PenWidthToPoints()
Kill statement
Purpose
Deletes a file.
Syntax
Kill filespec
filespec is a String which specifies a filename (and, optionally, the file’s path)
Return Value
String
Description
The Kill statement deletes a file from the disk.
There is no “undo” operation for a Kill statement. Therefore, the Kill statement should be used
with caution.
Example
Kill ”C:\TEMP\JUNK.TXT”
See Also
Open File
LabelFindByID( ) function
Purpose
Initializes an internal label pointer, so that you can query the label for a specific row in a map
layer.
Syntax
LabelFindByID( map_window_id , layer_number , row_id , table , b_mapper )
map_window_id is an Integer window id, identifying a Map window
layer_number is the number of a layer in the current Map window (e.g., 1 for the top layer)
row_id is a positive Integer value, indicating the row number of the row whose label you wish
to query.
table is a table name or an empty string (“”): when you query a table that belongs to a seamless
table, specify the name of the member table; otherwise, specify an empty string.
b_mapper is a Logical value. Specify TRUE to query the labels that appear when the Map is
active; specify FALSE to query the labels that appear when the map is inside a Layout.
Return Value
Logical value: TRUE means that a label exists for the specified row.
Description
Call LabelFindByID( ) when you want to query the label for a specific row in a map layer. If the
return value is TRUE, then a label exists for the row, and you can query the label by calling
Labelinfo( ).
Example
The following example maps the World table, displays automatic labels, and then determines
whether a label was drawn for a specific row in the table.
Include ”mapbasic.def”
Dim b_morelabels As Logical
Dim i_mapid As Integer
Dim obj_mytext As Object
If b_morelabels Then
’ The object was labeled; now query its label.
End If
See Also
LabelFindFirst( ), LabelFindNext( ), Labelinfo( )
LabelFindFirst( ) function
Purpose
Initializes an internal label pointer, so that you can query the first label in a map layer.
Syntax
LabelFindFirst( map_window_id , layer_number , b_mapper )
map_window_id is an Integer window id, identifying a Map window
layer_number is the number of a layer in the current Map window (e.g., 1 for the top layer)
b_mapper is a Logical value. Specify TRUE to query the labels that appear when the Map is
active; specify FALSE to query the labels that appear when the map is inside a Layout.
Return Value
Logical value: TRUE means that labels exist for the specified layer (either labels are currently
visible, or the user has edited labels, and those edited labels are not currently visible).
Description
Call LabelFindFirst( ) when you want to loop through a map layer’s labels to query the labels.
Querying labels is a two-step process:
1. Set MapBasic’s internal label pointer by calling one of these functions:
LabelFindFirst( ), LabelFindNext( ), or LabelFindByID( ).
2. If the function you called in step 1 did not return FALSE, you can query the
current label by calling Labelinfo( ).
To continue querying additional labels, return to step 1.
Example
For an example, see Labelinfo( ).
See Also
LabelFindByID( ), LabelFindNext( ), Labelinfo( )
LabelFindNext( ) function
Purpose
Advances the internal label pointer, so that you can query the next label in a map layer.
Syntax
LabelFindNext( map_window_id , layer_number )
map_window_id is an Integer window id, identifying a Map window
layer_number is the number of a layer in the current Map window (e.g., 1 for the top layer)
Return Value
Logical value: TRUE means the label pointer was advanced to the next label; FALSE means
there are no more labels for this layer.
Description
After you call LabelFindFirst( ) to begin querying labels, you can call LabelFindNext( ) to
advance to the next label in the same layer.
Example
For an example, see Labelinfo( ).
See Also
LabelFindByID( ), LabelFindFirst( ), Labelinfo( )
Labelinfo( ) function
Purpose
Returns information about a label in a map.
Syntax
Labelinfo( map_window_id , layer_number , attribute )
map_window_id is an Integer window id, identifying a Map window
layer_number is the number of a layer in the current Map window (e.g., 1 for the top layer)
attribute is a code indicating the type of information to return; see table below
Return Value
Return value depends on attribute.
Description
The Labelinfo( ) function returns information about a label in a Map window. Note: Labels are
different than text objects. To query a text object, call functions such as ObjectInfo( ) or
ObjectGeography( ).
Before calling Labelinfo( ), you must initialize MapBasic’s internal label pointer by calling
LabelFindFirst( ), LabelFindNext( ), or LabelFindByID( ). See example below.
The attribute parameter must be one of the codes from the following table; codes are defined in
MAPBASIC.DEF.
Example
The following example shows how to loop through all of the labels for a row, using the
Labelinfo( ) function to query each label.
Dim b_morelabels As Logical
Dim i_mapid, i_layernum As Integer
Dim obj_mytext As Object
’ Here, you would assign a Map window’s ID to i_mapid,
’ and assign a layer number to i_layernum.
b_morelabels = LabelFindFirst(i_mapid, i_layernum, TRUE)
Do While b_morelabels
obj_mytext = LabelInfo(i_mapid, i_layernum, LABEL_INFO_OBJECT)
’ At this point, you could save the obj_mytext object
’ in a permanent table; or you could query it by
’ calling ObjectInfo() or ObjectGeography().
b_morelabels = LabelFindNext(i_mapid, i_layernum)
Loop
See Also
LabelFindByID( ), LabelFindFirst( ), LabelFindNext( )
LayerInfo( ) function
Purpose
Returns information about a layer in a Map window.
Syntax
LayerInfo( map_window_id , layer_number , attribute )
map_window_id is a Map window identifier
layer_number is the number of a layer in the current Map window (e.g., 1 for the top layer); to
determine the number of layers in a Map window, call MapperInfo( )
attribute is a code indicating the type of information to return; see table below
Return Value
Return value depends on attribute parameter.
Restrictions
Many of the settings that you can query using LayerInfo( ) only apply to conventional map
layers (as opposed to Cosmetic map layers, thematic map layers, and map layers representing
raster image tables). See example below.
Description
The LayerInfo( ) function returns information about one layer in an existing Map window. The
layer_number must be a valid layer (0 is the cosmetic layer, 1 is the topmost table layer, and so
on). The attribute parameter must be one of the codes from the following table; codes are
defined in MAPBASIC.DEF. From here you can also query the Hotlink options using the
Layer_Hotlink attributes.
Example
Many of the settings that you can query using LayerInfo( ) only apply to conventional map
layers (as opposed to cosmetic map layers, thematic map layers, and map layers representing
raster image tables). To determine whether a map layer is a conventional layer, use the
LAYER_INFO_TYPE setting, as shown below:
i_lay_type = LayerInfo( map_id, layer_num, LAYER_INFO_TYPE)
Layout statement
Purpose
Opens a new layout window.
Syntax
Layout
[ Position ( x , y ) [ Units paperunits ] ]
[ Width window_width [ Units paperunits ] ]
[ Height window_height [ Units paperunits ] ]
[ { Min | Max } ]
paperunits is a String representing the name of a paper unit (e.g., “in” or “mm”)
x , y specifies the position of the upper left corner of the Layout, in paper units, where 0,0
represents the upper-left corner of the MapInfo Professional window
window_width and window_height dictate the size of the window, in Paper units
Description
The Layout statement opens a new Layout window. If the statement includes the optional Min
keyword, the window is minimized before it is displayed. If the statement includes the optional
Max keyword, the window appears maximized, filling all of MI Pro ’s screen space.
The Width and Height clauses control the size of the Layout window, not the size of the page
layout itself. The page layout size is controlled by the paper size currently in use and the
number of pages included in the Layout.
See the Set Layout statement for more information on setting the number of pages in a Layout.
MI Pro assigns a special, hidden table name to each Layout window. The first Layout window
opened has the table name Layout1, the next Layout window that is opened has the table name
Layout2, etc.
A MapBasic program can create, select, or modify objects on a Layout window by issuing
statements which refer to these table names. For example, the following statement selects all
objects from a Layout window:
Select * From Layout1
Example
The following example creates a Layout window two inches wide by four inches high, located
at the upper-left corner of the MapInfo workspace.
Layout Position (0, 0) Width 2 Height 4
See Also
Open Window
LCase$( ) function
Purpose
Returns a lower-case equivalent of a string.
Syntax
LCase$( string_expr )
string_expr is a string expression
Return Value
String
Description
The LCase$( ) function returns the string which is the lower-case equivalent of the string
expression string_expr.
Conversion from upper- to lower-case only affects alphabetic characters (A through Z);
numeric digits and punctuation marks are not affected. Thus, the function call:
LCase$( ”A#12a” )
returns the string value “a#12a”.
Example
Dim regular, lower_case As String
regular = ”Los Angeles”
lower_case = LCase$(regular)
’
’ Now, lower_case contains the value ”los angeles”
’
See Also
Proper$( ), UCase$( )
Left$( ) function
Purpose
Returns part or all of a string, beginning at the left end of the string.
Syntax
Left$ ( string_expr, num_expr )
string_expr is a string expression
num_expr is a numeric expression, zero or larger
Return Value
String
Description
The Left$( ) function returns a string which consists of the leftmost num_expr characters of the
string expression string_expr.
The num_expr parameter should be an integer value, zero or larger. If num_expr has a
fractional value, MapBasic rounds to the nearest integer. If num_expr is zero, Left$( ) returns a
null string. If the num_expr parameter is larger than the number of characters in the
string_expr string, Left$( ) returns a copy of the entire string_expr string.
Example
Dim whole, partial As String
whole = ”Afghanistan”
partial = Left$(whole, 6)
LegendFrameInfo( ) function
Purpose
Returns information about a frame within a legend.
Syntax
LegendFrameInfo( window_id, frame_id, attribute )
window_id is a number that specifies which legend window you want to query.
frame_id is a number that specifies which frame within the legend window you want to query.
Frames are numbered 1 to n where n is the number of frames in the legend.
attribute is an integer code indicating which type of information to return.
Return Value
Depends on the attribute parameter.
Attribute codes
FRAME_INFO_TYPE Returns one of the following predefined
constant indicating frame type:
FRAME_TYPE_STYLE
FRAME_TYPE_THEME
FRAME_INFO_MAP_LAYER_ID Returns the id of the layer to which the
frame corresponds.
FRAME_INFO_REFRESHABLE Returns true if the frame was created
without the Norefresh keyword. Always
returns true for theme frames.
FRAME_INFO_POS_X Returns the distance of the frames upper left
corner from the left edge of the legend
canvas (in paper units).
FRAME_INFO_POS_Y Returns the distance of the frame’s upper
left corner from the topt edge of the legend
canvas (in paper units).
FRAME_INFO_WIDTH Returns the width of the frame (in paper
units).
FRAME_INFO_HEIGHT Returns the height of the frame (in paper
units).
FRAME_INFO_TITLE Returns the title of a style frame or theme
frame.
FRAME_INFO_TITLE_FONT Returns the font of a style frame title.
Returns the default title font if the frame has
no title or if it is a theme frame.
FRAME_INFO_SUBTITLE Returns the subtitle of a style frame or
theme frame.
LegendInfo( ) function
Purpose
Returns information about a legend.
Syntax
LegendInfo( window_id, attribute )
window_id is a number that specifies which legend window you want to query.
attribute is an integer code indicating which type of information to return.
Return Value
Depends on the attribute parameter.
See Also:
LegendStyleInfo( ) function
LegendStyleInfo( ) function
Purpose
Returns information about a style item within a legend frame.
Syntax
LegendInfo( window_id,, frame_id, style_id, attribute )
window_id is a number that specifies which legend window you want to query.
frame_id is a number that specifies which frame within the legend window you want to query.
Frames are numbered 1 to n where n is the number of frames in the legend.
style_id is a number that specifies which style within a frame you want to query. Styles are
numbered 1 to n where n is the number of styles in the frame.
attribute is an integer code indicating which type of information to return.
Return Value
Error Conditions
Generates an error when issued on a frame that has no styles (theme frame).
See Also
LegendInfo( )
Len( ) function
Purpose
Returns the number of characters in a string or the number of bytes in a variable.
Syntax
Len( expr )
expr is a variable expression. expr cannot be a Pen, Brush, Symbol, Font, or Alias.
Return Value
SmallInt
Description
The behavior of the Len( ) function depends on the data type of the expr parameter.
If the expr expression represents a character string, the Len( ) function returns the number of
characters in the string.
Otherwise, if expr is a MapBasic variable, Len( ) returns the size of the variable, in bytes. Thus,
if you pass an Integer variable, Len( ) will return the value 4 (because each Integer variable
occupies 4 bytes), while if you pass a SmallInt variable, Len( ) will return the value 2 (because
each SmallInt variable occupies 2 bytes).
Example
Dim name_length As SmallInt
name_length = Len(”Boswell”)
Like( ) function
Purpose
Returns TRUE or FALSE to indicate whether a string satisfies pattern-matching criteria.
Syntax
Like( string , pattern_string , escape_char )
string is a String expression to test
pattern_string is a string that contains regular characters or special wild-card characters
escape_char is a String expression defining an escape character. Use an escape character (e.g.,
“\”) if you need to test for the presence of one of the wild-card characters (“%” and “_”) in the
string expression. If no escape character is desired, use an empty string (“”)
Return Value
Logical value (TRUE if string matches pattern_string)
Description
The Like( ) function performs string pattern-matching. This string comparison is case-sensitive;
to perform a comparison that is case-insensitive, use the Like operator.
The pattern_string parameter can contain the following wild-card characters:
See Also
Len(), StringCompare()
LocateFile$( ) function
Purpose
Return the path to one of the MapInfo application data files.
Syntax
LocateFile$( file_id )
file_id is one of the following values
Returns
String
Description
Given the id of a MapInfo application data file, this function returns the location where
MapInfo Professional found that file. In versions prior to 6.5 these files where, for the most
part, installed into the program directory (same directory as mapinfow.exe).
As of 6.5, MI Pro installs these files under the user's Application Data directory, but there are
several valid locations for these files, including the program directory. MapBasic applications
should not assume the location of these files, instead LocateFile$() should be used to determine
the actual location.
Example
include "mapbasic.def"
declare sub main
sub main
dim sGraphLocations as string
sGraphLocations = LocateFile$(LOCATE_GRAPH_DIR)
Print sGraphLocations
end sub
See Also
GetFolderPath$( )
LOF( ) function
Purpose
Returns the length of an open file.
Syntax
LOF ( filenum )
filenum is the number of an open file
Return Value
Integer
Description
The LOF( ) function returns the length of an open file, in bytes.
The file parameter represents the number of an open file; this is the same number specified in
the As clause of the Open File statement.
Error Conditions
ERR_FILEMGR_NOTOPEN error generated if the specified file is not open
Example
Dim size As Integer
Open File ”import.txt” For Binary As #1
size = LOF(1)
’ size now contains the # of bytes in the file
See Also
Open File
Log( ) function
Purpose
Returns the natural logarithm of a number.
Syntax
Log ( num_expr )
num_expr is a numeric expression
Return Value
Float
Description
The Log( ) function returns the natural logarithm of the numeric expression specified by the
num_expr parameter.
The natural logarithm represents the number to which the mathematical value e must be raised
in order to obtain num_expr. e has a value of approximately 2.7182818.
The logarithm is only defined for positive numbers; accordingly, the Log( ) function will
generate an error if num_expr has a negative value.
You can calculate logarithmic values in other bases (e.g., base 10) using the natural logarithm.
To obtain the base-10 logarithm of the number n, divide the natural log of n ( Log( n ) ) by the
natural logarithm of 10 ( Log( 10 ) ).
Example
Dim original_val, log_val As Float
original_val = 2.7182818
log_val = Log(original_val)
LTrim$( ) function
Purpose
Trims space characters from the beginning of a string and returns the results.
Syntax
LTrim$( string_expr )
string_expr is a string expression
Return Value
String
Description
The LTrim$( ) function removes any spaces from the beginning of the string_expr string, and
returns the resultant string.
Example
Dim name As String
name = ” Mary Smith”
name = LTrim$(name)
Main procedure
Purpose
The first procedure called when an application is run.
Syntax
Declare Sub Main
Sub Main
statement_list
End Sub
statement_list is a list of statements to execute when an application is run
Description
Main is a special-purpose MapBasic procedure name. If an application contains a sub
procedure called Main, MapInfo Professional runs that procedure automatically when the
application is first run. The Main procedure can then take actions (for example, issuing Call
statements) to cause other sub procedures to be executed.
However, you are not required to explicitly declare the Main procedure. Instead of declaring a
procedure named Main, you can simply place one or more statements at or near the top of your
program file, outside of any procedure declaration. MapBasic will then treat that group of
statements as if they were in a Main procedure. This is known as an “implicit” Main procedure
(as opposed to an “explicit” Main procedure).
Example
A MapBasic program can be as short as a single line. For example, you could create a MapBasic
program consisting only of the following statement:
Note ”Testing, one two three.”
If the statement above comprises your entire program, MapBasic considers that program to be
in an implicit Main procedure. When you run that application, MapBasic will execute the Note
statement.
Alternately, the following example explicitly declares the Main procedure, producing the same
results (i.e. a Note statement).
Declare Sub Main
Sub Main
Note ”Testing, one two three.”
End Sub
The next example contains an implicit Main procedure, and a separate sub procedure called
Talk. The implicit Main procedure calls the Talk procedure through the Call statement.
Declare Sub Talk(ByVal msg As String)
Call Talk(”Hello”)
Call Talk(”Goodbye”)
Sub Talk(ByVal msg As String)
Note msg
End Sub
The next example contains an explicit Main procedure, and a separate sub procedure called
Talk. The Main procedure calls the Talk procedure through the Call statement.
Declare Sub Main
Declare Sub Talk(ByVal msg As String)
Sub Main
Call Talk(”Hello”)
Call Talk(”Goodbye”)
End Sub
MakeBrush( ) function
Purpose
Returns a Brush value.
Syntax
MakeBrush( pattern, forecolor, backcolor)
pattern is an Integer value from 1 to 8 or from 12 to 71, dictating a fill pattern. See Brush clause
for a listing of the patterns.
forecolor is the Integer RGB color value of the foreground of the pattern. See the RGB( )
function for details.
backcolor is the Integer RGB color value of the background of the pattern. To make the
background transparent, specify -1 as the background color, and specify a pattern of 3 or
greater.
Return Value
Brush
Description
The MakeBrush function returns a Brush value. The return value can be assigned to a Brush
variable, or may be used as a parameter within a statement that takes a Brush setting as a
parameter (such as Create Ellipse, Set Map, Set Style, or Shade).
See the description of the Brush clause for more information about Brush settings.
Example
Include ”mapbasic.def”
Dim b_water As Brush
b_water = MakeBrush(64, CYAN, BLUE)
See Also
Brush, CurrentBrush( ), StyleAttr( )
MakeCustomSymbol( ) function
Purpose
Returns a Symbol value based on a bitmap file.
Syntax
MakeCustomSymbol( filename, color, size, customstyle )
filename is a string up to 31 characters long, representing the name of a bitmap file. The file
must be in the CustSymb directory inside the user’s MapInfo directory.
color is an integer RGB color value; see the RGB( ) function for details.
size is an Integer point size, from 1 to 48.
customstyle is an Integer code controlling color and background attributes. See table below.
Return Value
Symbol
Description
The MakeCustomSymbol( ) function returns a Symbol value based on a bitmap file. See the
description of the Symbol clause for information about other symbol types.
The following table describes how the customstyle argument controls the symbol’s style:
Example
Include ”mapbasic.def”
Dim sym_marker As Symbol
sym_marker = MakeCustomSymbol(”CAR1-64.BMP”, BLUE, 18, 0)
See Also
CurrentSymbol( ), MakeFontSymbol( ), MakeSymbol( ), StyleAttr( ), Symbol
MakeFont( ) function
Purpose
Returns a Font value.
Syntax
MakeFont( fontname, style, size, forecolor, backcolor )
fontname is a text string specifying a font (e.g., “Helv”). This argument is case sensitive.
style is a positive integer expression; 0 = plain text, 1 = bold text, etc. See Font clause for details.
size is an integer point size, one or greater
forecolor is the RGB color value for the text. See the RGB( ) function.
backcolor is the RGB color value for the background (or the halo color, if the style setting
specifies a halo). To make the background transparent, specify -1 as the background color.
Return Value
Font
Description
The MakeFont( ) function returns a Font value. The return value can be assigned to a Font
variable, or may be used as a parameter within a statement that takes a Font setting as a
parameter (such as Create Text or Set Style).
See the description of the Font clause for more information about Font settings.
Example
Include ”mapbasic.def”
Dim big_title As Font
big_title = MakeFont(”Helvetica”, 1, 20,BLACK,WHITE)
See Also
CurrentFont( ), Font, StyleAttr( )
MakeFontSymbol( ) function
Purpose
Returns a Symbol value, using a character from a TrueType font as the symbol.
Syntax
MakeFontSymbol( shape, color, size, fontname, fontstyle, rotation )
shape is a SmallInt value, 31 or larger (31 is invisible), specifying a character code from a
TrueType font.
color is an integer RGB color value; see the RGB( ) function for details.
size is a SmallInt value from 1 to 48, dictating the point size of the symbol.
fontname is a string representing the name of a TrueType font (e.g., “WingDings”). This
argument is case sensitive.
fontstyle is a numeric code controlling bold, outline, and other attributes; see below.
rotation is a floating-point number indicating the symbol’s rotation angle, in degrees.
Return Value
Symbol
Description
The MakeFontSymbol function returns a Symbol value based on a character in a TrueType font.
See the description of the Symbol clause for information about other symbol types.
The following table describes how the fontstyle argument controls the symbol’s style:
MakePen( ) function
Purpose
Returns a Pen value.
Syntax
MakePen( width, pattern, color)
width specifies a pen width
pattern specifies a line pattern; see Pen clause for a listing
color is the RGB color value; see the RGB( ) function for details
Return Value
Pen
Description
The MakePen( ) function returns a Pen value, which defines a line style. The return value can be
assigned to a Pen variable, or may be used as a parameter within a statement that takes a Pen
setting as a parameter (such as Create Line, Create Polyline, Set Style, or Set Map).
See the description of the Pen clause for more information about Pen settings.
Example
Include ”mapbasic.def”
Dim p_bus_route As Pen
p_bus_route = MakePen(3, 9, RED)
See Also
CurrentPen( ), Pen, StyleAttr( )
MakeSymbol( ) function
Purpose
Returns a Symbol value, using a character from the MapInfo 3.0 symbol set. The MapInfo 3.0
symbol set is the symbol set that was originally published with MapInfo for Windows 3.0 and
has been maintained in subsequent versions of MapInfo Professional.
Syntax
MakeSymbol( shape, color, size )
shape is a SmallInt value, 31 or larger (31 is invisible), specifying a symbol shape; standard
symbol set provides symbols 31 through 67; see Symbol clause for a listing
color is an integer RGB color value; see the RGB( ) function for details
size is a SmallInt value from 1 to 48, dictating the point size of the symbol
Return Value
Symbol
Description
The MakeSymbol( ) function returns a Symbol value. The return value can be assigned to a
Symbol variable, or may be used as a parameter within a statement that takes a Symbol setting
as a parameter (such as Create Point, Set Map, Set Style, or Shade).
To create a symbol from a character in a TrueType font, call MakeFontSymbol( ).
To create a symbol from a bitmap file, call MakeCustomSymbol( ).
See the description of the Symbol clause for more information about Symbol settings.
Example
Include ”mapbasic.def”
Dim sym_marker As Symbol
sym_marker = MakeSymbol(44, RED, 16)
See Also
CurrentSymbol( ), MakeCustomSymbol( ), MakeFontSymbol( ), StyleAttr( ), Symbol
Map statement
Purpose
Opens a new Map window.
Syntax
Map From table [ , table ... ]
[ Position ( x, y ) [ Units paperunits ] ]
[ Width window_width [ Units paperunits ] ]
[ Height window_height [ Units paperunits ] ]
[ { Min | Max } ]
table is the name of an open table
paperunits is the name of a paper unit (e.g., “in”)
x , y specifies the position of the upper left corner of the Map window, in paper units
window_width and window_height specify the size of the Map window, in paper units
Description
The Map statement opens a new Map window. After you open a Map window, you can modify
the window by issuing Set Map statements.
The table name specified must already be open. The table must also be mappable; in other
words, the table must be able to have graphic objects associated with the records. The table
does not need to actually contain any graphical objects, but the structure of the table must
specify that objects may be attached.
The Map statement must specify at least one table, since any Map window must contain at least
one layer. Optionally, the Map statement can specify multiple table names (separated by
commas) to open a multi-layer Map window. The first table name in the Map statement will be
drawn last whenever the Map window is redrawn; thus, the first table in the Map statement
will always appear on top. Typically, tables with point objects appear earlier in Map statements,
and tables with region (boundary) objects appear later in Map statements.
The default size of the resultant Map window is roughly a quarter of the screen size; the default
position of the window depends on how many windows are currently on the screen. Optional
Position, Height, and Width clauses allow you to control the size and position of the new Map
window. The Height and Width clauses dictate the window size, in inches. Note that the
Position clause specifies a position relative to the upper left corner of the MapInfo application,
not relative to the upper left corner of the screen (although this distinction is meaningless on a
Macintosh).
If the Map statement includes the optional Max keyword, the new Map window is maximized,
taking up all of the screen space available to MI Pro. Conversely, if the Map statement includes
the Min keyword, the window is minimized immediately; note that some hardware platforms
(e.g., Macintosh) do not support minimized windows.
Each Map window can have its own projection. MI Pro decides a Map window’s initial
projection based on the native projection of the first table mapped. A user can change a map’s
projection by choosing the Map > Options command. A MapBasic program can change the
projection by issuing a Set Map statement.
Example
The following example opens a Map window three inches wide by two inches high, inset one
inch from the upper left corner of the MapInfo application. The map has two layers.
Open Table ”world”
Open Table ”cust1994” As customers
Map from customers, world
Position (1,1) Width 3 Height 2
See Also
Add Map, Remove Map, Set Map, Set Shade, Shade
Map3dInfo( ) function
Purpose
Returns properties of a 3DMap window.
Syntax
Map3DInfo( window_id , attribute )
window_id is an Integer window identifier
attribute is an Integer code, indicating which type of information should be returned.
Returns
Float, Logical, or String, depending on the attribute parameter.
Description
The Map3DInfo() function returns information about a 3DMap window.
The window_id parameter specifies which 3DMap window to query. To obtain a window
identifier, call the FrontWindow() function immediately after opening a window, or call the
WindowID() function at any time after the window’s creation.
There are several numeric attributes that Map3DInfo() can return about any given 3DMap
window. The attribute parameter tells the Map3DInfo() function which Map window statistic
to return. The attribute parameter should be one of the codes from the following table; codes
are defined in MAPBASIC.DEF.
Example
Prints out all the state variables specific to the 3DMap window:
include ”Mapbasic.def”
Print ”MAP3D_INFO_SCALE: ” + Map3DInfo(FrontWindow(),
MAP3D_INFO_SCALE)
Print ”MAP3D_INFO_RESOLUTION_X: ” + Map3DInfo(FrontWindow(),
MAP3D_INFO_RESOLUTION_X)
Print ”MAP3D_INFO_RESOLUTION_Y: ” + Map3DInfo(FrontWindow(),
MAP3D_INFO_RESOLUTION_Y)
Print ”MAP3D_INFO_BACKGROUND: ” + Map3DInfo(FrontWindow(),
MAP3D_INFO_BACKGROUND)
Print ”MAP3D_INFO_UNITS: ” + Map3DInfo(FrontWindow(),
MAP3D_INFO_UNITS)
Print ”MAP3D_INFO_LIGHT_X : ” + Map3DInfo(FrontWindow(),
MAP3D_INFO_LIGHT_X )
Print ”MAP3D_INFO_LIGHT_Y : ” + Map3DInfo(FrontWindow(),
MAP3D_INFO_LIGHT_Y )
Print ”MAP3D_INFO_LIGHT_Z: ” + Map3DInfo(FrontWindow(),
MAP3D_INFO_LIGHT_Z)
Print ”MAP3D_INFO_LIGHT_COLOR: ” + Map3DInfo(FrontWindow(),
MAP3D_INFO_LIGHT_COLOR)
Print ”MAP3D_INFO_CAMERA_X: ” + Map3DInfo(FrontWindow(),
MAP3D_INFO_CAMERA_X)
Print ”MAP3D_INFO_CAMERA_Y : ” + Map3DInfo(FrontWindow(),
MAP3D_INFO_CAMERA_Y )
Print ”MAP3D_INFO_CAMERA_Z : ” + Map3DInfo(FrontWindow(),
MAP3D_INFO_CAMERA_Z )
Print ”MAP3D_INFO_CAMERA_FOCAL_X: ” + Map3DInfo(FrontWindow(),
MAP3D_INFO_CAMERA_FOCAL_X)
Print ”MAP3D_INFO_CAMERA_FOCAL_Y: ” + Map3DInfo(FrontWindow(),
MAP3D_INFO_CAMERA_FOCAL_Y)
Print ”MAP3D_INFO_CAMERA_FOCAL_Z: ” + Map3DInfo(FrontWindow(),
MAP3D_INFO_CAMERA_FOCAL_Z)
Print ”MAP3D_INFO_CAMERA_VU_1: ” + Map3DInfo(FrontWindow(),
MAP3D_INFO_CAMERA_VU_1)
Print ”MAP3D_INFO_CAMERA_VU_2: ” + Map3DInfo(FrontWindow(),
MAP3D_INFO_CAMERA_VU_2)
Print ”MAP3D_INFO_CAMERA_VU_3: ” + Map3DInfo(FrontWindow(),
MAP3D_INFO_CAMERA_VU_3)
Print ”MAP3D_INFO_CAMERA_VPN_1: ” + Map3DInfo(FrontWindow(),
MAP3D_INFO_CAMERA_VPN_1)
Print ”MAP3D_INFO_CAMERA_VPN_2: ” + Map3DInfo(FrontWindow(),
MAP3D_INFO_CAMERA_VPN_2)
Print ”MAP3D_INFO_CAMERA_VPN_3: ” + Map3DInfo(FrontWindow(),
MAP3D_INFO_CAMERA_VPN_3)
Print ”MAP3D_INFO_CAMERA_CLIP_NEAR: ” + Map3DInfo(FrontWindow(),
MAP3D_INFO_CAMERA_CLIP_NEAR)
Print ”MAP3D_INFO_CAMERA_CLIP_FAR: ” + Map3DInfo(FrontWindow(),
MAP3D_INFO_CAMERA_CLIP_FAR)
See Also
Create Map3D statement, Set Map3D statement
MapperInfo( ) function
Purpose
Returns coordinate or distance information about a Map window.
Syntax
MapperInfo( window_id , attribute )
window_id is an Integer window identifier
attribute is an Integer code, indicating which type of information should be returned
Return Value
Float, Logical, or String, depending on the attribute parameter
Description
The MapperInfo( ) function returns information about a Map window.
The window_id parameter specifies which Map window to query. To obtain a window
identifier, call the FrontWindow( ) function immediately after opening a window, or call the
WindowID( ) function at any time after the window’s creation.
There are several numeric attributes that MapperInfo( ) can return about any given Map
window. The attribute parameter tells the MapperInfo( ) function which Map window statistic
to return. The attribute parameter should be one of the codes from the following table; codes
are defined in MAPBASIC.DEF.
MAPPER_INFO_DISPLAY_ZOOM
MAPPER_INFO_DISPLAY_POSITION
MAPPER_INFO_DISTUNITS String representing the map’s abbreviated
distance unit name, e.g., “mi” for miles.
MAPPER_INFO_MOVE_DUPLICATE_NODES
Small integer, indicating whether duplicate
nodes should be moved when reshaping
objects in this Map window. If the value is 0,
duplicate nodes are not moved. If the value
is 1, any duplicate nodes within the same
layer will be move. The attribute.
A setting for each Map window and providing MapBasic support to set and get the current
setting for each mapper. During Reshape, the move duplicate nodes can be set to none or move
all duplicates within the same layer.
Whenever a new Map window is created, the initial move duplicate nodes setting will be
retrieved from the mapper preference (Options / Preference / Map Window / Move Duplicate
Nodes in).
An existing Map window can be queried for it’s current Move Duplicate Nodes setting using a
new attribute in MapperInfo( ) function.
The current state can be changed for a mapper window using the Set Map MapBasic statement.
Coordinate Value Returns
MapperInfo() does not return coordinates (i.e. MINX, MAXX, MINY, MAXY) in the units set
for the map window. Instead, the coordinate values are returned in the units of the internal
coordinate system of the MI Pro session or the MapBasic application that calls the function (if
the coordinate system was changed within the application). Also, the
MAPPER_INFO_XYUNITS attribute returns the units that are used to display the cursor
location in the Status Bar (set by using Set Map Window Frontwindow() XY Units).
Maximum( ) function
Purpose
Returns the larger of two numbers.
Syntax
Maximum( num_expr , num_expr )
num_expr is a numeric expression
Return Value
Float
Description
The Maximum( ) function returns the larger of two numeric expressions.
Example
Dim x, y, z As Float
x = 42
y = 27
z = Maximum(x, y)
MBR( ) function
Purpose
Returns a rectangle object, representing the minimum bounding rectangle of another object.
Syntax
MBR( obj_expr )
obj_expr is an object expression
Return Value
Object (a rectangle)
Description
The MBR( ) function calculates the minimum bounding rectangle (or MBR) which encompasses
the specified obj_expr object.
A minimum bounding rectangle is defined as being the smallest rectangle which is large
enough to encompass a particular object. In other words, the MBR of the United States extends
east to the eastern tip of Maine, south to the southern tip of Hawaii, west to the western tip of
Alaska, and north to the northern tip of Alaska.
The MBR of a point object has zero width and zero height.
Example
Dim o_mbr As Object
Open Table ”world”
Fetch First From world
o_mbr = MBR(world.obj)
See Also
Centroid( ), CentroidX( ), CentroidY( )
MenuitemInfoByHandler( ) function
Purpose
Returns information about a MapInfo Professional menu item.
Syntax
MenuitemInfoByHandler( handler , attribute )
handler is either a string (containing the name of a handler procedure specified in a Calling
clause) or an Integer (which was specified as a constant in a Calling clause)
attribute is an Integer code indicating which attribute to return; see table below
Description
The handler parameter can be an integer or a string. If you specify a string (a procedure name),
and if two or more menu items call that procedure, MI Pro returns information about the first
menu item that calls the procedure. If you need to query multiple menu items that call the same
handler procedure, give each menu item an ID number (e.g., using the optional ID clause in the
Create Menu statement), and call MenuitemInfoByID( ) instead of calling
MenuitemInfoByHandler( ).
The attribute parameter is a numeric code (defined in MAPBASIC.DEF) from the following
table:
See Also
MenuItemInfoByID( )
MenuitemInfoByID( ) function
Purpose
Returns information about a MapInfo Professional menu item.
Syntax
MenuitemInfoByID( menuitem_ID , attribute )
menuitem_ID is an Integer menu ID (specified in the ID clause in Create Menu)
attribute is an Integer code indicating which attribute to return
Description
This function is identical to the MenuitemInfoByHandler( ) function, except that the first
argument to this function is an Integer ID.
Call this function to query the status of a menu item when you know the ID of the menu item
you need to query. Call MenuitemInfoByHandler( ) to query the status of a menu item if you
would rather identify the menu item by its handler.
The attribute argument is a code from MAPBASIC.DEF, such as
MENUITEM_INFO_CHECKED. For a listing of codes you can use, see
MenuitemInfoByHandler( ).
See Also
MenuItemInfoByHandler( )
Metadata statement
Purpose
Manages a table’s metadata.
Syntax 1
Metadata Table table_name
{ SetKey key_name To key_value |
DropKey key_name [ Hierarchical ] |
SetTraverse starting_key_name [ Hierarchical ] Into ID traverse_ID_var }
table_name is the name of an open table.
key_name is a string, representing the name of a metadata key. The string must start with a
backslash (“\”), and it cannot end with a backslash.
key_value is a string up to 239 characters long, representing the value to assign to the key.
starting_key_name is a string representing the first key name to retrieve from the table. To set
up the traversal at the very beginning of the list of keys, specify “\” (backslash).
traverse_ID_var is the name of an Integer variable; MI Pro stores a traversal ID in the variable,
which you can use in subsequent Metadata Traverse... statements.
Syntax 2
Metadata Traverse traverse_ID
{ Next Into Key key_name_var Into Value key_value_var |
Destroy }
traverse_ID is an Integer value (such as the value of the traverse_ID_var variable described
above).
key_name_var is the name of a string variable; MI Pro stores the fetched key’s name in this
variable.
key_value_var is the name of a string variable; MI Pro stores the fetched key’s value in this
variable.
Description
The Metadata statement manages the metadata stored in MapInfo tables, versions 4.0 and later.
Metadata is information that is stored in a table’s .TAB file, instead of being stored as rows and
columns.
Each table can have zero or more keys. Each key represents an information category, such as an
author’s name, a copyright notice, etc. Each key has a string value associated with it. For
example, a key called “\Copyright” might have the value “Copyright 2001 MapInfo
Corporation.” For more information about Metadata, see the MapBasic User’s Guide.
Note: MI Pro automatically creates a metadata key called “\IsReadOnly” (with a default value
of “FALSE”) the first time you add a metadata key to a table. The \IsReadOnly key is a special
key, reserved for internal use by MI Pro.
DropKey
Deletes the specified key from the table. If you include the Hierarchical keyword, MI Pro
deletes the entire metadata hierarchy at and beneath the specified key. For example, if a table
has the keys “\Info\Author” and “\Info\Date” you can delete both keys with the following
statement:
MetaData Table Parcels DropKey ”\Info” Hierarchical
Example
The following procedure reads all metadata values from a table; the table name is specified by
the caller. This procedure prints the key names and key values to the Message window.
Sub Print_Metadata(ByVal table_name As String)
Dim i_traversal As Integer
Dim s_keyname, s_keyvalue As String
End Sub
See Also
GetMetadata$( ), TableInfo( )
Mid$( ) function
Purpose
Returns a string extracted from the middle of another string.
Syntax
Mid$( string_expr, position, length )
string_expr is a string expression
position is a numeric expression, indicating a starting position in the string
length is a numeric expression, indicating the number of characters to extract
Return Value
String
Description
The Mid$( ) function returns a substring copied from the specified string_expr string.
Mid$( ) copies length characters from the string_expr string, starting at the character position
indicated by position. A position value less than or equal to one tells MapBasic to copy from the
very beginning of the string_expr string.
If the string_expr string is not long enough, there may not be length characters to copy; thus,
depending on all of the parameters, the Mid$( ) may or may not return a string length
characters long. If the position parameter represents a number larger than the number of
characters in string_expr, Mid$( ) returns a null string. If the length parameter is zero, Mid$( )
returns a null string. If the length or position parameters are fractional, MapBasic rounds to the
nearest integer.
Example
Dim str_var, substr_var As String
str_var = ”New York City”
substr_var = Mid$(str_var, 10, 4)
MidByte$( ) function
Purpose
Accesses individual bytes of a string on a system with a double-byte character system.
Syntax
MidByte$( string_expr, position, length )
string_expr is a string expression
position is an integer numeric expression, indicating a starting position in the string
length is an integer numeric expression, indicating the number of bytes to return
Return Value
String
Description
The MidByte$( ) function returns individual bytes of a string.
Use the MidByte$( ) function when you need to extract a range of bytes from a string, and the
application is running on a system that uses a double-byte character set (DBCS systems). For
example, the Japanese version of Microsoft Windows uses a double-byte character system.
On systems with single-byte character sets, the results returned by the MidByte$( ) function are
identical to the results returned by the Mid$( ) function.
See Also
InStr( ), Left$( ), Right$( )
Minimum( ) function
Purpose
Returns the smaller of two numbers.
Syntax
Minimum( num_expr , num_expr )
num_expr is a numeric expression
Return Value
Float
Description
The Minimum( ) function returns the smaller of two numeric expressions.
Example
Dim x, y, z As Float
x = 42
y = -100
z = Minimum(x, y)
Month( ) function
Purpose
Returns the month component (1 - 12) of a date value.
Syntax
Month( date_expr )
date_expr is a date expression
Return Value
SmallInt value from 1 to 12, inclusive
Description
The Month( ) function returns an integer, representing the month component (one to twelve) of
the specified date.
Examples
The following example shows how you can extract just the month component from a particular
date value, using the Month( ) function.
If Month(CurDate()) = 12 Then
’
’ ... then it is December...
’
End If
You can also use the Month( ) function within the SQL Select statement. The following Select
statement extracts only particular rows from the Orders table. This example assumes that the
Orders table has a Date column, called Order_Date. The Select statement’s Where clause tells
MI Pro to only select the orders from December of 1993.
Open Table ”orders”
Select *
From orders
Where Month(orderdate) = 12 And Year(orderdate) = 1993
See Also
CurDate( ), Day( ), Weekday( ), Year( )
Note statement
Purpose
Displays a simple message in a dialog box.
Syntax
Note message
message is an expression to be displayed in a dialog
Description
The Note statement creates a dialog to display a message. The dialog contains an OK menu
button; the message dialog remains on the screen until the user clicks the Ok button.
The message expression does not need to be a string expression. If message is an object
expression, MapBasic will automatically produce an appropriate string (e.g., “Region”) for
display in the Note dialog. If the message expression is a string, the string can be up to 300
characters long, and can occupy up to 6 rows.
Example
Note ”Total # of records processed: ” + Str$( i_count )
See Also
Ask( ), Dialog, Print
NumAllWindows( ) function
Purpose
Returns the number of windows owned by MapInfo Professional, including special windows
such as ButtonPads and the Info window.
Syntax
NumAllWindows( )
Return Value
SmallInt
Description
The NumAllWindows( ) function returns the number of windows owned by MI Pro.
To determine the number of document windows opened by MI Pro (Map, Browse, Graph, and
Layout windows), call NumWindows( ).
See Also
NumWindows( ), WindowID( )
NumberToDate( ) function
Purpose
Returns a Date value, given an Integer.
Syntax
NumberToDate ( numeric_date )
numeric_date is an eight-digit Integer in the form YYYYMMDD (e.g., 19951231)
Return Value
Date
Description
The NumberToDate( ) function returns a Date value represented by an eight-digit Integer. For
example, the following function call returns a Date value of December 31, 1995:
NumberToDate(19951231)
Example
The following example subtracts one Date value from another Date. The result of the
subtraction is the number of days between the two dates.
Dim i_elapsed As Integer
NumCols( ) function
Purpose
Returns the number of columns in a specified table.
Syntax
NumCols ( table )
table is the name of an open table
Return Value
SmallInt
Description
The NumCols( ) function returns the number of columns contained in the specified open table.
The number of columns returned by NumCols( ) does not include the special column known as
Object (or Obj for short), which refers to the graphical objects attached to mappable tables.
Similarly, the number of columns returned does not include the special column known as
RowID.
Note: If a table has temporary columns (e.g., because of an Add Column statement), the
number returned by NumCols( ) includes the temporary column(s).
Error Conditions
ERR_TABLE_NOT_FOUND error generated if the specified table is not available
Example
Dim i_counter As Integer
Open Table ”world”
i_counter = NumCols(world)
See Also
ColumnInfo( ), NumTables( ), TableInfo( )
NumTables( ) function
Purpose
Returns the number of tables currently open.
Syntax
NumTables( )
Return Value
Smallint
Description
The NumTables( ) function returns the number of tables that are currently open.
A street-map table may consist of two “companion” tables. For example, when you open the
Washington, DC street map named DCWASHS, MapInfo Professional secretly opens the two
companion tables DCWASHS1.TAB and DCWASHS2.TAB. However, MI Pro treats the
DCWASHS table as a single table; for example, the Layer Control dialog box shows only the
table name DCWASHS. Similarly, the NumTables( ) function counts a street map as a single
table, although it may actually be composed of two companion tables.
Example
If NumTables() < 1 Then
Note ”You must open a table before continuing.”
End If
See Also
Open Table, TableInfo( ), ColumnInfo( )
NumWindows( ) function
Purpose
Returns the number of open document windows (Map, Browse, Graph, Layout).
Syntax
NumWindows( )
Return Value
SmallInt
Description
The NumWindows( ) function returns the number of Map, Browse, Graph, and Layout
windows that are currently open. The result is independent of whether windows are
minimized or not.
To determine the total number of windows opened by MapInfo Professional (including
ButtonPads and special windows such as the Info window), call NumAllWindows( ).
Example
Dim num_open_wins As SmallInt
num_open_wins = NumWindows()
See Also
NumAllWindows( ), WindowID( )
ObjectGeography( ) function
Purpose
Returns coordinate or angle information describing a graphical object.
Syntax
ObjectGeography( object , attribute )
object is an Object expression
attribute is an Integer code specifying which type of information should be returned
Return Value
Float
Description
The attribute parameter controls which type of information will be returned. The table below
summarizes the different codes that you can use as the attribute parameter; codes in the left
column (e.g., OBJ_GEO_MINX) are defined in MAPBASIC.DEF.
Some attributes apply only to certain types of objects. For example, arc objects are the only
objects with begin-angle or end-angle attributes, and text objects are the only objects with the
text-angle attribute.
Example
The following example reads the starting coordinates of a line object from the table City. A Set
Map statement then uses these coordinates to re-center the Map window.
Include ”MAPBASIC.DEF”
Dim i_obj_type As Integer, f_x, f_y As Float
Open Table ”city”
Map From city
Fetch First From city
’ at this point, the expression:
’ city.obj
’ represents the graphical object that’s attached
’ to the first record of the CITY table.
i_obj_type = ObjectInfo(city.obj, OBJ_INFO_TYPE)
If i_obj_type = OBJ_LINE Then
f_x = ObjectGeography(city.obj, OBJ_GEO_LINEBEGX)
f_y = ObjectGeography(city.obj, OBJ_GEO_LINEBEGY)
Set Map Center (f_x, f_y)
End If
See Also
Centroid( ), CentroidX( ), CentroidY( ), ObjectInfo( )
ObjectInfo( ) function
Purpose
Returns Pen, Brush, or other values describing a graphical object.
Syntax
ObjectInfo( object , attribute )
object is an Object expression
attribute is an Integer code specifying which type of information should be returned
Return Value
SmallInt, Integer, String, Float, Pen, Brush, Symbol, or Font, depending on the attribute
parameter
Description
The ObjectInfo( ) function returns general information about one aspect of a graphical object.
The first parameter should be an object value (e.g., the name of an Object variable, or a table
expression of the form tablename.obj).
Each object has several attributes. For example, each object has a “type” attribute, identifying
whether the object is a point, a line, or a region, etc. Most types of objects have Pen and/or
Brush attributes, which dictate the object’s appearance. The ObjectInfo( ) function returns one
attribute of the specified object. Which attribute is returned depends on the value used in the
attribute parameter. Thus, if you need to find out several pieces of information about an object,
you will need to call ObjectInfo( ) a number of times, with different attribute values in each call.
The table below summarizes the various attribute settings, and the corresponding return values.
Example
Include ”MAPBASIC.DEF”
Dim counter, obj_type As Integer
Open Table ”city”
Fetch First From city
’ at this point, the expression: city.obj
’ represents the graphical object that’s attached
’ to the first record of the CITY table.
obj_type = ObjectInfo(city.obj, OBJ_INFO_TYPE)
Do Case obj_type
Case OBJ_TYPE_LINE
Note ”First object is a line.”
Case OBJ_TYPE_PLINE
Note ”First object is a polyline...”
counter = ObjectInfo(city.obj, OBJ_INFO_NPNTS)
Note ” ... with ” + Str$(counter) + ” nodes.”
Case OBJ_TYPE_REGION
Note ”First object is a region...”
counter = ObjectInfo(city.obj, OBJ_INFO_NPOLYGONS)
Note ”, made up of ” + Str$(counter) + ” polygons...”
counter = ObjectInfo(city.obj, OBJ_INFO_NPOLYGONS+1)
Note ”The 1st polygon has” + Str$(counter) + ” nodes”
End Case
See Also
Alter Object, ObjectGeography( ), Pen, Brush, Symbol, Font
ObjectLen( ) function
Purpose
Returns the geographic length of a line or polyline object.
Syntax
ObjectLen( expr , unit_name )
expr is an object expression
unit_name is a string representing the name of a distance unit (e.g., “mi” for miles)
Return Value
Float
Description
The ObjectLen( ) function returns the length of an object expression. Note that only line and
polyline objects have length values greater than zero; to measure the circumference of a
rectangle, ellipse, or region, use the Perimeter( ) function.
The ObjectLen( ) function returns a length measurement in the units specified by the unit_name
parameter; for example, to obtain a length in miles, specify “mi” as the unit_name parameter.
See the Set Distance Units statement for the list of valid unit names.
For the most part, MapInfo Professional performs a Cartesian or Spherical operation. Generally,
a spherical operation is performed unless the coordinate system is nonEarth, in which case, a
Cartesian operation is performed.
Example
Dim geogr_length As Float
Open Table ”streets”
Fetch First From streets
geogr_length = ObjectLen(streets.obj, ”mi”)
’ geogr_length now represents the length of the
’ street segment, in miles
See Also
Distance( ), Perimeter( ), Set Distance Units
ObjectNodeX( ) function
Purpose
Returns the x-coordinate of a specific node in a region or polyline object.
Syntax
ObjectNodeX( object , polygon_num , node_num )
object is an Object expression
polygon_num is a positive Integer value indicating which polygon or section to query s a
positive integer. It is ignored for Multipoint objects (it used for regions and polylines).
node_num is a positive Integer value indicating which node to read
Return Value
Float
Description
The ObjectNodeX( ) function returns the x-value of a specific node from a region or polyline
object. The corresponding ObjectNodeY( ) function returns the y-coordinate value.
The polygon_num parameter must have a value of one or more. This specifies which polygon (if
querying a region) or which section (if querying a polyline) should be queried. Call the
ObjectInfo( ) function to determine the number of polygons or sections in an object. The
ObjectNodeX() function now supports Multipoint objects and returns the x-coordinate of a
specific node in a Multipoint object.
The node_num parameter must have a value of one or more; this tells MapBasic which of the
object’s nodes should be queried. You can use the ObjectInfo( ) function to determine the
number of nodes in an object.
The ObjectNodeX( ) function will return the value in the coordinate system currently in use by
MapBasic; by default, MapBasic uses a longitude, latitude coordinate system. See the Set
CoordSys statement for more information about coordinate systems.
Example
The following example queries the first graphic object in the table Routes. If the first object is a
polyline, the program queries the x- and y-coordinates of the first node in the polyline, then
creates a new Point object at the location of the polyline’s starting node.
Dim i_obj_type As SmallInt,
x, y As Float,
new_pnt As Object
Open Table ”routes”
Fetch First From routes
’ at this point, the expression:
’ routes.obj
’ represents the graphical object that’s attached
’ to the first record of the routes table.
i_obj_type = ObjectInfo(routes.obj, OBJ_INFO_TYPE)
If i_obj_type = OBJ_PLINE Then
’ ... then the object is a polyline...
x = ObjectNodeX(routes.obj, 1, 1) ’ read longitude
y = ObjectNodeY(routes.obj, 1, 1) ’ read latitude
Create Point Into Variable new_pnt (x, y)
Insert Into routes (obj) Values (new_pnt)
End If
See Also
Alter Object, ObjectGeography( ), ObjectInfo( ), ObjectNodeY( ), Set CoordSys
ObjectNodeY( ) function
Purpose
Returns the y-coordinate of a specific node in a region or polyline object.
Syntax
ObjectNodeY( object , polygon_num , node_num )
object is an Object expression
polygon_num is a positive Integer value indicating which polygon or section to query. It is
ignored for Multipoint objects (it used for regions and polylines).
node_num is a positive Integer value indicating which node to read
Return Value
Float
Description
The ObjectNodeY( ) function returns the y-value of a specific node from a region or polyline
object. See the description of the ObjectNodeX( ) function for more information.
Example
See the ObjectNodeX( ) function description.
See Also
Alter Object, ObjectGeography( ), ObjectInfo( ), ObjectNodeX( ), Set CoordSys
To help weed out the legitimate gap areas, such as the Great Lakes, from problem gap areas, a
Gap Area is used. Any potential gap that is larger than this gap area is discarded and not
reported. The units that the Gap Area is in is presented by the Units clause. If the Units sub-
clause is not present, then the Gap Area value will be interpreted in MapBasic's current area
unit.
Gaps will be presented using the Pen and Brush clauses that follow the Gap keyword. By
default, these regions are drawn with blue interiors and a thin black boundary.
Example
This example will run Objects Check on the table called TestFile and store the results in the
table called DumpFile. It will also perform the overlap parameter and change the default Point
and Polygon styles.
objects check from TestFile into table Dumpfile Overlap
Selfint Symbol (67, 16711680, 28)
Overlap Pen (1,2,0) Brush (2, 16776960,0)
Gap 100000 Units "sq mi" Pen (1,2,0) Brush (2,255,0)
See Also
Objects Enclose
Data clause
The Data clause controls data aggregation. (For an introduction to data aggregation, see the
description of the Objects > Combine operation in the MapInfo Professional Reference.) The Data
clause includes a comma-separated list of assignments. You can assign any expression to a
column, assuming the expression is of the correct data type (numeric, string, etc.). The
following table lists the more common types of column assignments:
Expression Description
col_name = col_name The column contents are not altered.
col_name = value MapBasic stores the hard-coded value in the
column of the result object.
col_name = Sum( col_name ) Used only for numeric columns. The column in
the result object contains the sum of the column
values of all objects being combined.
col_name = Avg( col_name ) Used only for numeric columns. The column in
the result object contains the average of column
values of all objects in the group.
col_name=WtAvg(colname, wtcolname) Used only for numeric columns. MI Pro
performs weighted averaging, averaging all of
the colname column values, and weighting the
average calculation based on the contents of the
wtcolname column.
The Data clause can contain an assignment for every column in the table. If the Data clause
only includes assignments for some of the columns, MapBasic assigns blank values to those
columns that are not listed in the Data clause. If you omit the Data clause entirely, but you
include the Into Target clause, then MI Pro retains the target object’s original column values.
If you omit both the Data clause and the Into Target clause, then the object produced by the
combine operation is stored in a new row, and MI Pro assigns blank values to all of the columns
of the new row.
See Also
Combine( ), Set Target
The optional Data clause controls what values are stored in the columns of the target objects.
The Data clause can contain a comma-separated list of column assignments. Each column
assignment can take one of the forms listed in the following table:
Assignment Effect
col_name = col_name Does not alter the value stored in the column.
col_name = value Stores a specific value in the column. If the
column is a character
column, the value can be a string; if the column is a
numeric column, the value can be a number.
col_name = Proportion( col_name ) Used only for numeric columns; reduces the
number stored in the column in proportion to
how much of the object's area was erased.
The Data clause can contain an assignment for every column in the table. If the Data clause
only specifies assignments for some of the columns, blank values are assigned to those columns
that are not listed in the Data clause.
If you omit the Data clause entirely, all columns are blanked out of the target objects, storing
zero values in numeric columns and blank values in character columns.
Example
Open Table "STATES.TAB" Interactive
Map From STATES
Set Map Layer 1 Editable On
select * from STATES
Objects Disaggregate Into Table STATES
See Also
Objects Create
Assignment Effect
col_name = col_name MapBasic does not alter the value stored in the
column.
col_name = value MapBasic stores a specific value in the column. If
the column is a character column, the value can
be a string; if the column is a numeric column,
the value can be a number.
col_name = Proportion( col_name ) Used only for numeric columns; MapBasic
reduces the number stored in the column in
proportion to how much of the object’s area was
erased. Thus, if the operation erases half of the
area of an object, the object’s column value is
reduced by half.
The Data clause can contain an assignment for every column in the table. If the Data clause
only specifies assignments for some of the columns, MapBasic assigns blank values to those
columns that are not listed in the Data clause.
If you omit the Data clause entirely, MapBasic blanks out all columns of the target ob
Objects, storing zero values in numeric columns and blank values in character columns.
Examples
In the following example, the Objects Erase statement does not include a Data clause. As a
result, MapBasic stores blank values in the columns of the target object(s). This example
assumes that one or more target objects have been designated, and one or more objects have
been selected.
Objects Erase Into Target
In the next example, the Objects Erase statement includes a Data clause, which specifies
expressions for three columns (State_Name, Pop_1990, and Med_Inc_80). This operation
assigns the string “area remaining” to the State_Name column and specifies that the Pop_1990
column should be reduced in proportion to the amount of the object that is erased. The
Med_Inc_80 column retains the value it had before the Objects Erase statement. The target
objects’ other columns are blanked out.
Objects Erase Into Target
Data
State_Name = ”area remaining”,
Pop_1990 = Proportion( Pop_1990 ),
Med_Inc_80 = Med_Inc_80
See Also
Erase( ), Objects Intersect
Assignment Effect
col_name = col_name MapBasic does not alter the value stored in the
column.
col_name = value MapBasic stores a specific value in the column. If
the column is a character column, the value can
be a string; if the column is a numeric column,
the value can be a number.
col_name = Proportion( col_name ) Used only for numeric columns; MapBasic
reduces the number stored in the column in
proportion to how much of the object’s area was
erased. Thus, if the operation erases half of the
area of an object, the object’s column value is
reduced by half.
The Data clause can contain an assignment for every column in the table. If the Data clause
only specifies assignments for some of the columns, MapBasic assigns blank values to those
columns that are not listed in the Data clause.
If you omit the Data clause entirely, MapBasic blanks out all columns of the target objects,
storing zero values in numeric columns and blank values in character columns.
The Objects Intersect statement is very similar to the Objects Erase statement, with one
important difference: Objects Intersect erases the parts of the target objects(s) that do not
overlap the current selection, while Objects Erase erases the parts of the target objec
For each Target object, a new object is created for each area that intersects a cutter object. For
example, if a target object is intersected by three cutter objects, then three new objects will be
created. The parts of the target that lie outside all cutter objects will be discarded.
For more information, see the description of the Objects Erase statement.
Example
Objects Intersect Into Target
Data
Field2=Proportion(Field2)
See Also
Create Object, Overlap( )
The Bend tolerance is used to control how co-linear a series of nodes can be. Given 3 nodes,
connect the all of the nodes in a triangle. Measure the perpendicular distance from the second
node to the line connecting the first and third nodes. If this distance is less than the Bend
tolerance, then the three nodes are considered co-linear, and the second node is removed from
the object.
The Distance tolerance is used to eliminate nodes within the same object that are close to each
other. Measure the distance between two successive nodes in an object. If the distance between
them is less than the Distance tolerance, then one of the nodes can be removed.
The Cull Area value is used to eliminate polygons from regions that are smaller than the
threshold area. The Units sub-clause of Cull lets you specify an area measurement name (such
as "sq km" for square kilometers) to apply to the Area value. If the Units sub-clause is not
present, then the Area value will be interpreted in MapBasic's current area unit. By default,
MapBasic uses square miles as the area unit; to change this unit, see the Set Area Units
statement.
Note: For all of the distance and area values mentioned above, the Type of measurement used
is always Cartesian. Please keep in mind the coordinate system that your data is in. An
length and area calculations in Longitude/Latitude calculated using the Cartesian
method is not mathematically precise. Ensure that you are working in a suitable
coordinate system (a Cartesian system) before applying the tolerance values.
Example
Open Table "STATES.TAB" Interactive
Map From STATES
Set Map Layer 1 Editable On
select * from STATES
Objects Snap From Selection Tolerance Node 3 Vector 3 Units "mi" Thin
Bend 0.5 Distance 1 Units "mi" Cull Area 10 Units "sq mi"
See Also
Create Object, Overlap
Assignment Effect
col_name = col_name MapBasic does not alter the value stored in the
column; each object resulting from the split operation
retains the original column value.
col_name = value MapBasic stores a specific value in the column. If the
column is a character column, the value can be a
string; if the column is a numeric column, the value
can be a number. Each object resulting from the split
operation retains the specified value.
col_name = Proportion( col_name ) Used only for numeric columns; MI Pro divides the
original target object’s column value among the
graphical objects resulting from the split. Each object
receives “part of” the original column value, with
larger objects receiving larger portions of the numeric
values.
The Data clause can contain an assignment for every column in the table. If the Data clause
only specifies assignments for some of the columns, MapBasic assigns blank values to those
columns that are not listed in the Data clause.
If you omit the Data clause entirely, MapBasic blanks out all columns of the target objects,
storing zero values in numeric columns and blank values in character columns.
Examples
In the following example, the Objects Split statement does not include a Data clause. As a
result, MapBasic stores blank values in the columns of the target object(s).
Objects Split Into Target
In the next example, the statement includes a Data clause, which specifies expressions for three
columns (State_Name, Pop_1990, and Med_Inc_80). This first part of the Data clause assigns
the string “sub-division” to the State_Name column; as a result, “sub-division” will be stored in
the State_Name column of each object produced by the split. The next part of the Data clause
specifies that the target object’s original Pop_1990 value should be divided among the objects
produced by the split. The third part of the Data clause specifies that each of the new objects
should retain the original value from the Med_Inc_80 column.
Objects Split Into Target
Data
State_Name = ”sub-division”,
Pop_1990 = Proportion( Pop_1990 ),
Med_Inc_80 = Med_Inc_80
See Also
Alter Object
OnError statement
Purpose
Enables an error-handling routine.
Syntax
OnError Goto { label | 0 }
label is a label within the same procedure or function
Restrictions
You cannot issue an OnError statement through the MapBasic window.
Description
The OnError statement either enables an error-handling routine, or disables a previously
enabled error-handler. (An error-handler is a group of statements executed in the event of an
error).
BASIC programmers should note that in the MapBasic syntax, OnError is a single word.
An OnError Goto label statement enables an error-handling routine. Following such an
OnError statement, if the application generates an error, MapBasic will jump to the label line
specified. The statements following the label presumably correct the error condition, warn the
user about the error condition, or both. Within the error-handling routine, use a Resume
statement to resume program execution.
Once you have inserted error-handling statements in your program, you may need to place a
flow-control statement (e.g., Exit Sub or End Program) immediately before the error handler’s
label. This prevents the program from unintentionally “falling through” to the error handling
statements, but it does not prevent MapBasic from calling the error handler in the event of an
error. See example below.
An OnError Goto 0 statement disables the current error-handling routine. If an error occurs
while there is no error-handling routine, MapBasic will display an error dialog, then halt the
application.
Each error handler is local to a particular function or procedure. Thus, a sub procedure can
define an error handler by issuing a statement such as this:
OnError Goto recover
(assuming that the same procedure contains a label called “recover” ). If, after executing the
above OnError statement, the procedure issues a Call statement to call another sub procedure,
the “recover” error handler is suspended until the program returns from the Call. This is
because each label (e.g., “recover”) is local to a specific procedure or function. With this
arrangement, each function and each sub procedure can have its own error handling.
Note: If an error occurs within an error-handling routine, your MapBasic program halts.
Example
OnError GoTo no_states
Open Table ”states”
no_states:
Note ”Could not open table States... no Map used.”
Resume after_mapfrom
no_cities:
Note ”City data not available...”
Map From states
Resume after_mapfrom
See Also
Err( ), Error, Error$( ), Resume
Examples
Open File ”cxdata.txt” For INPUT As #1
Open File ”cydata.txt” For RANDOM As #2 Len=42
Open File ”czdata.bin” For BINARY As #3
See Also
Close File, EOF( ), Get, Input #, Print #, Put, Open Table, Write #
Overlap( ) function
Purpose
Returns an object representing the geographic intersection of two objects; produces results
similar to MapInfo’s Objects > Erase Outside command.
Syntax
Overlap( object1 , object2 )
object1 is an object; cannot be a point or text object
object2 is an object; cannot be a point or text object
Return Value
An object that is the geographic intersection of object1 and object2.
Description
The Overlap( ) function calculates the geographic intersection of two objects (the area covered
by both objects), and returns an object representing that intersection.
MapBasic retains all styles (color, etc.) of the original object1 parameter; then, if necessary,
MapBasic applies the current drawing styles.
If one of the objects is linear (e.g., a polyline) and the other object is closed (e.g., a region),
Overlap( ) returns the portion of the linear object that is covered by the closed object.
See Also
AreaOverlap( ), Erase( ), Objects Intersect
OverlayNodes( ) function
Purpose
Returns an object based on an existing object, with new nodes added at points where the object
intersects a second object.
Syntax
OverlayNodes ( input_object, overlay_object )
input_object is the object whose nodes will be included in the output object; may not be a point
or text object
overlay_object is the object that will be intersected with input_object; may not be a point or text
object
Return Value
A region object or a polyline object
Description
The OverlayNodes( ) function returns an object that contains all the nodes in input_object plus
nodes at all locations where input_object intersects with overlay_object.
If the input_object was a closed object (region, rectangle, rounded rectangle or ellipse),
OverlayNodes( ) returns a region object. If input_object was a linear object (line, polyline or arc),
OverlayNodes( ) returns a polyline.
The object returned retains all styles (color, etc.) of the original input_object.
To determine whether the OverlayNodes( ) function added any nodes to the input_object, use
the ObjectInfo( ) function to count the number of nodes (OBJ_INFO_NPNTS). Even if two
objects do intersect, the OverlayNodes( ) function will not add any nodes if input_object already
has nodes at the points of intersection.
See Also
Objects Overlay
PathToDirectory$( ) function
Purpose
Given a file specification, return only the file’s directory.
Syntax
PathToDirectory$( filespec )
filespec is a String expression representing a full file specification
Return Value
String
Description
The PathToDirectory$( ) function returns just the “directory” component from a full file
specification.
A full file specification can include a directory and a filename. A DOS directory can begin with
a hard drive letter (e.g., “C:” is a common hard drive specifier). Similarly, on the Macintosh, a
directory can begin with a device name (e.g., “Applications” might be the name of the hard
drive).
The following DOS file specification:
”C:\MAPINFO\DATA\WORLD.TAB”
includes the directory “C:\MAPINFO\DATA\”.
The following Macintosh file specification:
”HD:MAPINFO:DATA:WORLD”
includes the directory “HD:MAPINFO:DATA:”.
Example
Dim s_filespec, s_filedir As String
s_filespec = ”C:\MAPINFO\DATA\STATES.TAB”
s_filedir = PathToDirectory$(s_filespec)
PathToFileName$( ) function
Purpose
Given a file specification, return just the filename (without the directory).
Syntax
PathToFileName$( filespec )
filespec is a String expression representing a full file specification
Return Value
String
Description
The PathToFileName$( ) function returns just the “filename” component from a full file
specification.
A full file specification can include a directory and a filename. Under DOS, the filename can be
eight letters, followed by a file extension of up to three letters. The PathToFileName$( )
function returns the file’s name, including the file extension if there is one.
The following DOS file specification:
”C:\MAPINFO\DATA\WORLD.TAB”
includes a directory (“C:\MAPINFO\DATA\”) and a filename (“WORLD.TAB”).
The following Macintosh file specification:
”HD:MapInfo:Data:World”
includes a directory (“HD:MapInfo:Data:”) and a filename (“World”).
Example
Dim s_filespec, s_filename As String
s_filespec = ”C:\MAPINFO\DATA\STATES.TAB”
s_filename = PathToFileName$(s_filespec)
PathToTableName$( ) function
Purpose
Given a complete file specification (such as “C:\MapInfo\Data\1995 Data.tab”), returns a
string representing a table alias (such as “_1995_Data”).
Syntax
PathToTableName$( filespec )
filespec is a String expression representing a full file specification
Return Value
String, up to 31 characters long.
Description
Given a full file name that identifies a table’s .TAB file, this function returns a string that
represents the table’s alias. The alias is the name by which a table appears in the MapInfo
Professional user interface (e.g., on the title bar of a Browser window).
To convert a file name to a table alias, MI Pro removes the directory path from the beginning of
the string and removes “.TAB” from the end of the string. Any special characters (e.g., spaces or
punctuation marks) are replaced with the underscore character (_). If the table name starts with
a number, MI Pro inserts an underscore at the beginning of the alias. If the resulting string is
longer than 31 characters, MI Pro trims characters from the end; aliases cannot be longer than
31 characters.
Note that a table may sometimes be open under an alias that differs from its default alias. For
example, the following Open Table statement uses the optional As clause to force the World
table to use the alias “Earth”:
Open Table ”C:\MapInfo\Data\World.tab” As Earth
Furthermore, if the user opens two tables that have identical names but different directory
locations, MI Pro assigns the second table a different alias, so that both tables can be open at
once. In either of these situations, the “default alias” returned by PathToTableName$( ) might
not match the alias under which the table is currently open. To determine the alias under which
a table was actually opened, call TableInfo( ) with the TAB_INFO_NAME code.
Example
Dim s_filespec, s_tablename As String
s_filespec = ”C:\MAPINFO\DATA\STATES.TAB”
s_tablename = PathToTableName$(s_filespec)
’ s_tablename now contains the string ”STATES”
See Also
PathToDirectory$( ), PathToFileName$( ), TableInfo( )
Pen clause
Purpose
Specifies a line style for graphic objects.
Syntax
Pen pen_expr
pen_expr is a Pen expression, e.g., MakePen( width , pattern , color )
Description
The Pen clause specifies a line style - in other words, a set of thickness, pattern, and color
settings that dictate the appearance of a line or polyline object.
The Pen clause is not a complete MapBasic statement. Various object-related statements, such
as Create Line, let you include a Pen clause to specify an object’s line style. The keyword Pen
may be followed by an expression which evaluates to a Pen value. This expression can be a Pen
variable:
Pen pen_var
or a call to a function (e.g., CurrentPen( ) or MakePen( ) ) which returns a Pen value:
Pen MakePen(1, 2, BLUE)
With some MapBasic statements (e.g., Set Map), the keyword Pen can be followed immediately
by the three parameters that define a Pen style ( width, pattern, and color) within parentheses:
Pen(1, 2, BLUE)
Some MapBasic statements take a Pen expression as a parameter (e.g., the name of a Pen
variable), rather than a full Pen clause (the keyword Pen followed by the name of a Pen
variable). The Alter Object statement is one example.
The following table summarizes the components that define a Pen:
Component Description
width Integer value, usually from 1 to 7, representing the thickness of
the line (in pixels). To create an invisible line style, specify a
width of zero, and use a pattern value of 1 (one).
pattern Integer value from 1 to 118; see table below. Pattern 1 is invisible.
color Integer RGB color value; see the RGB( ) function.
Example
Include ”MAPBASIC.DEF”
Dim cable As Object
Create Line
Into Variable cable
(73.5, 42.6) (73.67, 42.9)
Pen MakePen(1, 2, BLACK)
See Also
Alter Object, Create Line, Create Pline, CurrentPen( ), MakePen( ), RGB( ), Set Style
PenWidthToPoints() function
Purpose
The PenWidthToPoints function returns a point size for a given pen width.
Syntax
PenWidthToPoints ( penwidth )
penwidth is an integer greater than 10 representing the pen width.
Return Value
Float
Description
The PenWidthToPoints function takes a pen width and returns the point size for that pen. The
pen width for a line style may be returned by the StyleAttr function. The pen width returned
by the StyleAttr function may be in points or pixels. Pen widths of less than ten are in pixels.
Any pen width of ten or greater is in points. PenWidthToPoints will only return values for pen
widths that are in points. To determine if pen widths are in pixels or points, use the
IsPenWidthPixels function.
Example
Include “MAPBASIC.DEF”
Dim CurPen As Pen
Dim Width As Integer
Dim PointSize As Float
CurPen = CurrentPen()
Width = StyleAttr(CurPen, PEN_WIDTH)
If Not IsPenWidthPixels(Width) Then
PointSize = PenWidthToPoints(Width)
End If
See Also
CurrentPen(), IsPenWidthPixels(), MakePen(),Pen, PointsToPenWidth(), StyleAttr()
PointsToPenWidth() function
Purpose
The PointsToPenWidth function returns a pen width for a given point size.
Syntax
PointsToPenWidth ( pointsize )
pointsize is a float value in tenths of a point.
Return Value
SmallInt
Description
The PointsToPenWidth function takes a value in tenths of a point and converts that into a pen
width.
Example
Include “MAPBASIC.DEF”
Dim Width As Integer
Dim p_bus_route As Pen
Width = PointsToPenWidth(1.7)
p_bus_route = MakePen(Width, 9, RED)
See Also
CurrentPen(), IsPenWidthPixels(), MakePen(),Pen, PenWidthToPoints(), StyleAttr()
Perimeter( ) function
Purpose
Returns the perimeter of a graphical object.
Syntax
Perimeter ( obj_expr, unit_name )
obj_expr is an object expression
unit_name is a string representing the name of a distance unit (e.g., “km”)
Return Value
Float
Description
The Perimeter( ) function calculates the perimeter of the obj_expr object. The Perimeter()
function is defined for the following object types: ellipses, rectangles, rounded rectangles, and
polygons. Other types of objects have perimeter measurements of zero.
The Perimeter( ) function returns a length measurement in the units specified by the unit_name
parameter; for example, to obtain a length in miles, specify “mi” as the unit_name parameter.
See the Set Distance Units statement for the list of valid unit names.
The Perimeter( ) function returns approximate results when used on rounded rectangles.
MapBasic calculates the perimeter of a rounded rectangle as if the object were a conventional
rectangle.
For the most part, MapInfo Professional performs a Cartesian or Spherical operation. Generally,
a spherical operation is performed unless the coordinate system is nonEarth, in which case, a
Cartesian operation is performed.
Example
The following example shows how you can use the Perimeter( ) function to determine the
perimeter of a particular geographic object.
Dim perim As Float
Open Table ”world”
Fetch First From world
perim = Perimeter(world.obj, ”km”)
’ The variable perim now contains
’ the perimeter of the polygon that’s attached to
’ the first record in the World table.
You can also use the Perimeter( ) function within the SQL Select statement. The following
Select statement extracts information from the States table, and stores the results in a
temporary table called Results. Because the Select statement includes the Perimeter( ) function,
the Results table will include a column showing each state’s perimeter.
Open Table ”states”
Select state, Perimeter(obj, ”mi”)
From states
Into results
See Also
Area( ), ObjectLen( ), Set Distance Units
Print statement
Purpose
Prints a prompt or a status message in the Message window.
Syntax
Print message
message is a String expression
Description
The Print statement prints a message to the Message window.
The Message window is a special window which does not appear in MapInfo’s standard user
interface. The Message window lets you display custom messages that relate to a MapBasic
program. You could use the Message window to display status messages (“Record deleted”) or
prompts for the user (“Select the territory to analyze.”). To set the font for the Message window,
use the Set Window statement. A MapBasic program can explicitly open the Message window
through the Open Window statement.
If a Print statement occurs while the Message window is closed, MapBasic opens the Message
window automatically.
The Print statement is similar to the Note statement, in that you can use either statement to
display status messages or debugging messages. However, the Note statement displays a
dialog box, pausing program execution until the user clicks OK.
The Print statement simply prints text to a window, without pausing the program. Each Print
statement is printed to a new line in the Message window. After you have printed enough
messages to fill the Message window, scroll buttons appear at the right edge of the window, to
allow the user to scroll through the messages.
To clear the Message window, print a string which includes the form-feed character (code 12):
Print Chr$(12) ’This statement clears the Message window
By embedding the line-feed character (code 10) in a message, you can force a single message to
be split onto two or more lines. The following Print statement produces a two-line message:
Print ”Map Layers:” + Chr$(10) + ” World, Capitals”
The Print statement converts each Tab character (code 09) to a space (code 32).
Example
The following example displays the Message window, sets the window’s size (three inches
wide by one inch high), sets the window’s font (Helvetica, bold, 10-point), and prints a message
to the window.
Include ”MAPBASIC.DEF” ’ needed for color name ’BLUE’
Open Window Message ’ open Message window
Set Window Message
Font (”Helv”, 1, 10, BLUE) ’ Helvetica bold...
Position (0.25, 0.25) ’ place in upper left
Width 3.0 ’ make window 3” wide
Height 1.0 ’ make window 1” high
Print ”MapBasic Dispatcher now on line”
Note: The buffer size for message window text has been doubled to 8191 characters.
See Also
Ask( ), Close Window, Note, Open Window, Set Window
Print # statement
Purpose
Writes data to a file opened in a Sequential mode (Output or Append).
Syntax
Print # file_num [ , expr ]
file_num is the number of a file opened through the Open File statement
expr is an expression to write to the file
Description
The Print # statement writes data to an open file. The file must be open, in a sequential mode
which allows output (Output or Append).
The file_num parameter corresponds to the number specified in the As clause of the Open File
statement.
MapInfo Professional writes the expression expr to a line of the file. To store a comma-separated
list of expressions in each line of the file, use Write # instead of Print #.
See Also
Line Input #, Open File, Write #
PrintWin statement
Purpose
Prints an existing window.
Syntax
PrintWin [ Window window_id ] [ Interactive ]
window_id is a window identifier
Description
The PrintWin statement prints a window.
If the statement includes the optional Window clause, MapBasic prints the specified window;
otherwise, MapBasic prints the active window.
The window_id parameter represents a window identifier; see the FrontWindow( ) and
WindowInfo( ) functions for more information about obtaining window identifiers.
If you include the Interactive keyword, MapInfo Professional displays the Print dialog. If you
omit the Interactive keyword, MI Pro prints the window automatically, without displaying the
dialog.
Example
Dim win_id As Integer
Open Table ”world”
Map From world
win_id = FrontWindow()
’
’ knowing the ID of the Map window,
’ the program could now print the map by
’ issuing the statement:
’
PrintWin Window win_id Interactive
See Also
FrontWindow( ), Run Menu Command, WindowInfo( )
PrismMapInfo( ) function
Purpose
Returns properties of a Prism Map window.
Syntax
PrismMapInfo( window_id , attribute )
window_id is an Integer window identifier
attribute is an Integer code, indicating which type of information should be returned
Returns
Float, Logical, or String, depending on the attribute parameter.
Description
The PrismMapInfo() function returns information about a Prism Map window.
The window_id parameter specifies which Prism Map window to query. To obtain a window
identifier, call the FrontWindow() function immediately after opening a window, or call the
WindowID() function at any time after the window's creation.
There are several numeric attributes that PrismMapInfo() can return about any given Prism
Map window. The attribute parameter tells the PrismMapInfo() function which Map window
statistic to return. The attribute parameter should be one of the codes from the following table;
codes are defined in MAPBASIC.DEF.
ProgramDirectory$( ) function
Purpose
Returns the directory path to where the MapInfo Professional software is installed.
Syntax
ProgramDirectory$( )
Return Value
String
Description
The ProgramDirectory$( ) function returns a string representing the directory path where the
MI Pro software is installed.
Example
Dim s_prog_dir As String
s_prog_dir = ProgramDirectory$()
See Also
HomeDirectory$( ), SystemInfo( )
ProgressBar statement
Purpose
Displays a dialog with a Cancel button and a horizontal progress bar.
Syntax
ProgressBar status_message
Calling handler
[ Range n ]
status_message is a String value displayed as a message in the dialog
handler is the name of a Sub procedure
n is a number at which the job is finished
Restrictions
You cannot issue the ProgressBar statement through the MapBasic window.
Description
The ProgressBar statement displays a dialog with a horizontal progress bar and a Cancel
button. The bar indicates the percentage of completion of a lengthy operation. The user can halt
the operation by clicking the Cancel button. Following the ProgressBar statement, a MapBasic
program can call CommandInfo(CMD_INFO_DLG_OK) to determine whether the operation
finished or whether the user cancelled first (see below).
The status_message parameter is a String value, such as “Processing data...”, which is displayed
in the dialog.
The handler parameter is the name of a sub procedure in the same MapBasic program. As
described below, the sub procedure must perform certain actions in order for it to interact with
the ProgressBar statement.
The n parameter is a number, representing the count value at which the operation will be
finished. For example, if an operation needs to process 7,000 rows of a table, the ProgressBar
statement might specify 7000 as the n parameter. If no Range n clause is specified, the n
parameter has a default value of 100.
When a program issues a ProgressBar statement, MapBasic calls the specified handler sub
procedure. The sub procedure should perform a small amount of processing - a few seconds’
worth of processing at most - and then it should end. At that time, MapBasic checks to see if the
user clicked the Cancel button. If the user did click Cancel, MapBasic removes the dialog, and
proceeds with the statements which follow the ProgressBar statement (and thus, the lengthy
operation is never completed). Alternately, if the user did not click Cancel, MapBasic
automatically calls the handler sub procedure again. If the user never clicks Cancel, the
ProgressBar statement repeatedly calls the procedure until the operation is finished.
The handler procedure must be written in such a way that each call to the procedure performs
only a small percent of the total job. Once a ProgressBar statement has been issued, MapBasic
will repeatedly call the handler procedure until the user clicks Cancel or until the handler
procedure indicates that the procedure is finished. The handler indicates the job status by
assigning a value to the special MapBasic variable, also named ProgressBar.
Sub Main
next_row = 1
ProgressBar ”Writing data...” Calling write_out Range 600
If CommandInfo(CMD_INFO_STATUS) Then
Note ”Operation complete! Thanks for waiting.”
Else
Note ”Operation interrupted!”
End If
End Sub
Sub write_out
Dim start_time As Float
start_time = Timer()
’ process records until either (a) the job is done,
’ or (b) more than 2 seconds elapse within this call
Proper$( ) function
Purpose
Returns a mixed-case string, where only the first letter of each word is capitalized.
Syntax
Proper$( string_expr )
string_expr is a string expression
Return Value
String
Description
The Proper$( ) function first converts the entire string_expr string to lower case, and then
capitalizes only the first letter of each word in the string, thus producing a result string with
“proper” capitalization. This style of capitalization is appropriate for proper names.
Example
Dim name, propername As String
name = ”a b c d”
propername = Proper$(name)
’ propername now contains the string ”A B C D”
See Also
LCase$( ), UCase$( )
ProportionOverlap( ) function
Purpose
Returns a number that indicates what percentage of one object is covered by another object.
Syntax
ProportionOverlap(object1,object2)
object1 is the bottom object (not text or points)
object2 is the top object (not text or points)
Return Value
A Float value equal to Area(Overlap(object1,object2) ) / Area(object1).
See Also
AreaOverlap( )
Put statement
Purpose
Writes the contents of a MapBasic variable to an open file.
Syntax
Put [#] filenum, [ position ] , var_name
filenum is the number of a file opened through an Open File statement
position is the file position to write to (does not apply to sequential file access)
var_name is the name of a variable which contains the data to be written
Description
The Put statement writes to an open file. Note: If the Open File statement specified a sequential
access mode (OUTPUT or APPEND), use Print # or Write # instead of Put.
If the Open File statement specified Random file access, the Put statement’s Position clause
can be used to indicate which record in the file to overwrite. When the file is opened, the file
position points to the first record of the file (record 1).
If the Open File statement specified Binary file access, one variable can be written at a time.
The byte sequence written to the file depends on whether the hardware platform’s byte
ordering; see the ByteOrder clause of the Open File statement. The number of bytes written
depends on the variable type, as summarized below:
Randomize statement
Purpose
Initializes MapBasic’s random number function.
Syntax
Randomize [ With seed ]
seed is an Integer expression
Description
The Randomize statement “seeds” the random number generator so that later calls to the Rnd(
) function produce random results. Without this statement before the first call to Rnd( ), the
actual series of random numbers will follow a standard list. In other words, unless the program
includes a Randomize statement, the sequence of values returned by Rnd( ) will follow the
same pattern each time the application is run.
The Randomize statement is only needed once in a program and should occur prior to the first
call to the Rnd( ) function.
If you include the With clause, the seed parameter is used as the seed value for the pseudo-
random number generator. If you omit the With clause, MapBasic automatically seeds the
pseudo-random number generator using the current system clock. Use the With clause if you
need to create repeatable test scenarios, where your program generates repeatable sequences of
“random” numbers.
Example
Randomize
See Also
Rnd( )
ReadControlValue( ) function
Purpose
Reads the current status of a control in the active dialog.
Syntax
ReadControlValue( id_num )
id_num is an integer value indicating which control to read
Return Value
Integer, Logical, String, Pen, Brush, Symbol, or Font, depending on the type of control
Description
The ReadControlValue( ) function returns the current value of one of the controls in an active
dialog. A ReadControlValue( ) function call is only valid while there is an active dialog; thus,
you may only call the ReadControlValue( ) function from within a dialog control’s handler
procedure.
The integer id_num parameter specifies which control MapBasic should read. If the id_num
parameter has a value of -1 (negative one), the ReadControlValue( ) function returns the value
of the last control which was operated by the user. To explicitly specify which control you want
to read, pass ReadControlValue( ) an Integer ID that identifies the appropriate control. Note: a
dialog control does not have a unique ID unless you include an ID clause in the Dialog
statement’s Control clause.
Some types of dialog controls have no readable values (e.g., static text labels). The chart below
summarizes what types of values will be returned by various controls. Note that special
processing is required for handling MultiListBox controls: since the user can select more than
one item from a MultiListBox control, a program may need to call ReadControlValue( )
multiple times to obtain a complete list of the selected items.
Sub okhandler
’ this sub is called when/if the user
’ clicks the OK control
Note ”Welcome aboard, ” + ReadControlValue(23) + ”!”
End Sub
See Also
Alter Control, Dialog, Dialog Preserve, Dialog Remove
ReDim statement
Purpose
Re-sizes an array variable.
Syntax
ReDim var_name ( newsize ) [ , ... ]
var_name is the name of an existing local or global array variable
newsize is an integer value dictating the new array size. Under 16-bit versions of Windows, the
maximum value is 7,000; under Macintosh or 32-bit Windows, the maximum value is 32,767.
Description
The ReDim statement re-sizes (or “re-dimensions”) one or more existing array variables. The
variable identified by var_name must have already been defined as an array variable through a
Dim or a Global statement.
The ReDim statement can increase or decrease the size of an existing array. If your program no
longer needs a given array variable, the ReDim statement can re-size that array to have zero
elements (this minimizes the amount of memory required to store variables).
Unlike some BASIC languages, MapBasic does not allow custom subscript settings for arrays; a
MapBasic array’s first element always has a subscript of one.
If you store values in an array, and then enlarge the array through the ReDim statement, the
values you stored in the array remain intact.
Example
Dim names_list(10) As String, cur_size As Integer
’ The following statements determine the current
’ size of the array, and then ReDim the array to
’ a size 10 elements larger
cur_size = UBound(names_list)
ReDim names_list(cur_size + 10)
ReDim names_list(0)
As shown below, the ReDim statement can operate on arrays of custom Type variables, and
also on arrays that are Type elements.
Type customer
name As String
serial_nums(0) As Integer
End Type
ReDim new_customers(5)
ReDim new_customers(1).serial_nums(10)
See Also
Dim, Global, UBound( )
ControlPoints are optional, but can be specified if the type is Grid or Raster. If the
ControlPoints token is specified, it must be followed by at least 3 pairs of Map and Raster
coordinates which are used to georegister an image. If the ControlPoints are specified, they will
override and replace any control points associated with the image or an associated World file.
The CoordSys clause is optional, but can be specified if the type is Grid or Raster. If a CoordSys
is specified, it will override and replace any coordsys associated with the image. This is useful
when registering a raster image that has an associated World file.
In the case of Shapefiles, the CoordSys clause is mandatory. The compiler will indicate an error
if it is missing.
PersistentCache On specifies if .MAP and .ID files generated during the opening of Shapefiles
are saved on hard disk after closing a table. If PersistentCache is set to Off, then these .MAP and
.ID files will be deleted after closing a table and will be generated each time the table is opened.
Symbol (...) clause specifies the symbol style to be used for a point object type created from a
shapefile
Linestyle Pen (...) clause specifies the line style to be used for a line object type created from a
shapefile
Regionstyle Pen (...) Brush(...) clause specifies the line style and fill style to be used for a region
object type created from a shapefile
The Interactive keyword is optional, but can be specified if the type is Grid or Raster. If the
Interactive keyword is specified, the user will be prompted for any missing control point or
projection information. If the Interactive keyword is not specified, a .TAB file will be generated
without user input and will be created as though the user had selected "Display" when
opening a raster image from the File>Open dialog.
destination_file specifies the name to give to the MapInfo table (.TAB file). This string may
include a path; if it does not include a path, the file is built in the same directory as the source
file.
Description
Before you can use a non-native file (e.g., a dBASE file) in MapInfo, you must register the file.
The Register Table statement tells MI Pro to examine a non-native file (e.g., filename.DBF) and
build a corresponding table file (filename.TAB). Once the Register Table operation has built a
table file, you can access the file as an MapInfo table.
The Register Table statement does not copy or alter the original data file. Instead, it scans the
data, determines the datatypes of the columns, and creates a separate table file. The table is not
opened automatically. To open the table, use an Open Table statement.
Note: Each data file need only be registered once. Once the Register Table operation has built
the appropriate table file, subsequent MI Pro sessions simply Open the table, rather than
repeat the Register Table operation.
The Type clause specifies where the file came from originally. This consists of the keyword
Type, followed by one of the following character constants: NATIVE, DBF, ASCII, WKS, XLS,
Raster, Access, or Grid. The other information is necessary for preparing certain types of tables.
If the type of file being registered is a grid, the coordsys string will be read from the grid file
and a MapInfo .TAB file will be created. If a raster file is being registered, the .TAB file that is
generated will be the same as if the user selected ”Display” when opening a raster image from
the File> Open dialog.
If the type of file being registered is a grid, the coordsys string will be read from the grid file
and a MapInfo .TAB file will be created. If a raster file is being registered, the .TAB file that is
generated depends upon if georegistration information can be found in the image file or
associated World file.
The CharSet clause specifies a character set. The char_set parameter should be a string such as
“MacRoman” or “WindowsLatin1”. If you omit the CharSet clause, MI Pro uses the default
character set for the hardware platform that is in use at run-time. See the CharSet clause
discussion for more information.
The Delimiter clause is followed by a string containing the delimiter character. The default
delimiter is a TAB. The Titles clause indicates that the row before the range of data in the
worksheet should be used as column titles. The Range clause allows the specification of a
named range to use. The Into clause is used to override the table name or location of the .TAB
file. By default, it will be named the same as the data file, and stored in the same directory.
However, when reading a read-only device such as a CD-ROM, you need to store the .TAB file
on a volume that is not read-only.
Registering Access Tables
When you register an Access table, MI Pro checks for a counter column with a unique index. If
there is already a counter column, MI Pro registers that column in the .TAB file. The column is
read-only.
If the Access table does not have a counter column, MI Pro modifies the Access table by adding
a column called MAPINFO_ID with the counter datatype. In this case, the counter column does
not display in MapInfo.
Note: Do not alter the counter column in any way. It must be exclusively maintained
automatically by MapInfo.
Access datatypes are translated into the closest MapInfo datatypes. Special Access datatypes,
such as OLE objects and binary fields, are not editable in MapInfo Professional.
Registering ODBC Tables
Before accessing a table live from a remote database, it is highly recommended that you first
open a map table (e.g., canada.tab) for the database table. If you don't open a map table, the
entire database table will be downloaded all at once, which could take a long time.
Open a map table and zoom in to an area that corresponds to a subset of rows you wish to see
from the database table. For example, if you want to download rows pertaining to Ontario,
zoom in to Ontario on the map. As a result, when you open the database table, only rows
within the map window's MBR (minimum bounding rectangle), in this case Ontario, will be
downloaded.
This is a list of known problems/issues with live access:
• Every table must have a single unique key column.
• FastEdit is not supported.
• With MS ACCESS if the key is character, it will not display rows where the key value is less
than the full column width e.g., if the key is char(5) the value 'aaaa' will look like a deleted
row.
• For Live Access, the ReadOnly checkbox on the save table dialogue will be grayed out.
• Changes made by another user are not visible until a browser is scrolled or somehow
refreshed. Inserts by another user are not seen until either : 1). An MBR search returns the
row or 2). PACK command is issued In addition if cache is on another users updates may
not appear until the cache is invalidated by a pan or zooming out.
• There will be a problem if a client side join (through SQL Select menu item or MapBasic) is
done against 2 or more SPATIALWARE tables that are stored in different coordinate
systems. This is not an efficient thing to do (it is better to do the join in the SQL statement
that defines the table) but it is a problem in the current build.
• Oracle 7 tables that are indexed on a decimal field larger than 8 bytes will cause MI Pro to
crash when editing.
• If the Cache OFF statement is before the connection string an error will be generated at
compile time.
Registering Shapefiles
When you register shapefiles, they can be opened in MapInfo Professional with read-only
access. Since a shapefile itself does not contain projection information, you must specify a
CoorSys clause. It is also possible to set styles that will be used when shapefile objects are
displayed in MapInfo Professional. Projection and style information is stored as metadata in
the TAB file.
Example1
Register Table ”c:\mapinfo\data\rpt23.dbf”
Type ”DBF”
Into ”Report23”
Example5
Registering a raster image that has no control point or projection information.
Register Table "NoRegistration.BMP" type "raster" controlpoints
(1000,2000) (1,2), (2000,3000) (2, 3), (5000,6000) (5,6) coordsys
earth projection 9, 62, "m", -96, 23, 29.5, 45.5, 0, 0 into
"NoRegistration.tab"
Example6
The following example registers a shapefile.
Register Table "C:\Shapefiles\CNTYLN.SHP" TYPE SHAPEFILE Charset
"WindowsLatin1" CoordSys Earth Projection 1, 33 PersistentCache Off
linestyle Pen (2,26,16711935) Into "C:\Temp\CNTYLN.TAB"
Open Table "C:\Temp\CNTYLN.TAB" Interactive
Map From CNTYLN
See Also
Open Table, Create Table
RemoteMapGenHandler procedure
Purpose
A reserved procedure name, called when an OLE Automation client calls the MapGenHandler
Automation method.
Syntax
Declare Sub RemoteMapGenHandler
Sub RemoteMapGenHandler
statement_list
End Sub
statement_list is a list of MapBasic statements to execute when the OLE Automation client calls
the MapGenHandler method.
Description
RemoteMapGenHandler is a special-purpose MapBasic procedure name, which is invoked
through OLE Automation. If you are using OLE Automation to control MapInfo, and you call
the MapGenHandler method, MapInfo Professional calls the RemoteMapGenHandler
procedures of any MapBasic applications that are running. The MapGenHandler method is
part of the MapGen Automation model introduced in MapInfo Professional 4.1.
The MapGenHandler Automation method takes one argument: a string. Within the
RemoteMapGenHandler procedure, you can retrieve the string argument by issuing the
following function call ...
CommandInfo(CMD_INFO_MSG)
... and assigning the results to a String variable.
Example
For an example of using RemoteMapGenHandler, see the sample program MAPSRVR.MB.
RemoteMsgHandler procedure
Purpose
A reserved procedure name, called when a remote application sends an execute message.
Syntax
Declare Sub RemoteMsgHandler
Sub RemoteMsgHandler
statement_list
End Sub
statement_list is a list of statements to execute upon receiving an execute message
Description
RemoteMsgHandler is a special-purpose MapBasic procedure name that handles inter-
application communication. If you run a MapBasic application that includes a procedure
named RemoteMsgHandler, MapInfo Professional automatically calls the
RemoteMsgHandler procedure every time another application (e.g., a spreadsheet or database
package) issues an “execute” command. The MapBasic procedure then can call CommandInfo(
) to retrieve the string corresponding to the execute command.
You can use the End Program statement to terminate a RemoteMsgHandler procedure once it is
no longer wanted. Conversely, you should be careful not to issue an End Program statement
while the RemoteMsgHandler procedure is still needed.
Inter-Application Communication Using Windows DDE
If a Windows application is capable of conducting a DDE (Dynamic Data Exchange)
conversation, that application can initiate a conversation with MapInfo. In the conversation, the
external application is the client (active party), and a specific MapBasic application is the server
(passive party).
Each time the DDE client sends an execute command, MI Pro calls the server’s
RemoteMsgHandler procedure. Within the RemoteMsgHandler procedure, you can use
function call:
CommandInfo(CMD_INFO_MSG)
to retrieve the string sent by the remote application.
The DDE conversation must use the name of the sleeping application (e.g.,
“C:\MAPBASIC\DISPATCH.MBX”) as the topic in order to facilitate RemoteMsgHandler
functionality.
See Also
DDEExecute, DDEInitiate( ), SelChangedHandler, ToolHandler, WinChangedHandler,
WinClosedHandler
RemoteQueryHandler( ) function
Purpose
A special function, called when a MapBasic program acts as a DDE server, and the DDE client
performs a “peek” request.
Syntax
Declare Function RemoteQueryHandler( ) As String
Function RemoteQueryHandler( ) As String
statement_list
End Function
statement_list is a list of statements to execute upon receiving a peek request
Description
The RemoteQueryHandler( ) function works in conjunction with DDE (Dynamic Data
Exchange). For an introduction to DDE, see the MapBasic User’s Guide.
An external application can initiate a DDE conversation with your MapBasic program. To
initiate the conversation, the external application uses “MapInfo” as the DDE application
name, and it uses the name of your MapBasic application as the DDE topic. Once the
conversation is initiated, the external application (the client) can issue peek requests to request
data from your MapBasic application (the server).
To handle peek requests, include a function called RemoteQueryHandler( ) in your MapBasic
application. When the client application issues a peek request, MI Pro automatically calls the
RemoteQueryHandler( ) function. The client’s peek request is handled synchronously; the
client waits until RemoteQueryHandler( ) returns a value.
Note: The DDE client can peek at the global variables in your MapBasic program, even if you
do not define a RemoteQueryHandler( ) function. If the client issues a peek request
using the name of a MapBasic global variable, MI Pro automatically returns the global’s
value to the client instead of calling RemoteQueryHandler( ). In other words, if the data
you want to expose is already stored in global variables, you do not need
RemoteQueryHandler( ).
Example
The following example calls CommandInfo( ) to determine the item name specified by the
DDE client. The item name is used as a flag; in other words, this program decides which value
to return based on whether the client specified “code1” as the item name.
Function RemoteQueryHandler() As String
Dim s_item_name As String
s_item_name = CommandInfo(CMD_INFO_MSG)
End Function
See Also
DDEInitiate( ), RemoteMsgHandler
Reproject statement
Purpose
Allows you to specify which columns should appear the next time a table is browsed.
Syntax
Reproject column [ , column . . . ] From table
column is the name of a column
table is the name of an open table
Description
The Reproject statement lets you specify the list of columns that should appear the next time a
table is browsed. If you issue a Reproject statement, and then issue a Browse statement, the
new Browser window will show only the columns listed in the Reproject statement.
Example
The following statements open the World table and display it in a Browser window. Because of
the Reproject statement, the Browser window displays only two columns.
Open Table ”world” Interactive As World
Reproject Country, Population From World
Browse * From World
See Also
Browse
Resume statement
Purpose
Returns from an OnError error handler.
Syntax
Resume { 0 | Next | label }
label is a label within the same procedure or function
Restrictions
You cannot issue a Resume statement through the MapBasic window.
Description
The Resume statement tells MapBasic to return from an error-handling routine.
The OnError statement enables an error-handling routine, which is a group of statements
MapBasic carries out in the event of a run-time error. Typically, each error-handling routine
includes one or more Resume statements. The Resume statement causes MapBasic to exit the
error-handling routine.
The various forms of the Resume statement let the application dictate which statement
MapBasic is to execute after exiting the error-handling routine:
A Resume 0 statement tells MapBasic to retry the statement which generated the error.
A Resume Next statement tells MapBasic to go to the first statement following the statement
which generated the error.
A Resume label statement tells MapBasic to go to the line identified by the label. Note that the
label must be in the same procedure.
Example
OnError GoTo no_states
Open Table ”states”
Map From states
after_mapfrom:
...
End Program
no_states:
Note ”Could not open States; no Map used.”
Resume after_mapfrom
See Also
Err( ), Error, Error$( ), OnError
RGB( ) function
Purpose
Returns an RGB color value calculated from Red, Green, Blue components.
Syntax
RGB ( red, green, blue )
red is a numeric expression from 0 to 255, representing a concentration of red
green is a numeric expression from 0 to 255, representing a concentration of green
blue is a numeric expression from 0 to 255, representing a concentration of blue
Return Value
Integer
Description
Some MapBasic statements allow you to specify a color as part of a pen or brush definition
(e.g., the Create Point statement). MapBasic pen and brush definitions require that each color
be specified as a single integer value, known as an RGB value. The RGB() function lets you
calculate such an RGB value.
Colors are often defined in terms of the relative concentrations of three components - the red,
green and blue components. Accordingly, the RGB( ) function takes three parameters - red,
green, and blue - each of which specifies the concentration of one of the three primary colors.
Each color component should be an integer value from 0 to 255, inclusive.
The RGB value of a given color is calculated by the formula:
Right$( ) function
Purpose
Returns part or all of a string, beginning at the right end of the string.
Syntax
Right$ ( string_expr, num_expr )
string_expr is a string expression
num_expr is a numeric expression
Return Value
String
Description
The Right$( ) function returns a string which consists of the rightmost num_expr characters of
the string expression string_expr.
The num_expr parameter should be an integer value, zero or larger. If num_expr has a fractional
value, MapBasic rounds to the nearest integer. If num_expr is zero, Right$( ) returns a null
string. If num_expr is larger than the number of characters in the string_expr string, Right$( )
returns a copy of the entire string_expr string.
Example
Dim whole, partial As String
whole = ”Afghanistan”
partial = Right$(whole, 4)
Rnd( ) function
Purpose
Returns a random number.
Syntax
Rnd ( list_type )
list_type selects the kind of random number list
Return Value
A number of type Float between 0 and 1 (exclusive)
Description
The Rnd( ) function returns a random floating-point number, greater than zero and less than
one.
The conventional use is of the form Rnd(1), in which the function returns a random number.
The sequence of random numbers is always the same unless you insert a Randomize statement
in the program. Any positive list_type parameter value produces this type of result.
A less common use is the form Rnd(0), which returns the previous random number generated
by the Rnd( ) function. This functionality is provided primarily for debugging purposes.
A very uncommon use is a call with a negative list_type value, such as Rnd(-1). For a given
negative value, the Rnd( ) function always returns the same number - regardless of whether
you have issued a Randomize statement. This functionality is provided primarily for
debugging purposes.
Example
Chknum = 10 * Rnd(1)
See Also
Randomize
Rollback statement
Purpose
Discards a table’s unsaved edits.
Syntax
Rollback Table tablename
tablename is the name of an open table
Description
If the specified table has been edited, but the edits have not been saved, the Rollback statement
discards the unsaved edits. The user can obtain the same results by choosing File > Revert,
except that the Revert command displays a dialog box.
Note: When you Rollback a query table, MapInfo Professional discards any unsaved edits in
the permanent table used for the query (except in cases where the query produces a join, or the
query produces aggregated results, e.g., using the Select statement’s Group By clause).
For example, if you edit a permanent table (such as WORLD), make a selection from WORLD,
and browse the selection, MI Pro will “snapshot” the Selection table, and call the snapshot
(something like) QUERY1. If you then Rollback the QUERY1 table, MI Pro discards any
unsaved edits in the WORLD table, since the WORLD table is the table on which QUERY1 is
based.
Using a Rollback statement on a linked table discards the unsaved edits and returns the table
to the state it was in prior to the unsaved edits.
Example
If keep_changes Then
Commit Table towns
Else
Rollback Table towns
End If
See Also
Commit
Rotate( ) function
Purpose
Allows an object (not a text object) to be rotated about the rotation anchor point.
Syntax
Rotate(object, angle)
object represents an object that can be rotated. It cannot be a text object.
angle is a float value that represents the angle (in degrees) to rotate the object.
Return Value
A rotated object.
Description
Rotates all object types except for text objects without altering the source object in any way.
To rotate text objects, use the Alter Object OBJ_GEO_TEXTANGLE statement.
If an arc, ellipse, rectangle, or rounded rectangle is rotated, the resultant object will be
converted to a polyline/polygon so that the nodes can be rotated.
Example
dim RotateObject as object
Open Table "C:\MapInfo_data\TUT_USA\USA\STATES.TAB"
map from states
select * from States where state = "IN"
RotateObject = rotate(selection.obj, 45)
insert into states (obj) values (RotateObject)
See Also
RotateAt Point
RotateAtPoint( ) function
Purpose
Allows an object (not a text object) to be rotated about a specified anchor point.
Syntax
RotateAtPoint(object, angle, anchor_point_object)
object represents an object that can be rotated. It cannot be a text object.
angle is a float value that represents the angle (in degrees) to rotate the object.
anchor_point_object is an object representing the anchor point which the object nodes are rotated
about.
Return Value
A rotated object.
Description
Rotates all object types except for text objects without altering the source object in any way.
To rotate text objects, use the Alter Object OBJ_GEO_TEXTANGLE statement.
If an arc, ellipse, rectangle, or rounded rectangle is rotated, the resultant object will be
converted to a polyline/polygon so that the nodes can be rotated.
Example
dim RotateAtPointObject as object
dim obj1 as object
dim obj2 as object
Open Table "C:\MapInfo_data\TUT_USA\USA\STATES.TAB" ]
map from states
select * from States where state = "CA"
obj1 = selection.obj
select * from States where state = "NV"
obj2 = selection.obj
oRotateAtPointObject = RotateAtPoint(obj1 , 65, centroid(obj2))
insert into states (obj) values (RotateAtPointObject )
See Also
Rotate()
Round( ) function
Purpose
Returns a number obtained by rounding off another number.
Syntax
Round( num_expr, round_to )
num_expr is a numeric expression
round_to is the number to which num_expr should be rounded off
Return Value
Float
Description
The Round( ) function returns a rounded-off version of the numeric num_expr expression.
The precision of the result depends on the round_to parameter. The Round( ) function rounds
the num_expr value to the nearest multiple of the round_to parameter. If round_to is 0.01,
MapInfo Professional rounds to the nearest hundredth; if round_to is 5, MI Pro rounds to the
nearest multiple of 5; etc.
Example
Dim x, y As Float
x = 12345.6789
y = Round(x, 100)
’ y now has the value 12300
y = Round(x, 1)
’ y now has the value 12346
y = Round(x, 0.01)
’ y now has the value 12345.68
See Also
Fix( ), Format$( ), Int( )
RTrim$( ) function
Purpose
Trims space characters from the end of a string, and returns the results.
Syntax
RTrim$( string_expr )
string_expr is a string expression
Return Value
String
Description
The RTrim$( ) function removes any spaces from the end of the string_expr string, and returns
the resultant string.
Example
Dim s_name As String
s_name = RTrim$(”Mary Smith ”)
cmd_string = ” x = Abs(y) ”
Run Command cmd_string
However, variable names can be used in the construction of the command string. In the
following example, the command string is constructed from an expression that includes a
character variable.
’this example WILL work
Dim cmd_string As String
Dim map_it, browse_it As Logical
Example
The Run Command statement provides a flexible way of issuing commands that have variable-
length argument lists. For example, the Map From statement can include a single table name,
or a comma-separated list of two or more table names. An application may need to decide at
run time (based on feedback from the user) how many table names should be included in the
Map From statement. One way to do this is to construct a text string at run time, and execute
the command through the Run Command statement.
Dim cmd_text As String
Dim cities_wanted, counties_wanted As Logical
If counties_wanted Then
cmd_text = ”counties, ” + cmd_text
End If
If cities_wanted Then
cmd_text = ”cities, ” + cmd_text
End If
The following example shows how to duplicate a Map window, given the window ID of an
existing map. The WindowInfo( ) call returns a string containing MapBasic statements; the Run
Command statement executes the string.
Dim i_map_id As Integer
See Also
Run Application, Run Program
SearchInfo( ) function
Purpose
Returns information about the search results produced by SearchPoint( ) or SearchRect( ).
Syntax
SearchInfo ( sequence_number , attribute )
sequence_number is an Integer number, from 1 to the number of objects located
attribute is a small Integer code from the table below
Return Value
String or Integer, depending on attribute
Description
After you call SearchRect( ) or SearchPoint( ) to search for map objects, call SearchInfo( ) to
process the search results.
The sequence_number argument is an Integer number, 1 or larger. The number returned by
SearchPoint( ) or SearchRect( ) is the maximum value for the sequence_number.
The attribute argument must be one of the codes (from MAPBASIC.DEF) in the following table:
Include ”mapbasic.def”
Include ”icons.def”
Declare Sub Main
Declare Sub tool_sub
Sub Main
Create ButtonPad ”Searcher” As
ToolButton Calling tool_sub ID 1
Icon MI_ICON_ARROW
Cursor MI_CURSOR_ARROW
DrawMode DM_CUSTOM_POINT
HelpMsg ”Click on a map location\nClick a location”
Separator
ToolButton Calling tool_sub ID 2
Icon MI_ICON_SEARCH_RECT
Cursor MI_CURSOR_FINGER_LEFT
DrawMode DM_CUSTOM_RECT
HelpMsg ”Drag a rectangle in a map\nDrag a rectangle”
Width 3
If CommandInfo(CMD_INFO_TOOLBTN) = 1 Then
’ Then the user is using the point-mode tool.
’ determine how many objects are at the chosen point.
i_found = SearchPoint(i_win_id, x, y)
Else
’ The user is using the rectangle-mode tool.
’ Determine what objects are within the rectangle.
x2 = CommandInfo(CMD_INFO_X2)
y2 = CommandInfo(CMD_INFO_y2)
i_found = SearchRect(i_win_id, x, y, x2, y2)
End If
If i_found = 0 Then
Beep ’ No objects found where the user clicked.
Else
Print Chr$(12)
If CommandInfo(CMD_INFO_TOOLBTN) = 2 Then
Print ”Rectangle: x1= ” + x + ”, y1= ” + y
SearchPoint( ) function
Purpose
Searches for map objects at a specific x/y location.
Syntax
SearchPoint ( map_window_id , x , y )
map_window_id is a Map window’s Integer ID number
x is an x-coordinate (e.g., longitude)
y is a y-coordinate (e.g., latitude)
Return Value
Integer, representing the number of objects found
Description
The SearchPoint( ) function searches for map objects at a specific x/y location. The search
applies to all selectable layers in the Map window, even the Cosmetic layer (if it is currently
selectable). The return value indicates the number of objects found.
This function does not select any objects, nor does it affect the current selection. Instead, this
function builds a list of objects in memory. After calling SearchPoint( ), call SearchInfo( ) to
process the search results.
The search allows for a small tolerance, identical to the tolerance allowed by MapInfo
Professional’s Info tool. Points or linear objects that are very close to the location are included
in the search results, even if the user did not click on the exact location of the object.
To allow the user to select an x/y location with the mouse, use the Create ButtonPad statement
or the Alter ButtonPad statement to create a custom ToolButton. Use DM_CUSTOM_POINT as
the button’s draw mode. Within the button’s handler procedure, call CommandInfo( ) to
determine the x/y coordinates.
Example
For a code example, see SearchInfo( ).
See Also
SearchInfo( ), SearchRect( )
SearchRect( ) function
Purpose
Searches for map objects within a rectangular area.
Syntax
SearchRect ( map_window_id , x1 , y1 , x2 , y2 )
map_window_id is a Map window’s Integer ID number
x1 , y1 are coordinates that specify one corner of a rectangle
x2 , y2 are coordinates that specify the opposite corner of a rectangle
Return Value
Integer, representing the number of objects found
Description
The SearchRect( ) function searches for map objects within a rectangular area. The search
applies to all selectable layers in the Map window, even the Cosmetic layer (if it is currently
selectable). The return value indicates the number of objects found.
Note: This function does not select any objects, nor does it affect the current selection. Instead,
this function builds a list of objects in memory. After calling SearchRect() you call
SearchInfo( ) to process the search results.
The search behavior matches the behavior of MapInfo Professional’s Marquee Select button: If
an object’s centroid falls within the rectangle, the object is included in the search results.
To allow the user to select a rectangular area with the mouse, use the Create ButtonPad
statement or the Alter ButtonPad statement to create a custom ToolButton. Use
DM_CUSTOM_RECT as the button’s draw mode. Within the button’s handler procedure, call
CommandInfo( ) to determine the x/y coordinates.
Example
For a code example, see SearchInfo( ).
See Also
SearchInfo( ), SearchPoint( )
Seek( ) function
Purpose
Returns the current file position.
Syntax
Seek ( filenum )
filenum is the number of an open file
Return Value
Integer
Description
The Seek( ) function returns MapBasic’s current position in an open file.
The file parameter represents the number of an open file; this is the same number specified in
the As clause of the Open File statement.
The integer value returned by the Seek( ) function represents a file position. If the file was
opened in random-access mode, Seek( ) returns a record number (the next record to be read or
written). If the file was opened in binary mode, Seek( ) returns the byte position of the next
byte to be read from or written to the file.
Error Conditions
ERR_FILEMGR_NOTOPEN error generated if the specified file is not open
See Also
Get, Open File, Put, Seek
Seek statement
Purpose
Sets the current file position, to prepare for the next file input/output operation.
Syntax
Seek [ # ]filenum , position
filenum is an Integer value, indicating the number of an open file
position is an Integer value, indicating the desired file position
Description
The Seek statement resets the current file position of an open file. File input / output
operations which follow a Seek statement will read from (or write to) the location specified by
the Seek.
If the file was opened in Random access mode, the position parameter specifies a record
number.
If the file was opened in a sequential access mode, the position parameter specifies a specific
byte position; a position value of one represents the very beginning of the file.
See Also
Get, Input #, Open File, Print #, Put, Seek( ), Write #
SelChangedHandler procedure
Purpose
A reserved procedure, called automatically when the set of selected rows changes.
Syntax
Declare Sub SelChangedHandler
Sub SelChangedHandler
statement_list
End Sub
statement_list is a list of statements to execute when the set of selected rows changes
Description
SelChangedHandler is a special MapBasic procedure name. If the user runs an application
with a procedure named SelChangedHandler, the application “goes to sleep” when the Main
procedure runs out of statements to execute. The sleeping application remains in memory until
the application executes an End Program statement. As long as the application remains in
memory, MapInfo Professional automatically calls the SelChangedHandler procedure
whenever the set of selected rows changes.
Within the SelChangedHandler procedure, you can obtain information about recent changes
made to the selection by calling CommandInfo( ) with one of the following codes:
Select statement
Purpose
Selects particular rows and columns from one or more open tables, and treats the results as a
separate, temporary table. Also provides the ability to sort and sub-total data.
Syntax
Select expression_list
From table_name [ , ... ] [ Where expression_group ]
[ Into results_table [ Noselect ] ]
[ Group By column_list ]
[ Order By column_list ]
expression_list is a comma-separated list of expressions which will comprise the columns of the
Selection results
expression_group is a list of one or more expressions, separated by the keywords AND or OR
table_name is the name of an open table
results_table is the name of the table where query results should be stored
column_list is a list of one or more names of columns, separated by commas
Description
The Select statement provides MapBasic programmers with the capabilities of MapInfo
Professional’s Query > SQL Select dialog.
The MapBasic Select statement is modeled after the Select statement in the Structured Query
Language (SQL). Thus, if you have used SQL-oriented database software, you may already be
familiar with the Select statement. Note, however, that MapBasic’s Select statement includes
geographic capabilities that you will not find in other packages.
Column expressions (e.g., tablename.columnname ) in a Select statement may only refer to tables
that are listed in the Select statement’s From clause. For example, a Select statement may only
incorporate the column expression STATES.OBJ if the table STATES is included in the
statement’s From clause.
The Select statement serves a variety of different purposes. One select statement might apply a
test to a table, making it easy to browse only the records which met the criteria (this is
sometimes referred to as filtering). Alternately, Select might be used to calculate totals or
subtotals for an entire table. Select can also: sort the rows of a table; derive new column values
from one or more existing columns; or combine columns from two or more tables into a single
results table.
Generally speaking, a Select statement queries one or more open tables, and selects some or all
of the rows from said table(s). The Select statement then treats the group of selected rows as a
results table; Selection is the default name of this table (although the results table can be
assigned another name through the Into clause). Following a Select statement, a MapBasic
program - or, for that matter, an MI Pro user - can treat the results table as any other MapInfo
table.
After issuing a Select statement, a MapBasic program can use the SelectionInfo( ) function to
examine the current selection.
The Select statement format includes several clauses, most of which are optional. The nature
and function of a Select statement depend upon which clauses are included. For example: if
you wish to use a Select statement to set up a filter, you should include a Where clause; if you
wish to use a Select statement to subtotal the values in the table, you should include a Group
By clause; if you want MapBasic to sort the results of the Select statement, you should include
an Order By clause. Note that these clauses are not mutually exclusive; one Select statement
may include all of the optional clauses.
Select clause
This clause dictates which columns MapBasic should include in the results table. The simplest
type of expression_list is an asterisk character (“*”). The asterisk signifies that all columns
should be included in the results. The statement:
Select * From world
tells MapBasic to include all of the columns from the “world” table in the results table.
Alternately, the expression_list clause can consist of a list of expressions, separated by commas,
each of which represents one column to include in the results table. Typically, each of these
expressions involves the names of one or more columns from the table in question. Very often,
MapBasic function calls and/or operators are used to derive some new value from one or more
of the column names. For example, the following Select statement specifies an expression_list
clause with two expressions:
Select country, Round(population,1000000)
From world
The expression_list above consists of two expressions, the first of which is a simple column name
(country), and the second of which is a function call ( Round( ) ) which operates on another
column (population).
After MapBasic carries out the above Select statement, the first column in the results table will
contain values from the world table’s name column. The second column in the results table will
contain values from the world table’s population column, rounded off to the nearest million.
Each expression in the expression_list clause can be explicitly named by having an alias follow
the expression; this alias would appear, for example, at the top of a Browser window
displaying the appropriate table. The following statement would assign the field alias
“Millions” to the second column of the results table:
Select country,Round(population,1000000) ”Millions”
From world
Any mappable table also has a special column, called object (or obj for short). If you include the
column expression obj in the expression_list, the resultant table will include a column which
indicates what type of object (if any) is attached to that row.
The expression_list may include either an asterisk or a list of column expressions, but not both. If
an asterisk appears following the keyword Select, then that asterisk must be the only thing in
the expression_list. In other words, the following statement would not be legitimate:
Select *, object From world ’ this won’t work!
From clause
The From clause specifies which table(s) to select data from. If you are doing a multiple-table
join, the tables you are selecting from must be base tables, rather than the results of a previous
query.
Where clause
One function of the Where clause is to specify which rows to select. Any expression can be used
(see Expressions section below). Note, however, that groups of two or more expressions must be
connected by the keywords And or Or, rather than being comma-separated. For example, a
two-expression Where clause might read like this:
Suppose the Q4Sales table describes sales information for the fourth fiscal quarter. Each record
in this table contains information about the dollar amount of a particular sale. Each record’s
Territory column indicates the name of the territory where the sale occurred. The following
query counts how many sales occurred within each territory, and calculates the sum total of all
of the sales within each territory.
Select territory, Count(*), Sum(amount)
From q4sales
Group By territory
The Group By clause tells MapBasic to group the table results according to the contents of the
Territory column, and then create a subtotal for each unique territory name. The expression list
following the keyword Select specifies that the results table should have three columns: the
first column will state the name of a territory; the second column will state the number of
records in the q4sales table “belonging to” that territory; and the third column of the results
table will contain the sum of the Amount columns of all records belonging to that territory.
Note: The Sum( ) function requires a parameter, to tell it which column to summarize. The
Count( ) function, however, simply takes an asterisk as its parameter; this tells MapBasic
to simply count the number of records within that sub-totalled group. The Count( )
function is the only aggregate function that does not require a column identifier as its
parameter.
The following table describes MI Pro’s aggregate functions.
another group; etc. For each group of rows—in other words, for each continent—MI Pro
calculates a weighted average of the literacy rates.
A simple average (using the Avg( ) function) calculates the sum divided by the count. A
weighted average (using the WtAvg( ) function) is more complicated, in that some rows affect
the average more than other rows. In this example, the average calculation is weighted by the
Pop_1994 (population) column; in other words, countries that have a large population will
have more of an impact on the result than countries that have a small population.
Column Expressions in the Group By clause
In the preceding example, the Group By territory clause identifies the Territory column by
name. Alternately, a Group By clause can identify a column by a number, using an expression
of the form col#. In this type of expression, the # sign represents an integer number, having a
value of one or more, which identifies one of the columns in the Select clause. Thus, the above
Select statement could have read Group By col1, or even Group By 1, rather than Group By
territory.
It is sometimes necessary to use one of these alternate syntaxes. If you wish to Group By a
derived expression, which does not have a column name, then the Group By clause must use
the col# syntax or the # syntax to refer to the proper column expression. In the following
example, we Group By a column value derived through the Month( ) function. Since this
column expression does not have a conventional column name, our Group By clause refers to it
using the col# format:
Select Month(sick_date), Count(*)
From sickdays
Group By 1
This example assumes that each row in the sickdays table represents a sick day claim. The
results from this query would include twelve rows (one row for each month); the second
column would indicate how many sick days were claimed for that month.
Grouping By Multiple Columns
Depending on your application, you may need to specify more than one column in the Group
By clause; this happens when the contents of a column are not sufficiently unique. For example,
you may have a table describing counties across the United States. County names are not
unique; for example, many different states have a Franklin county. Therefore, if your Group By
clause specifies a single county-name column, MapBasic will create one sub-total row in the
results table for the county “Franklin”. That row would summarize all counties having the
name “Franklin”, regardless of whether the records were in different states.
When this type of problem occurs, your Group By clause must specify two or more columns,
separated by commas. For example, a group by clause might read:
Group By county, state
With this arrangement, MapBasic would construct a separate group of rows (and, thus, a
separate sub-total) for each unique expression of the form countyname , statename. The results
table would have separate rows for Franklin County, MA versus Franklin County, FL.
Order By clause
This optional clause specifies which column or set of columns to order the results by. As with
the Group By clause, the column is specified by name in the field list, or by a number
representing the position in the field list. Multiple columns are separated by commas.
By default, results sorted by an Order By clause are in ascending order. An ascending character
sort places “A” values before “Z” values; an ascending numeric sort places small numbers
before large ones. If you want one of the columns to be sorted in descending order, you should
follow that column name with the keyword DESC.
Select * From cities
Order By state, population Desc
This query performs a two-level sort on the table Cities. First, MapBasic sorts the table, in
ascending order, according to the contents of the state column. Then MapBasic sorts each state’s
group of records, using a descending order sort of the values in the population column. Note
that there is a space, not a comma, between the column name and the keyword DESC.
The Order By clause may not reference a function with a variable return type, such as the
ObjectInfo( ) function.
Geographic Operators
MapBasic supports several geographic operators: Contains, Contains Part, Contains Entire,
Within, Partly Within, Entirely Within, and Intersects. These operators can be used in any
expression, and are very useful within the Select statement’s Where clause. All geographic
operators are infix operators (operate on two objects and return a boolean). The operators are
listed in the table below.
Selection Performance
Some Select statements are considerably faster than others, depending in part on the contents
of the Where clause.
If the Where clause contains one expression of the form:
columnname = constant_expression
or if the Where clause contains two or more expressions of that form, joined by the And
operator, then the Select statement will be able to take maximum advantage of indexing,
allowing the operation to proceed quickly. However, if multiple Where clause expressions are
joined by the Or operator instead of by the And operator, the statement will take more time,
because MI Pro will not be able to take maximum advantage of indexing.
Similarly, MI Pro provides optimized performance for Where clause expressions of the form:
[ tablename . ] obj geographic_operator object_expression
and for Where clause expressions of the form:
RowID = constant_expression
RowID is a special column name. Each row’s RowID value represents the corresponding row
number within the appropriate table; in other words, the first row in a table has a RowID value
of one.
Examples
This example selects all customers that are in New York, Connecticut, or Massachusetts. Each
customer record does not need to include a state name; rather, the query relies on the
geographic position of each customer object to determine whether that customer is “in” a given
state.
Select * From customers
Where obj Within Any(Select obj From states
Where state = ”NY” or state = ”CT” or state = ”MA”)
The next example demonstrates a sub-select. Here, we want to select all sales territories which
contain customers that have been designated as “Federal.” The subselect selects all customer
records flagged as Federal, and then the main select works from the list of Federal customers to
select certain territories.
Select * From territories
Where obj Contains Any (Select obj From customers
Where customers.source = ”Federal”)
The following query selects all parcels that touch parcel 120059.
Select * From parcels
Where obj Intersects (Select obj From parcels
Where parcel_id = 120059)
See Also
Open Table
SelectionInfo( ) function
Purpose
Returns information about the current selection.
Note: Selected labels do not count as a “selection,” because labels are not complete objects,
they are attributes of other objects.
Syntax
SelectionInfo( attribute )
attribute is an Integer code from the table below.
Return Value
String or Integer; see table below
Description
The table below summarizes the codes (from MAPBASIC.DEF) that you can use as the attribute
parameter.
Note: If the current selection is the result of a join of two or more tables,
SelectionInfo(SEL_INFO_NROWS) returns the number of rows selected in the base
table, which might not equal the number of rows in the Selection table. See example
below.
Error Conditions
ERR_FCN_ARG_RANGE error generated if an argument is outside of the valid range
Example
The following example uses a Select statement to perform a join. Afterwards, the variable i
contains 40 (the number of rows currently selected in the base table, States) and the variable j
contains 125 (the number of rows in the query results table).
Dim i, j As Integer
Select * From States, City_125
Where States.obj Contains City_125.obj Into QResults
i = SelectionInfo(SEL_INFO_NROWS)
j = TableInfo(QResults, TAB_INFO_NROWS)
See Also
Select, TableInfo( )
Example
’ Application to ”print” address labels
’ Assumes that a relational table ADDR exists with 6 columns...
Dim hdbc, hstmt As Integer
Dim first_name, last_name, street, city, state, zip As String
Dim fn_stat, ln_stat, str_stat, ct_stat, st_stat, zip_stat As Integer
hdbc = Server_Connect(”ODBC”, ”DLG=1”)
hstmt = Server_Execute( hdbc, ”select * from ADDR”)
Server hstmt Bind Column 1 To first_name,fn_stat
Server hstmt Bind Column 2 To last_name, ln_stat
Server hstmt Bind Column 3 To street, str_stat
Server hstmt Bind Column 4 To city, ct_stat
Server hstmt Bind Column 5 To state, st_stat
Server hstmt Bind Column 6 To zip, zip_stat
Server hstmt Fetch NEXT
Server_ColumnInfo( ) function
Purpose
Retrieves information about columns in a resultset.
Syntax
Server_ColumnInfo(StatementNumber, ColumnNo, Attr)
StatementNumber is an integer value that identifies information about an SQL statement.
ColumnNo is the number of the column in the table, starting at 1 with the leftmost column.
Attr is a code indicating which aspect of the column to return.
Return Value
The return value is conditional based on the value of the attribute passed (Attr).
Description
The Server_ColumnInfo function returns information about the current fetched column in the
resultset of a remote data source described by a remotely executed Select statement. The
Statementnumber parameter specifies the particular statement handle associated with that
connection. The ColumnNo parameter indicates the desired column (the columns are numbered
from the left starting at 1). Attr selects the kind of information that will be returned.
The following table contains the attributes returned to the Attr parameter. These types are
defined in MAPBASIC.DEF.
Example
Dim hdbc, Stmt As Integer
Dim Col As Integer
hdbc = Server_Connect(”ODBC”, ”DLG=1”)
Stmt = Server_Execute(hdbc, ”Select * from emp”)
Server Stmt Fetch NEXT
For Col = 1 To Server_NumCols(Stmt)
Print Server_ColumnInfo(Stmt, Col, SRV_COL_INFO_NAME) +
” = ” +
Server_ColumnInfo(Stmt, Col, SRV_COL_INFO_VALUE)
Next
See Also
Server Bind Column, Server Fetch, Server_NumCols()
Server_Connect( ) function
Purpose
Establishes communications with a remote data server.
Syntax
Server_Connect(toolkit, connect_string)
toolkit is a string value identifying the remote interface, e.g., “ODBC”, “ORAINET”. Valid
values for toolkit can be obtained from the Server_DriverInfo( ) function.
connect_string is a string value with additional information necessary to obtain a connection to
the database.
Return Value
Integer
Description
The Server_Connect( ) function establishes a connection to a data source. This function returns
a connection number. A connection number is an identifier to the connection. This identifier
must be passed to all server statements that you wish to operate on the connection.
The parameter toolkit identifies the MapInfo Professional remote interface toolkit through
which the connection to a database server will be made. Information can be obtained about the
possible values via calls to Server_NumDrivers and Server_DriverInfo().
The connect_string parameter supplies additional information to the toolkit necessary to obtain
a connection to the database. The parameters depend on the requirements of the remote data
source being accessed.
The connection string sent to Server_Connect() has the form:
attribute=value[;attribute=value...]
(There are no spaces allowed in the connection string.)
Passing the DLG=1 connect option provides a nice connect dialog with active help buttons.
Microsoft ACCESS Attributes
The attributes used by ACCESS are:
Attribute Description
DSN The name of the ODBC data source for Microsoft ACCESS.
UID The user login ID.
PWD The user-specified password.
SCROLL The default value is NO. If SCROLL=YES the ODBC cursor library is
used for this connection allowing the ability to fetch first, last, previous,
or record n of the database.
An example of a connection string for ACCESS is:
”DSN=MI ACCESS;UID=ADMIN;PWD=SECRET”
Attribute Description
LogonID (UID) The logon ID (user name) that the application uses to
connect to your Oracle database. A logon ID is
required only if security is enabled on your database.
If so, contact your system administrator to get your
logon ID.
These conversions are performed on the client by the SQL Server Wire Protocol driver. This
requires that the same ANSI code page (ACP) used on the server be available on the client.
These settings have no effect on the conversions that occur for the following transfers:
Unicode SQL_C_WCHAR client data sent to char, varchar, or text on the server.
Char, varchar, or text server data sent to a Unicode SQL_C_WCHAR variable on the client.
ANSI SQL_C_CHAR client data sent to Unicode nchar, nvarchar, or ntext on the server.
Unicode char, varchar, or text server data sent to an ANSI SQL_C_CHAR variable on the client.
When set to no, character translation is not performed.
The SQL Server Wire Protocol driver does not translate client ANSI character SQL_C_CHAR
data sent to char, varchar, or text variables, parameters, or columns on the server. No
translation is performed on char, varchar, or text data sent from the server to SQL_C_CHAR
variables on the client.
If the client and SQL Server are using different ACPs, then extended characters can be
misinterpreted.
DATABASE: The name of the default SQL Server database for the connection. If DATABASE is
not specified, the default database defined for the login is used. The default database from the
ODBC data source overrides the default database defined for the login. The database must be
an existing database unless AttachDBFileName is also specified. If AttachDBFileName is
specified, the primary file it points to is attached and given the database name specified by
DATABASE.
LANGUAGE: The SQL Server language name (optional). SQL Server can store messages for
multiple languages in sysmessages. If connecting to a SQL Server with multiple languages, this
attribute specifies which set of messages are used for the connection.
Network: The name of a network library dynamic-link library. The name need not include the
path and must not include the .dll file name extension, for example, Network=dbnmpntw.
PWD: The password for the SQL Server login account specified in the UID parameter. PWD
need not be specified if the login has a NULL password or when using Windows NT
authentication (Trusted_Connection=yes).
QueryLogFile: The full path and file name of a file to be used for logging data about long-
running queries.
QueryLog_On: QueryLog_On={yes | no}. Determines whether long-running query data is
logged.
When set to yes, logging long-running query data is enabled on the connection.
When set to no, long-running query data is not logged.
QueryLogTime: A digit character string specifying the threshold (in milliseconds) for logging
long-running queries. Any query that does not receive a response in the time specified is
written to the long-running query log file.
QuotedID: QuotedID={yes | no}. Determines whether QUOTED_IDENTIFIERS is set ON or
OFF for the connection.
When set to yes, QUOTED_IDENTIFIERS is set ON for the connection, and SQL Server uses
the SQL-92 rules regarding the use of quotation marks in SQL statements.
When set to no, QUOTED_IDENTIFIERS is set OFF for the connection, and SQL Server uses the
legacy Transact-SQL rules regarding the use of quotation marks in SQL statements.
Regional: Regional={yes | no}. Determines how currency, date, and time data are converted.
When set to yes, the SQL Server Wire Protocol driver uses client settings when converting
currency, date, and time data to character data. The conversion is one way only; the driver does
not recognize non-ODBC standard formats for date strings or currency values.
When set to no, the driver uses ODBC standard strings to represent currency, date, and time
data that is converted to string data.
SAVEFILE: The name of an ODBC data source file into which the attributes of the current
connection are saved if the connection is successful.
SERVER: The name of a server running SQL Server on the network. The value must be either
the name of a server on the network, or the name of a SQL Server Client Network Utility
advanced server entry. You can enter "(local)" as the server name on Windows NT to connect to
a copy of SQL Server running on the same computer.
StatsLogFile: The full path and file name of a file used to record SQL Server Wire Protocol
driver performance statistics.
StatsLog_On: StatsLog_On={yes | no}. Determines whether SQL Server Wire Protocol driver
performance data is available.
When set to yes, SQL Server Wire Protocol driver performance data is captured.
When set to no, SQL Server Wire Protocol driver performance data is not available on the
connection.
Trusted_Connection: Trusted_Connection={yes | no}. Determines what information the SQL
Server Wire Protocol driver will use for login validation.
When set to yes, the SQL Server Wire Protocol driver uses Windows NT Authentication Mode
for login validation. The UID and PWD keywords are optional.
When set to no, the SQL Server Wire Protocol driver uses a SQL Server username and
password for login validation. The UID and PWD keywords must be specified.
UID: A valid SQL Server login account. UID need not be specified when using Windows NT
authentication.
WSID: The workstation ID. Typically, this is the network name of the computer on which the
application resides (optional). If specified, this value is stored in the master.dbo.sysprocesses
column hostname and is returned by sp_who and the Transact-SQL HOST_NAME function.
Informix Attributes
If your application requires a connection string to connect to a data source, you must specify
the data source name that tells the driver which section of the system information to use for the
default connection information. Optionally, you may specify attribute=value pairs in the
connection string to override the default values stored in the system information. These values
are not written to system information.
You can specify either long or short names in the connection string. The connection string has
the form:
DSN=data_source_name[;attribute=value[;attribute=value]...]
An example of a connection string for Informix is:
DSN=Informix TABLES;DB=PAYROLL
The paragraphs that follow give the long and short names for each attribute, as well as a
description. The defaults listed are initial defaults that apply when no value is specified in
either the connection string or in the data source definition in the system information. If you
specified a value for the attribute when configuring the data source, that value is the default.
See Also
Server Disconnect
Server_ConnectInfo function
Purpose
Retrieves information about the active database connections.
Syntax
Server_ConnectInfo (ConnectionNo, Attr)
ConnectionNumber is the integer returned by Server_Connect that identifies the database
connection.
Attr is a code indicating which information to return.
Return Value
String
Description
The Server_ConnectInfo function returns information about a database connection. The first
parameter selects the connection number (starting at 1). The second parameter selects the kind
of information that will be returned. Refer to the following table.
Example
Dim dbname as string
Dim hdbc As Integer
hdbc = Server_Connect(”ODBC”, ”DLG=1”)
dbname=Server_ConnectInfo(hdbc, SRV_CONNECT_INFO_DB_NAME)
Print dbname
coordinate system. The Coordinate System must be the same as the one specified in the Server
Create Map Statement when making it mappable. For other DBMS, this clause has no effect on
table creation.
The supported databases include Oracle, SQL Server, IUS, and Microsoft Access. However, to
create a table with a spatial geometry/object column, SpatialWare/Blade is required for SQL
Server and IUS, and the spatial option is required for Oracle.
Examples
The following examples show how to create a table named ALLTYPES that contains seven
columns that cover each of the data types supported by MI Pro, plus the three columns Key,
SpatialObject, and Style columns, for a total of ten columns.
For SQL Server with SpatialWare or IUS with SpatialWare Blade:
dim hodbc as integer
hodbc = server_connect("ODBC", "dlg=1")
Server hodbc Create Table ALLTYPES( Field1 char(10),Field2
integer,Field3 smallint,Field4 float,Field5 decimal(10,4),Field6
date,Field7 logical)
KeyColumn SW_MEMBER
ObjectColumn SW_GEOMETRY
StyleColumn MI_STYLE
For Oracle Spatial:
dim hodbc as integer
hodbc = server_connect("ORAINET",
"SRVR=cygnus;UID=mipro;PWD=mipro")
Server hodbc Create Table ALLTYPES( Field1 char(10),Field2
integer,Field3 smallint,Field4 float,Field5 decimal(10,4),Field6
date,Field7logical)
KeyColumn MI_PRINX
ObjectColumn GEOLOC
StyleColumn MI_STYLE
Coordsys Earth Projection 1, 0
See also
Server Link, Unlink, Create Map, Server Create Map
Server_DriverInfo( ) function
Purpose
Retrieves information about the installed toolkits and data sources.
Syntax
Server_DriverInfo(DriverNo, Attr)
DriverNo is an integer value assigned to an interface toolkit by MapInfo Professional when you
start MI Pro.
Attr is a code indicating which information to return.
Return Value
String
Description
The Server_DriverInfo function returns information about the data sources. The first
parameter selects the toolkit (starting at 1). The total number of toolkits can be obtained by a
call to the Server_NumDrivers() function. The second parameter selects the kind of
information that will be returned. Refer to the following table.
Example
Dim dlg_string, source As String
dlg_string = Server_DriverInfo(0, SRV_DRV_INFO_NAME_LIST)
source = Server_DriverInfo(1, SRV_DRV_DATA_SOURCE)
While source <> ””
Print ”Available sources on toolkit ” +
Server_DriverInfo(1, SRV_DRV_INFO_NAME) + ”: ” +
source
source = Server_DriverInfo(1,
SRV_DRV_DATA_SOURCE)
Wend
See Also
Server_NumDrivers( )
Server_EOT( ) function
Purpose
Determines whether the end of the result table has been reached via a Server Fetch statement.
Syntax
Server_EOT (StatementNumber)
Statementnumber is the is the number of the fetch statement you are checking.
Return Value
Logical
Description
The Server_EOT function returns TRUE or FALSE indicating whether the previous fetch
statement encountered a condition where there was no more data to return. Attempting to fetch
a previous record immediately after fetching the first record causes this to return TRUE.
Attempting to fetch the next record after the last record also returns a value of TRUE.
Example
Dim hdbc, hstmt As Integer
hdbc = Server_Connect(”ODBC”, ”DLG=1”)
hstmt = Server_Execute(hdbc, ”Select * from ADDR”)
Server hstmt Fetch FIRST
While Not Server_EOT(hstmt)
’ Processing for each row of data ...
Server hstmt Fetch Next
Wend
See Also
Server Fetch
Server_Execute( ) function
Purpose
Sends an SQL string to execute on a remote data server.
Syntax
Server_Execute(ConnectionNumber, server_string)
ConnectionNumber is an integer value that identifies the specific connection.
server_string is any valid SQL statement supported by the connected server. Refer to the SQL
language guide of your server database for information on valid SQL statements.
Return Value
Integer
Description
The Server_Execute function sends the server_string (an SQL statement) to the server
connection specified by the ConnectionNumber. Any valid SQL statement supported by the
active server is a valid value for the server_string parameter. Refer to the SQL language guide of
your server database for information on valid SQL statements.
This function returns a statement number. The statement number is used to associate
subsequent SQL requests, like the Fetch and Close operations, to a particular SQL statement.
You should perform a Server Close for each Server_Execute function as soon as you are done
using the statement handle. For selects, this is as soon as you are done fetching the desired
data. This will close the cursor on the remote server and free up the result set. Otherwise, you
can exceed the cursor limit and further executes will fail. Not all database servers support
forward and reverse scrolling cursors. For other SQL commands, issue a Server Close
statement immediately following the Server_Execute function.
Dim hdbc, hstmt As Integer
hdbc = Server_Connect(”ODBC”, ”DLG=1”)
hstmt = Server_Execute(hdbc, ”Select * from ADDR”)
Server hstmt Close
Example
Dim hdbc, hstmt As Integer
hdbc = Server_Connect(”ODBC”, DSN=ORACLE7;DLG=1”)
hstmt = Server_Execute (hdbc,
”CREATE TABLE NAME_TABLE (NAME CHAR (20))”)
Server hstmt Close
hstmt = Server_Execute (hdbc,
”INSERT INTO NAME_TABLE VALUES (‘Steve’)”)
Server Close hstmt
hstmt = Server_Execute ( hdbc,
”UPDATE NAME_TABLE SET name = ‘Tim’ ”)
Server Close hstmt
Server hdbc Disconnect
See Also
Server Close, Server Fetch
Server_GetodbcHConn( ) function
Purpose
Return the ODBC connection handle associated with the remote database connection.
Syntax
Server_GetodbcHConn (ConnectionNumber)
ConnectionNumber is the Integer returned by Server_Connect that identifies the database
connection.
Description
This function returns an Integer containing the ODBC connection handle associated with the
remote database connection. This enables you to call any function in the ODBC DLL to extend
the functionality available through the MapBasic Server Statements.
Example
’* Find the identity of the Connected database
DECLARE FUNCTION SQLGetInfo LIB ”ODBC32.DLL” (BYVAL odbchdbc AS
INTEGER, BYVAL infoflag AS INTEGER, val AS STRING, BYVAL len AS
INTEGER, outlen AS INTEGER) AS INTEGER
’ Connect to a database
hdbc = Server_Connect(”ODBC”, ”DLG=1”)
odbchdbc = Server_GetodbcHConn(hdbc) ’ get ODBC connection handle
Server_GetodbcHStmt( ) function
Purpose
Return the ODBC statement handle associated with the MapBasic Server statement.
Syntax
Server_GetodbcHStmt(StatementNumber)
StatementNumber is the integer returned by Server_Execute() that identifies the result set of the
SQL statement executed.
Description
This function returns the ODBC statement handle associated with the MapBasic Server
statement. This enables you to call any ODBC function to extend the functionality available
through the MapBasic Server Statements.
Example
’ Find the Number of rows affected by an Update
Dim rc, outlen, hdbc, hstmt, odbchstmt AS INTEGER
Dim RowsUpdated AS INTEGER
’ Find the Number of rows affected by an Update
DECLARE FUNCTION SQLRowCount LIB ”ODBC32.DLL” (BYVAL odbchstmt AS
INTEGER, rowcnt AS INTEGER) AS INTEGER
hdbc = Server_Connect(”ODBC”, ”DLG=1”)
hstmt = Server_Execute(hdbc, ”UPDATE TIML.CUSTOMER SET STATE=’NY’
WHERE STATE=’NY’”)
odbchstmt = Server_GetodbcHStmt(hstmt)
rc = SQLRowCount(odbchstmt, RowsUpdated)
Note ”Updated ” + RowsUpdated + ” New customers to Tier 1”
See Also
Server_GetodbcHConn( )
Server_NumCols( ) function
Purpose
Retrieves the number of columns in the resultset.
Syntax
Server_NumCols(StatementNumber)
StatementNumber is an integer value that identifies information about an SQL statement.
Return Value
Integer
Description
The Server_NumCols() function returns the number of columns in the resultset currently
referenced by StatementNumber.
Example
Dim hdbc, hstmt As Integer
hdbc = Server_Connect(”ODBC”, ”DLG=1”)
hstmt = Server_Execute(hdbc, ”Select Name, Addr from emp”)
Print ”Number of columns = ” + Server_NumCols(hstmt)
See Also
Server ColumnInfo()
Server_NumDrivers( ) function
Purpose
Retrieves the number of database connection toolkits currently installed for access from
MapInfo Professional.
Syntax
Server_NumDrivers()
Return Value
Integer
Description
The Server_NumDrivers() function returns the number of database connection toolkits
installed for use by MI Pro.
Example
Print ”Number of drivers = ” + Server_NumDrivers()
See Also
Server_DriverInfo()
Example
Server Refresh ”City_1k”
See Also
Commit Table, Server Link, Unlink
...
SessionInfo () function
Purpose
Returns various pieces of information about a running session of MapInfo Professional.
Syntax
SessionInfo( attribute )
attribute is an Integer code indicating which session attribute to query
Return Value
String
Description
The SessionInfo( ) function returns information about MI Pro's session status. The
attribute can be any of the codes listed in the table below. The codes are defined in
MAPBASIC.DEF.
Error Conditions
ERR_FCN_ARG_RANGE error generated if an argument is outside of the valid range
Example
Include "mapbasic.def"
print SessionInfo(SESSION_INFO_COORDSYS_CLAUSE)
Example
Set Area Units ”acre”
See Also
Area( ), Set Distance Units
Example
Set Distance Units ”km”
See Also
Distance( ), ObjectLen( ), Set Area Units, Set Paper Units
Example
Suppose a date variable (date_var) contains the date June 11, 1995. The function call:
Str$( date_var )
may return “06/11/95” or “95/11/06” depending on the date formatting options set up on the
user’s computer. If you use the Set Format Date “US” statement before calling Str$( ), you
force the Str$( ) function to follow U.S. formatting (Month/Day/Year), which makes the results
predictable.
See Also
Format$( ), FormatNumber$( ), Str$( ), StringToDate( ), SystemInfo( )
[ Pen . . . ]
[ Title axis_title [ Font . . . ] ] ]
[ Legend
[ Title legend_title [ Font . . . ] ]
[ Subtitle legend_subtitle [ Font . . . ] ]
[ Range [ Font . . . ] ]
]
window_id is the window identifier of a Grapher window
overlap_percent is the percentage value, from zero to 100, dictating bar overlap
gutter_percent is a percentage value, from zero to 100, dictating space between bars
angle is a number from zero to 360, representing the starting angle of a pie chart
graph_title is the title that appears at the top of the Grapher window
axis_title is a title that appears on one of the axes of the Grapher window
min_value is the minimum value to show along the appropriate axis
max_value is the maximum value to show along the appropriate axis
cross_value is the value at which the axes should cross
unit_value is the unit increment between labels on an axis
series_num is an integer identifying which series of a graph to modify (e.g., 2, 3, ...)
series_title is the name of a series; this appears next to the pen/brush sample in the Legend
legend_title and legend_subtitle are text strings which appear in the Legend
The Line clause specifies a line style
The Brush clause specifies a fill style, and the Pen clause specifies the fill’s border
The Symbol clause specifies a symbol style
The Font clause specifies a text style
Description
The Set Graph statement alters the settings of an existing Graph window. If no window_id is
specified, the statement affects the topmost Graph. This statement allows a MapBasic program
to control those options which an end-user would set through MapInfo Professional’s Graph
menu, as well as some options which a user would set through the Customize Legend dialog.
Between sessions, MI Pro preserves Graph settings by storing a Set Graph statement in the
workspace file. Thus, to see an example of the Set Graph statement, you could create a Graph,
save the workspace (e.g., GRAPHER.WOR), and examine the workspace in a MapBasic text
edit window. You could then cut/copy and paste to put the Set Graph statement in your
MapBasic program file.
To change the width, height, or position of a Graph window, use the Set Window statement.
Graph commands in workspaces or programs that were created prior to version 5.5 will still
create a 5.0 graph window. When a 5.0 graph window is active in MapInfo Professional 5.5
and later, the 5.0 graph menu will be also be active, so the user can modify the graph using the
5.0 editing dialogs. The Create Graph wizard will always created a 5.5 graph window.
Example
5.5 and later graphs
include ’mapbasic.def’
graph_id = WindowId(4) ’ window code for a graph is 4
Set Graph
Window graph_id
Pen (1,2,117440512)
Title ”Order amounts ($)” Font (”Helv”,0,8,0)
’
’ the above title (”Order amounts...”) appears
’ along the grapher’s y-axis
’
’
’ The next set graph customizes graphical styles
’ for series 2. This dictates what color bars will
’ appear to represent the orders_rcvd column data.
’ Also controls what description will appear in the
’ legend
’
’ Since this is a bar graph, the Brush is the style
’ of prime importance; if this was a line graph,
’ the Line and Symbol clauses would be important).
’
Set Graph Series 2
Brush (8,255,16777215)
Line (1,2,0,255) Symbol (32,255,12)
Title ”Orders Received ($)”
’
’the above title will appear in the legend...
’
’
’ The next set graph customizes the styles
’ used by series 3 (orders_shipped).
’
Set Graph Series 3
Brush (2,12632256,201326591)
Line (1,2,0,0) Symbol (34,12632256,12)
Title ”Orders Shipped ($)”
’
’ the above title will appear in the legend...
’
’
’ the last Set Graph statement dictates what
’ Grapher-related title and subtitle will appear
’ in the Legend window, as well as what fonts will
’ be used in the legend.
’
Set Graph Legend
Title ”Orders Received vs. Orders Shipped”
Font (”Helv”,0,10,0) ’set the title font
Subtitle ”(by salesperson)”
Font (”Helv”,0,8,0) ’set subtitle font
Range font (”Helv”,2,8,0) ’set the font used for
’range descriptions
See Also
Graph, Set Window
See Also
SelChangedHandler, ToolHandler
The following statement tells MI Pro to always redraw the Layout window, when necessary, to
reflect changes in the client window(s):
Set Layout Frame Contents On
The following statement tells MI Pro to only redraw the Layout window when it is the active
window:
Set Layout Frame Contents Active
The following statement tells MI Pro to never redraw the Layout window:
Set Layout Frame Contents Off
When Frame Contents are set Off, each frame appears as a plain rectangle with a simple
description (e.g., “World Map”).
The Ruler clause controls whether MI Pro displays a ruler along the top and left edges of the
Layout window. By default, the Ruler is On.
The Zoom clause specifies the magnification factor of the page layout; in other words, it
enlarges or reduces the window’s view of the layout. For example, the following statement
specifies a zoom setting of fifty percent:
Set Layout Zoom 50.0
When a page layout is displayed at fifty percent, that means that an actual sheet of paper is
twice as wide and twice as high as it is represented on-screen (in the Layout window). Note
that the page layout can show extreme close-ups, for the sake of allowing accurate detail work.
Accordingly, a Layout window displayed at 200 percent will show a magnification of the page.
The Zoom clause can specify a zoom value anywhere from 6.25% to 800 %, inclusive.
The Zoom clause does not need to specify a specific percentage. The following statement tells
MI Pro to set the zoom level so that the entire page layout will appear in the Layout window at
one time:
Set Layout Zoom To Fit
Note: Once a Layout window’s frame object has been selected, a MapBasic program could
issue a Run Menu Command statement to perform a Move to back or Move to front
operation. Also, since frame objects are (in some senses) conventional MI Pro graphical
objects, MapBasic’s Alter Object statement lets an application reset the pen and brush
styles associated with frame objects.
To change the width, height, or position of a Layout window, use the Set Window statement.
Example
Set Layout
Zoom To Fit Extents To Fit
Ruler Off
Frame Contents On
See Also
Alter Object, Create Frame, Layout, Run Menu Command, Set Window
The remainder of the options for the Set Legend statement all pertain to the Layer clause; that
is, all of the clauses described below are actually sub-clauses within the Layer clause.
The Count clause dictates whether each line of the theme legend should include a count, in
parentheses, of how many of the table’s records belong to that range. The Shades, Symbols and
Lines clauses dictate which types of graphic objects appear in each line of the theme legend. If
the statement includes the Shades On clause, each line of the theme legend will include a
sample fill pattern. If the statement includes the Symbols On clause, each line of the theme
legend will include a sample symbol marker. If the statement includes the Lines On clause,
each line of the theme legend will include a sample line style.
The Title clause specifies what title, if any, will appear above the range information in the
theme legend. Similarly, the Subtitle clause specifies a subtitle. The title and the subtitle are
each limited to thirty-two characters. If a theme legend includes a title, a subtitle, and range
information, the objects will appear in that order - the title first, then the subtitle below it, then
the range information below the subtitle. If the optional Auto clause is used, the text is
automatically generated for each theme.
The Font clause specifies a text style.
The Ascending On clause arranges the range descriptions in ascending order. If this optional
clause is omitted, the default order of the ranges is descending.
The Ranges clause describes the text that will accompany each line in the theme legend. Each
range’s description consists of a text string ( range_title ) followed by a Display clause. The
Display clause (Display On or Display Off) dictates whether that range will be displayed in
the theme legend. Note If the Auto clause is not used, the Ranges clause must include a
range_title Display clause for each range in the thematic map, even if some of the ranges are not
to be displayed.
If a map layer is a graduated symbols theme, there should be exactly two range_title Display
clauses. If a map layer is shaded as a dot density theme, there should be exactly one range_title
Display clause. Otherwise, there should be one more range_title Display clause than there are
ranges; this is because the theme legend reserves one line for an artificial range known as “all
others”. The all-others range represents any and all objects which do not belong to any of the
other ranges.
See Also
Map, Open Window, Set Map, Set Window, Shade
distance is either be Spherical or Cartesian. All distance, length, perimeter, and area
calculations for objects contained in the Map Window will be performed using one of these
calculation methods. Note that if the Coordsys of the Map Window is NonEarth, then the
calculations will be performed using Cartesian methods regardless of the option chosen, and if
the Coordsys of the Map Window is Latitude/Longitude, then calculations will be performed
using Spherical methods regardless of the option chosen.
xy_unit is a string representing the name of an x/y coordinate unit (e.g., ”m” for meters,
”degree” for degrees). If the XY Units are in degrees, the Display Decimal clause specifies
whether to display in decimal degrees. Set to On to display in decimal degrees or Off to set in
degrees, minutes or seconds. Set Display Grid to display in Military grid reference Format.
Relief turns relief shading for a grid on or off. The grid must have relief shade information
calculated for it for it for this clause to have any effect. Relief shade information can be
calculated for a grid with the the Relief Shade command
Move Node can be 0 or 1. If the value is 0, duplicate nodes are not moved. If the value is 1, any
duplicate nodes within the same layer will be moved. If a Move Node value is specified, that
window is considered to be using a custom value. To return to using the default (from the
mapper preference), Move Nodes Default can be specified.
screen_dist and map_dist specify a map scale (e.g., screen_dist = 1 inch, map_dist = 1 mile).
num_inflections is a numeric expression, specifying the number of color:value inflection pairs.
alpha_value is an integer value representing the alpha channel value for translucency. Values
range from 0-255. 0 is completely transparent. 255 is completely opaque. Values between 0-255
make the image layer display translucent.
translucency_percent is an integer value representing the percentage of translucency for a raster
or grid image. Values range between 0-100. 0 is completely opaque. 100 is completely
transparent.
Either ALPHA or TRANSLUCENCY should be specified, not both since they are different
ways of specifying the same thing. If multiple tokens are specified, the last value will be used.
The ALPHA and TRANSLUCENCY tokens are new for Set Map. They apply to raster and grid
layers.
The CONTRAST, BRIGHTNESS and GRAYSCALE tokens are now supported for raster
layers. They now apply to both raster and grid layers.
The TRANSPARENCY and COLOR tokens are new for Set Map and only apply to raster
layers.
The TRANSPARENCY token determines whether and individual color is transparent for a
raster layer.
The COLOR token specifies which color is transparent in a raster layer.
color:expr is a color expression of, part of a color:value inflection pair.
In the syntax above, LAYERCLAUSE is a shorthand notation, not a MapBasic keyword. Each
LAYERCLAUSE has the syntax described below.
[ Layer layer_id
[ Activate { [ Using launch_expr ] | [ On { [ Labels ] | [ Objects ] ] | [ Relative Path {
On | Off } ] }
[ Editable { On | Off } ]
[ Selectable { On | Off } ]
[ Zoom ( min_zoom, max_zoom ) [ Units dist_unit ] [{ On | Off }] ]
[ Arrows { On | Off } ]
[ Centroids { On | Off } ]
[ Default Zoom ]
[ Nodes { On | Off }]
LABELCLAUSE
[ Display { Off | Graphic | Global } ]
[ Global Line ... ]
[ Global Pen ... ]
[ Global Brush ... ]
[ Global Symbol ... ]
[ Global Font ... ]
]
layer_id identifies which layer to modify; can be a Smallint (e.g., use 1 to specify the top map
layer other than Cosmetic) or a String representing the name of a table displayed in the map.
min_zoom is a numeric expression, identifying the minimum zoom at which the layer will
display.
max_zoom is a numeric expression, identifying the maximum zoom at which the layer will
display.
launch_expr is an expression that will resolve to the name of the file to launch when the object is
activated.
The Using clause sets the filename expression and the On clause sets the activation mode. At
least one of these clauses is required. If the Using clause is included, then filename_expr is
required.
If the On clause is included, then one or both of the Labels and Objects clauses are required. If
just Labels is included, then activation occurs on labels only. If just Objects is included, then
activation occurs on objects only. If both keywords are included, then activation occurs on both
labels and objects. By default activation occurs on labels only.
Use Relative Path On when the files to be launched are stored in a location relative to the table
in which the links are defined. Use Relative Path Off when the HotLinks are URLs or full path
files descriptions; this is the default.
The Line clause specifies a line style used to draw lines and polylines; identical to a Pen clause,
except that the keyword Pen is replaced by the keyword Line.
The Pen clause specifies a line style used to draw frames around filled objects.
The Brush clause specifies a fill style.
The Symbol clause specifies a symbol style.
The Font clause specifies a text style.
In the syntax above, LABELCLAUSE is a shorthand notation, not a MapBasic keyword. Each
LABELCLAUSE has the syntax described below:
[ Label [ Line { Simple | Arrow | None } ]
[ Position [ Center ] [ Above | Below ] [ Left | Right ] ]
[ Font ... ] [ Pen ... ]
[ With label_expr ]
[ Parallel { On | Off } ]
[ Visibility { On | Off | Zoom( min_vis , max_vis ) [Units dist_unit] } ]
[ Auto [ { On | Off } ] ]
[ Overlap [ { On | Off } ] ]
[ PartialSegments { On | Off } ]
[ Duplicates [ { On | Off } ] ]
[ Max [ number_of_labels ] ]
[ Offset offset_amount ]
[ Default ]
[ Object ID
[ Table alias ]
[ Visibility { On | Off } ]
[ Anchor ( anchor_x , anchor_y ) ]
Text text_string
[ Position [ Center ] [ Above | Below ] [ Left | Right ] ]
[ Font ... ] [ Pen ... ]
[ Line { Simple | Arrow | None } ]
[ Angle text_angle ]
[ Offset offset_amount ]
[ Callout ( callout_x, callout_y ) ] }
[ Object ... ]
]
label_expr is the expression to use for creating labels.
min_vis , max_vis are numbers specifying the minimum and maximum zoom distances within
which the labels will display.
dist_unit is a string representing the name of a distance unit (e.g., “mi” for miles, “m” for
meters; see Set Distance Units for a list of available unit names).
number_of_labels is an Integer representing the maximum number of labels MapInfo
Professional will display for the layer. If you omit the number_of_labels argument, there is no
limit.
offset_amount is a number from zero to 50 (representing a distance in points), causing the label
to be offset from its anchor point.
ID is an Integer that identifies an edited label; generated automatically when the user saves a
workspace. A label’s ID equals the row ID of the object that owns the label.
alias is the name of a table that is part of a seamless map. The Table alias clause generates an
error if this layer is not a seamless map.
anchor_x , anchor_y are map coordinates, specifying the anchor position for the label.
text_string is a string that will become the text of the label.
text_angle is an angle, in degrees, indicating the rotation of the text.
callout_x , callout_y are map coordinates, specifying the end of the label call-out line.
Description
The Set Map statement controls the settings of a Map window. If no window_id is specified, the
statement affects the topmost Map window. This statement allows a MapBasic program to
control options a user would set through MI Pro’s Map > Layer Control, Map > Change View
and Map > Options menu items. For example, the Set Map statement lets you configure which
map layer is editable, and lets you set the map’s zoom distance or scale.
Note: Set Map controls the contents of a Map window, not the size or position of the
window’s frame. To change the size or position of a Map window, use the Set Window
statement.
Between sessions, MI Pro preserves Map settings by storing a Set Map statement in a
workspace file. To see an example of the Set Map statement, create a map, save the workspace
(e.g., MAPPER.WOR), and examine the workspace in a MapBasic text edit window.
The order of the clauses in a Set Map statement is very important. Entering the clauses in an
incorrect order can generate a syntax error.
Display
Dictates what type of information should appear on the status bar when the Map window is
active. Display Zoom displays the current zoom (the width of the area displayed). Display
Scale displays the current scale. Display Position displays the position of the cursor (e.g.,
decimal degrees of longitude / latitude).
Set Map Display Position
Distance Units
Specifies the unit of measure used to display distance calculations (for example, in the Ruler
Tool window). For a list of area unit names, see the Set Distance Units statement.
Set Map Distance Units ”km”
Preserve
Controls how the Map window behaves when the user re-sizes the window. If you specify
Preserve Zoom then MI Pro redraws the entire Map window whenever the user re-sizes the
window. If you specify Preserve Scale then MI Pro only redraws the portion of the window
that needs to be redrawn. These options correspond to settings in MI Pro’s Change View dialog
box (Map menu > Change View).
Redraw
Disables or enables the automatic redrawing of the Map window. If you issue a Set Map
Redraw Off statement, subsequent statements can affect the map (e.g., Set Map, Add Map
Layer, Remove Map Layer) without causing MI Pro to redraw the Map window. After making
all necessary changes to the Map window, issue a Set Map Redraw On statement to restore
automatic redrawing (at which time, MI Pro will redraw the map once to show all changes).
Note: Some actions, such as panning and zooming, can cause MI Pro to redraw a Map
window even after you specify Redraw Off. If you find that the Redraw Off syntax does
not prevent window redraws, you may want to use the Set Event Processing Off
statement.
XY Units
Specifies the type of coordinate unit used to display x, y coordinates (e.g., when the user has
specified that the map should display the cursor position on the status bar). The unit name can
be “degree” (for degrees longitude/latitude) or a distance unit such as “m” for meters.
If the XY Units are in degrees, the Display Decimal clause specifies whether to display in
decimal degrees (On) or in degrees, minutes, seconds (Off). Display Grid will display
coordinates in Military Grid reference system format no matter how the XY Units are specified.
Set Map XY Units "m" Display Grid
Set Map XY Units "degree" Display Grid
Set Map XY Units "degree" Display Decimal On
Set Map XY Units "degree" Display Decimal Off
The following statement specifies meters as the coordinate unit:
Set Map XY Units ”m”
Changing the Order of Layers
The Order clause resets the order in which map layers are drawn. Each layer_num is a number
identifying a map layer, according to that layer’s original position in the map, where 1 (one) is
the top-most layer number (the layer which draws last, and therefore always appears on top).
The Cosmetic layer is a special layer, with a layer number of zero. The Cosmetic layer is always
drawn last; thus, a zero should not appear in an order clause. For example: given a Map
window with four layers (not including the Cosmetic layer), the following Set Map statement
will reverse the order of the topmost two layers:
Set Map Order 2, 1, 3, 4
Changing the Behavior of Individual Layers
Editable
Sets the Editable attribute for the appropriate Layer. At any given time, only one of the
mapper’s layers may have the Editable attribute turned on. Note that turning on a layer’s
Editable attribute automatically turns on that layer’s Selectable attribute. The following Set
Map statement turns on the Editable attribute for first non-cosmetic layer:
Set Map
Layer 1 Editable On
Selectable
Sets whether the given layer should be selectable through operations such as Radius-Search.
Any or all of the Map layers can have the Selectable attribute on. The following Set Map
statement turns on the Selectable attribute for the first non-cosmetic map layer, and turns off
the Selectable attribute for the second and third map layers:
Set Map
Layer 1 Selectable On
Layer 2 Selectable Off
Layer 3 Selectable Off
Zoom
Configures the zoom-layering of the specified layer. Each layer can have a zoom-layering
range; this range, when enabled, tells MI Pro to only display the Map layer when the map’s
zoom distance is within the layering range. The following statement sets a range of 0 to 10
miles for the first non-Cosmetic layer.
Set Map
Layer 1 Zoom (0, 10) Units ”km” On
The On keyword activates zoom layering for the layer. To turn off zoom layer, specify Off
instead.
Set Map Clause for HotLinks
An active object is an object in a map window that has a URL or filename associated with it.
Clicking on an active object with the new HotLink Tool will launch the associated URL or file.
For example, if the string http://www.boston.com is associated with a point object on the map,
then clicking the point, or it’s label, will result in the default browser being started with the site
http://www.boston.com. You can associated other types of files with map objects; MapInfo
workspace (.wor), table (.tab) or application (.mbx) files, Word documents (.doc), executable
files (.exe), etc. Any type of file that the system knows how to ”launch” can be associated with
a map object.
About Relative Path Settings
The Relative Path setting allows you to define links to files stored in locations relative to the
tables. For example: if the table c:\data\states.tab contains HotLinks to workspace files that are
stored in directories under c:\data. The workspace file for New York, newyork.wor, is stored
in c:\data\ny and the HotLink associated with New York is “ny\newyork.wor”. Setting
Relative Path to On tells MI Pro to prefix the HotLink string with the location of the .tab file, in
this case resulting in the launch string “c:\data\ny\newyork.wor”.
Note: HotLinks identified as URLs are not modified before launch, regardless of the Relative
Path setting. The ShellAPI function path’s URL is used to determine if a HotLink is a
URL.
Changing the Appearance of Individual Layers
Arrows
Turns the display of direction arrows on or off.
Centroids
Turns the display of centroids on or off.
Inflect
Overrides the inflection color:value pairs that are stored in the grid (.MIG) file.
Nodes
Turns the display of nodes on or off.
The following statement turns on the display of arrows, centroids, and nodes for layer 1:
Set Map
Layer 1 Arrows On Centroids On Nodes On
Display
This clause controls how the objects in the layer are displayed.
When you specify Display Off, the layer does not appear in the Map.
When you specify Display Graphic, the layer’s objects appear in their default style, as saved in
the table.
When you specify Display Global, all objects appear in the global styles assigned to the layer.
These global styles can be assigned through the optional Global sub-clauses:
The Global Line clause specifies the style used to display line and polyline objects. A Line
clause is identical to a Pen clause, except for the use of the keyword Line instead of Pen.
The Global Pen clause specifies the style used to display the borders of filled objects.
The Global Brush clause specifies the style used to display filled objects.
The Global Symbol clause specifies the style used to display point objects.
The Global Font clause specifies the font used to display text objects.
The following statement displays layer 1 in its default style:
Set Map
Layer 1 Display Graphic
The following statement displays layer 1 with green line and fill styles:
Set Map
Layer 1 Display Global
Global Line(1, 2, GREEN)
Global Pen (1, 2, GREEN)
Global Brush (2, GREEN, WHITE)
Changing Labeling Options for Individual Layers
The Label clause controls a map layer’s labeling options. The Label clause has the following
sub-clauses:
Line
Sets the type of call-out line, if any, that should appear when a label is dragged from its original
location. You can specify Line Simple, Line Arrow, or Line None. For example:
Set Map Layer 1
Label Line Arrow
Position
Controls label positions with respect to the positions of object centroids. For example, the
following statement sets labels above and to the right of object centroids.
Set Map Layer 1
Label Position Above Right
Font
Specifies the font used in labels.
Pen
Specifies the line style to use for call-out lines. Call-out lines only appear if you specify Line
Simple or Line Arrow, and if the user drags a label from its original location.
Set Map Layer 1
Label Line Arrow
Pen( 2, 1, 255)
With
Specifies the expression used to construct the text for the labels. For example, the following
statement specifies a labeling expression which uses the Proper$( ) function to control
capitalization in the label.
Set Map Layer 1
Label With Proper$(Cityname)
Parallel
Controls whether labels for line objects are rotated, so that the labels are parallel to the lines.
Set Map Layer 1
Label Parallel On
Visibility
Controls whether labels are visible for this layer. Specify Visibility Off to turn off label display
for both default labels and user-edited labels. Specify Visibility Zoom ... to set the labels to
display only when the map is within a certain zoom distance. The following example sets labels
to display when the map is zoomed to 2 km or less.
Set Map Layer 1
Label Visibility Zoom (0, 2) Units ”km”
Auto
Controls whether automatic labels display. If you specify Auto Off, automatic labels will not
display, although user-edited labels will still display.
Overlap
Controls whether MI Pro draws labels that would overlap existing labels. To prevent
overlapping labels, specify Overlap Off.
PartialSegments
Controls whether MI Pro labels an object when the object's centroid is not in the visible portion
of the map. If you specify PartialSegments On (which corresponds to selecting the Label
Partial Objects check box in MI Pro), MapInfo Professional labels the visible portion of the
object. If you specify PartialSegments Off, an object will only be labeled if its centroid appears
in the Map window. In version 7.0, this feature has been expanded to all object types. For
versions previous to 7.0, only linear objects where affected.
Duplicates
Controls whether MI Pro allows two or more labels that have the same text. To prevent
duplicate labels, specify Duplicates Off.
Max number_of_labels
Sets the maximum number of labels that MI Pro will display for this layer. If you omit the
number_of_labels argument, MI Pro does not place any limit on the number of labels.
Offset offset_amount
Specifies an offset distance, so that MI Pro automatically places each label away from the
object’s centroid. The offset_amount argument is an integer from zero to 50, representing a
distance in points. If you specify Offset 0 labels appear immediately adjacent to centroids. If
you specify Offset 10 labels appear 10 points away. The offset setting is ignored when the
Position clause specifies centered text.
The following statement allows overlapping labels, placed to the right of object centroids, with
a horizontal offset of 10 points:
Set Map Layer 1
Label Overlap On Position Right Offset 10
Default
Resets all of the labels for this layer to their default values. The following statement deletes all
edited labels from the top layer in the Map window, restoring the layer’s default labels:
Set Map Layer 1 Label Default
Object
The Object clause allows you to edit labels. For example, if you edit labels in MI Pro and then
save a workspace, the workspace contains Object clauses to represent the edited labels. The Set
Map statement contains one Object clause for each edited label.
To see examples of the Object clause, edit a map’s labels, save a workspace, and examine the
workspace in a text editor.
Settings That Have a Permanent Effect on a Map Layer
The Default Zoom clause is a special clause that modifies a table, rather than a Map window.
Use the Default Zoom clause to reset a table’s default zoom distance and center position
settings to the window’s current zoom and center point.
Every mappable table has a default zoom distance and center position. When the user first
opens a Map window, MI Pro sets the window’s initial zoom distance and center position
according to the zoom and center settings stored in the table.
If a Set Map...Layer statement includes the Default Zoom clause, MI Pro stores the Map
window’s current zoom distance and center point in the named table. For example, the
following statement stores the Map window’s zoom and center settings in the table that
comprises the first map layer:
Set Map Layer 1 Default Zoom
The Default Zoom clause takes effect immediately; no Save operation is required.
Setting Move Duplicate Nodes
Once Set Map Move Nodes value has been used, that map has a custom setting. If a Map
window has a custom setting, the Map window preference will not be used. The Map window
preference will apply to new Map windows and any non-customized Map windows. The
setting for an existing Map window can be customized by using the Set Map Move Nodes
value MapBasic statement.
Example
The following program opens two tables, opens a Map window to show both tables, and then
performs a Set Map statement to make changes to the Map window:
Open Table ”world”
Open Table ”cust1993” As customers
Map From customers, world
Set Map
Center (100, 40) ’center map over mid-USA
Zoom 4000 Units ”mi” ’show entire USA
Preserve Zoom ’preserve zoom when resizing
Display Position ’show lat/long on status bar
Layer 1
Editable On
Layer 2
Selectable Off
Display Global
Global Brush (2, 255, 65535)
See Also
Add Map, LayerInfo( ), Map, MapperInfo( ), Remove Map, Set Window
of the grid x,y dimension. If the grid is 200x200 then the resolution values will be clamped to a
maximum of 200x200. You can’t increase the grid resolution, only specify a subsample value.
Units specifies the units the grid values are in. Do not specify this for unitless grids (i.e. grids
generated using temperature or density). This option needs to be specified at creation time. If
there are units associated with your grid values, they have to specified when you create the
3Dmap. You cannot change them later with Set Map3D or the Properties dialog.
Refresh regenerates the texture from the original tables.
Example
Dim win3D as Integer
Create Map3D Resolution(75,75) Resolution(100,100) Scale 2 Background
RGB(255,0,0)
win3D = FrontWindow()
Set Map3D Window win3D Resolution(150,100) Scale 0.75 Background
RGB(255,255,0)
Changes the original 3DMap window’s resolution in the X and Y, the
scale to de-emphasize the grid in the Z direction (< 1) and change the
background color to yellow.
See Also
Create Map3D statement, Map3DInfo function
This statement reparents document windows. To reparent dialog box windows, use the Set
Application Window statement. To reparent special windows such as the Info window, use the
Set Window statement.
Example
The sample program Legends.mb uses the following statements to create a Theme Legend
window inside of a Map window.
Dim win As Integer
win = FrontWindow()
...
Set Next Document
Parent WindowInfo(win, WIN_INFO_WND)
Style 1
Create Legend From Window win
See Also
Set Application Window, Set Window
See Also
Set Area Units, Set Distance Units
Example
Changes the original PrismMap window's resolution in the X and Y, the scale to de-emphasize
the grid in the Z direction (< 1) and change the background color to yellow.
Dim win3D as Integer
Create PrismMap Resolution(75,75) Resolution(100,100) Scale 2
Background RGB(255,0,0)
win3D = FrontWindow()
Set PrismMap Window win3D Resolution(150,100) Scale 0.75 Background
RGB(255,255,0)
See Also
Create PrismMap, PrismMapInfo()
Examples
Once a redistricting session is in effect, the following statement creates a new district.
Set Redistricter Districts
Add ”NorthWest” Brush MakeBrush(2, 255, 0)
The following statement renames the “NE” district to “NorthEast.” Note that this type of
change can affect the table that is being redistricted. Initially, any rows belonging to the “NE”
district have “NE” stored in the district column. After the Set Redistricter... Change statement,
each of those rows has “NorthEast” stored in that column.
Set Redistricter Districts
Change ”NE” To ”NorthEast”
The following statement removes the “NorthWest” district from the Districts table:
Set Redistricter Districts
Remove ”NorthWest”
The following statement sets the ordering of rows in the Districts Browser, so that the most
recently used districts appear at the top:
Set Redistricter Districts
Order ”MRU”
See Also
Create Redistricter
Example of Pen:
In this example, the line pen and the border pen are red.
Include "mapbasic.def"
Set Style Pen MakePen(3, 9, RED)
See Also
CurrentBrush( ), CurrentFont( ), CurrentPen( ), CurrentSymbol( ), MakeBrush( ),
MakeFont( ), MakePen( ), MakeSymbol( ), RGB( ), LinePen( ), BorderPen( )
Example Effect
UserMap Off Table will not appear in the New Map Window or Add Layer
dialog boxes.
UserBrowse Off Table will not appear in the New Browser Window dialog box.
UserClose Off Table will not appear in the Close Table dialog.
UserEdit Off Table will not be editable through the user interface: Browser and
Info windows are not editable, and the map layer cannot be
made editable.
UserRemoveMap Off If this table appears in a Map window, the Remove button (in the
Layer Control dialog box) is disabled for this table.
UserDisplayMap Off If this table appears in a Map window, the Display check box (in
the Layer Control dialog box) is disabled for this table.
Example
The following statement prevents the World table from appearing in the Close Table dialog.
Set Table World UserClose Off
See Also
TableInfo( )
Transparency Raster determines how transparent pixels should be rendered. Select Device or
ROP dependent upon your printer driver or export file format. You may need to determine
your selection after trying each and determining which option produces the best output for
you.
Transparency Raster ROP corresponds to the "Use ROP Method to Display Transparent
Raster" option in the MapInfo Professional user interface (Preferences > Output, File > Print >
Advanced button, and File > Save Window As > Advanced button). If ROP is selected, the
transparent image is rendered using a raster operation (ROP) to handle the transparent pixels.
This method is used to draw transparent (non-translucent) images onscreen; however, it does
not always work well when printing. You will need to experiment to determine if your printer
driver handles ROP correctly. If you are exporting an image using the Save Window As
command, this option is beneficial if the output format is a metafile (EMF or WMF). Using the
ROP method allows any underlying data to be rendered in the original form. For example,
vector data that is under transparent pixels will not be rasterized. In metafiles, the ROP method
will not draw any data in the areas of the raster pixels and allow the background
Transparency Raster Device prevents MapInfo Professional from performing any special
handling when printing raster or grid images that contain transparency. The image will be
generated using the same method that is used to display the image(s) on screen, but there may
be some problems with the output.
Transparency Vector Internal causes MapInfo Professional to perform special handling when
outputting transparent fill patterns or transparent bitmap symbols.
Transparency Vector Device prevents MapInfo Professional performing special handling when
outputting transparent fill patterns or transparent bitmap symbols. This may cause problems
with the output.
Margins User can set printer margins as floating point values in desired units. These values
may be increased by the printer driver if the printer margins are smaller than physically
possible on a particular printer.
Description
The Set Window statement customizes an open window, setting such options as the window’s
size, position, status, font or title.
The window_id parameter can be an Integer window identifier, which you can obtain by calling
the FrontWindow( ) and WindowId( ) functions. Alternately, when you use the Set Window
statement to affect a special MI Pro window, such as the Statistics window, you can identify the
window by its name (e.g., Statistics) or by its code (e.g., WIN_STATISTICS); codes are defined
in MAPBASIC.DEF.
The table below lists the window names and window codes which you can use as the
window_id parameter.
Help The Help window. You can also refer to this window by the
Define code: WIN_HELP.
Statistics The Statistics window. You can also refer to this window by the
Define code: WIN_STATISTICS.
Legend The Theme Legend window. You can also refer to this window by
the Define code: WIN_LEGEND.
Info The Info tool window (which appears when the user uses the Info
tool). You also can refer to this window by the Define code:
WIN_INFO.
Ruler The window displayed when the user uses the Ruler tool. You can
also refer to this window by the Define code: WIN_RULER.
Message The Message window (which appears when you issue a Print
statement). You can also refer to this window by the Define code:
WIN_MESSAGE.
The optional Position clause controls the window’s position in the MI Pro workspace. The
upper left corner of the workspace has the position 0, 0. The optional Width and Height clauses
control the window’s size. Window position and size values use paper units settings, such as
“in” (inches) or “cm” (centimeters). MapBasic has a current paper units setting, which defaults
to inches; a MapBasic program can change this setting through the Set Paper Units statement.
A Set Window statement can override the current paper units by including the optional Units
subclause within the Position, Width, and/or Height clauses.
If the statement includes the optional Max keyword, the window will be maximized (it will
occupy all of MI Pro’s work space). If the statement includes the optional Min keyword, the
window will be minimized (it will be reduced, appearing only as a small icon in the lower part
of the screen). If a window is already minimized or maximized, and if the statement includes
the optional Restore keyword, the window is restored to its previous size.
If the statement includes the optional Front keyword, MapBasic makes the window the active
window; this is also known as setting the focus on the window. The window comes to the front,
as if the user had clicked on the window’s title bar.
The statement may always specify a Position clause or a Front clause, regardless of the type of
window specified. However, some of the clauses in the Set Window statement apply only to
certain types of windows. For example, the Ruler Tool window may not be re-sized, maximized
or minimized.
To change the window’s title, include the optional Title clause. The Application window title
(the main “MapInfo” title bar) cannot be changed unless the user is running a runtime version
of MI Pro.
The SysMenuClose clause lets you disable the Close command in the window’s system menu
(the menu that appears when a user clicks the box in the upper-left corner of a window).
Disabling the Close command only affects the user interface; MapBasic programs can still close
the window by issuing Close Window statements. The following example disables the Close
command of the active window:
Set Window FrontWindow() SysMenuClose Off
Note: If off-screen bitmaps have been turned off, then Smart Pan in a Map window behaves
like a Layout window.
Floating Window (Legend, Ruler, etc.) Syntax
The Parent clause allows you to specify a new parent window for a Legend, Statistics, Info,
Ruler, or Message window; this clause is only supported on Windows. The window specified
by window_id becomes a popup window, attached to the window specified by HWND. Note:
reparenting a window in this manner changes the window’s Integer ID value. To return a
window to its original parent (MI Pro), specify zero as the HWND.
The ReadOnly / Default Access clause applies to the Info, Browser, and Legend windows. This
clause controls whether the window is read-only. If you specify ReadOnly, the window does
not allow editing. If you specify Default Access, the window reflects the read/write state of the
table it’s displaying. This works for the main legend and cartographic legends created with the
Create Legend or Create Cartographic Legend MapBasic statements.
The Table clause allows you to display a specific row in the Info window; this clause is only
valid when window_id refers to the Info window. Using the Table clause displays the Info
window, if it was not already visible.
The Show or Hide clause allows you to show or hide any window that supports show/hide
operations (e.g., the Ruler window). It can also be used in the MI Pro application window.
Controlling the Printer
By default, windows are printed using the global printer device. This is initialized to the
default Windows printer or the MI Pro preferred printer, depending on how the user has set
preferences. Using the Name clause an application, workspace, or the MapBasic window can
override the printer preferences for an individual document. Several settings for the printer
can also be controlled by using additional command clauses. Also, when the printer settings
are changed through the user interface, appropriate MapBasic commands are generated
internally. These overrides are saved with the workspace commands for the affected windows,
so they will be reapplied when the workspace is reopened. An override can be removed from a
window by running a Set Window Printer Default command.
Attribute codes, WIN_INFO_PRINTER_NAME, WIN_INFO_PRINTER_ORIENT or
WIN_INFO_PRINTER_COPIES, are also returned with WindowInfo() function.
Example
Set Window frontwindow()
Printer Name ”\\Discovery\HP 2500CP”
Orientation Portrait
Copies 10
Note: To find out the window’s printer name, start MapInfo Professional, go to File>Page
Setup. Click the Printer button. Use the printer name found in that dialog.
Controlling Snap Tolerance
You can set snap to a particular pixel tolerance for a given window, set snap back to the default
snap tolerance for a given window, or retrieve the current snap tolerance for a given window.
You can also turn snap on/off for a given window, or retrieve information about whether snap
is on/off for a window.
Snap mode settings for a particular window can be queried using new attribute parameters in
the WindowInfo() function. Snap mode and tolerance can now be set for each Map and Layout
window. These settings are saved in the workspace for each window.
Example
Dim win_id As Integer
Open Table ”world”
Map From world
win_id = FrontWindow()
Set Window win_id Width 5 Height 3
See Also
Map, Browse, Graph, Layout, Set Paper Units
Sgn( ) function
Purpose
Returns -1, 0, or 1, to indicate that a specified number is negative, zero, or positive
(respectively).
Syntax
Sgn( num_expr )
num_expr is a numeric expression
Return Value
Float (-1, 0, or 1)
Description
The Sgn( ) function returns a value of -1 if the num_expr is less than zero, a value of 0 (zero) if
num_expr is equal to zero, or a value of 1 (one) if num_expr is greater than zero.
Example
Dim x As Integer
x = Sgn(-0.5)
Shade statement
Purpose
Creates a thematic map layer and adds it to an existing Map window.
Syntax 1 (shading by ranges of values)
Shade [ Window window_id ]
{ layer_id | layer_name }
With expr
[ Ignore value_to_ignore ]
Ranges
[ Apply { Color | Size | All } ]
[ Use { Color | Size | All } [ Pen... ] [ Line... ] [ Brush... ] [ Symbol... ] ]
{ [ From Variable float_array
Style Variable style_array ] |
minimum : maximum [ Pen... ] [ Line...] [ Brush... ] [ Symbol... ]
[ , minimum : maximum [ Pen... ] [ Line...] [ Brush... ] [ Symbol... ] ... ] }
[ Default [ Pen... ] [ Line... ] [ Brush... ] [ Symbol... ] ]
Syntax 2 (shading by individual values)
Shade [ Window window_id ]
{ layer_id | layer_name }
With expr
[ Ignore value_to_ignore ]
Values const [ Pen... ] [ Line...] [ Brush... ] [ Symbol... ]
[ , const [ Pen... ] [ Line...] [ Brush... ] [ Symbol... ] ... ]
[ Vary { Color | All } ]
[ Default [ Pen... ] [ Brush... ] [ Symbol... ] ]
Syntax 3 (dot density)
Shade [ Window window_id ]
{ layer_id | layer_name }
With expr
Density dot_value : dot_size
[ Color color ]
Syntax 4 (graduated symbols)
Shade [ Window window_id ]
{ layer_id | layer_name }
With expr
Graduated min_value : symbol_size max_value : symbol_size
Symbol . . .
[ Inflect Symbol . . . ]
[ Vary Size By { “LOG” | “SQRT” | “CONST” } ]
Syntax 5 (pie charts)
Shade [ Window window_id ]
{ layer_id | layer_name | Selection }
With expr [ , expr . . . ]
[ Half ] Pie [ Angle angle ] [ Counter ]
[ Fixed ] [ Max Size chart_size [ Units unitname ]
[ At Value max_value [ Vary Size By {“LOG” | “SQRT” | “CONST” } ] ] ]
[ Border Pen . . . ]
[ Position [ { Left | Right | Center } ] [ { Above | Below | Center } ] ]
[ Style Brush . . . [ , Brush . . . ] ]
Description
The Shade statement creates a thematic map layer and adds the layer to an existing Map
window. The Shade statement corresponds to MapInfo Professional’s Map > Create Thematic
Map menu item. For an introduction to thematic mapping and the Create Thematic Map menu
item, see the MapInfo Professional documentation.
Between sessions, MI Pro preserves thematic settings by storing a Shade statement in the
workspace file. Thus, to see an example of the Shade statement, you could create a Map, choose
the Map > Create Thematic Map command, save the workspace (e.g., THEME.WOR), and
examine the workspace in a MapBasic text edit window. You could then copy the Shade
statement in your MapBasic program. Similarly, you can see examples of the Shade statement
by opening MapInfo Professional’s MapBasic Window before you choose Map > Create
Thematic Map.
The optional window_id clause identifies which Map is to be shaded; if no window_id is
provided, MapBasic shades the topmost Map window.
The Shade statement must specify which layer to shade thematically, even if the Map window
has only one layer. The layer may be identified by number (layer_id), where the topmost map
layer has a layer_id value of one, the next layer has a layer_id value of two, etc. Alternately, the
Shade statement can identify the map layer by name (e.g., “world”).
Each Shade statement must specify an expr expression clause. MI Pro evaluates this expression
for each object in the table being shaded; following the Shade statement, MI Pro chooses each
object’s display style based on that record’s expr value. The expression typically includes the
names of one or more columns from the table being shaded.
The keywords following the expr clause dictate which type of shading MI Pro will perform. The
Ranges keyword results in a shaded map where each object falls into a range of values; the
Values keyword creates a map where each unique value has its own display style; the Density
keyword creates a dot density map; the Graduated keyword results in a graduated symbols
map; and the Pie and Bar keywords specify thematically constructed charts.
Ranges of Values
In a Ranges map (Syntax 1, above), you can use the From Variable and Style Variable clauses
to read pre-calculated sets of range information from array variables. The array variables must
have been initialized using the Create Ranges and Create Styles statements. For an example of
using arrays in Shade statements, see Create Ranges.
If you specify either the Ranges or Values keyword, the statement can include the optional
Default clause. This clause lets you specify the graphic styles used by the “all others” range. If
a row does not fall into any of the specified ranges, MapInfo Professional assigns the row to the
all-others range.
If the Shade statement does not read range settings from array variables, then the Ranges
keyword is followed by from one to sixteen explicit range descriptions. Each range description
consists of a pair of numeric values (separated by a colon), followed by the graphic styles that
MI Pro should use to display objects belonging to that range. If a record’s expr value is greater
than or equal to the minimum value, and less than the maximum value, then that record
belongs to that range. The range descriptions are separated by commas.
Open Table ”states”
Map From states
Shade states With Pop_1990 Ranges
4827000:29280000 Brush (2,0,201326591) ,
0 : 300000 Symbol(35,YELLOW,9) ,
300000 : 900000 Symbol(35,GREEN,18) ,
900000 :20000000 Symbol(35,BLUE,27)
Note: The Use Size clause provides its own Symbol style: Shape 34 (circle), in red.
Because of the Use Size clause, MI Pro uses only the size values from the latter Symbol clauses
(9, 18, 27 point); MI Pro ignores the other display attributes (i.e. YELLOW, GREEN, BLUE). The
thematic map shows red circles, because the Use Size Symbol clause specifies red circles. The
end result: Points in the low range appear as 9-point, red circles; points in the medium range
appear as 18-point, red circles; points in the high range appear as 27-point, red circles.
If you specify Use Color instead of Use Size, MI Pro uses only the colors from the latter Symbol
clauses. The map will show yellow, green, and blue circles, all at 24-point size.
Specifying Use All has the same effect as leaving out the Use clause.
The Use clause is only valid if you specify Apply All (or if you omit the Apply clause entirely).
Individual Values
In a Values map (Syntax 2, above), the keyword Values is followed by from one to 255 value
descriptions. Each value description consists of a unique value (string or numeric), followed by
the graphic styles that MapInfo Professional should use to display objects having that exact
value. If a record’s expr value is exactly equal to one of the Shade statement’s value
descriptions, then that record’s object will be displayed with the appropriate graphic style. The
value descriptions are separated by commas.
If the Shade statement specifies either the Ranges or Values keyword, the statement can
include the optional Default clause. This clause lets you specify the graphic styles used by the
“all others” range. If a row does not fall into any of the specified ranges, MI Pro assigns the row
to the all-others range. The Vary clause sets how the objects will vary in appearance. The
default is Vary All. If Vary All is specified, all of the display tools for each range are applied in
the theme. If Vary Color is specified, only the color for the specified for each range is applied.
The following example assumes that the UK_Sales table has a column called Sales_Rep; this
column contains the name of the sales representative who handles the accounts for a sales
territory in the United Kingdom. The Shade statement will display each region in a shade
which depends upon that region’s salesperson. Thus, all regions assigned to Bob will appear in
one color, while all regions assigned to Jan will appear in another color, etc.
Open Table ”uk_sales”
Map From uk_sales
region has an expr value of 100, and the Shade statement specifies a dot_value of 5, then MI Pro
draws 20 dots in that region, because each dot represents a quantity of 5.
The dot_size specifies how large the dots should be, in terms of pixels. The dot_size should be
one (1) or four (4). The optional color clause is used to set the color of the dots.
The following example creates a dot density map using the States table’s Num_HH_90 column,
which indicates the number of households per state, circa 1990. The resultant dot density map
will show many 4-pixel dots; each dot representing 60,000 households.
Open Table ”states”
Map From states
The optional Counter keyword specifies that wedges are drawn in counter-clockwise order,
starting at the start angle.
The Max Size clause controls the sizes of the pie charts, in terms of paper units (e.g., “in” for
inches). If you include the Fixed keyword, all charts are the same size.
For example, the following statement produces pie charts, all of the same size:
Shade sales_95 With phone_sales, retail_sales
Pie Fixed
Max Size 0.25 Units ”in”
To vary the sizes of Pie charts, omit the Fixed keyword and include the At Value clause. For
example, the following statement produces a theme where the size of the Pie charts varies. If a
record has a sum of 85,000 its Pie chart will be 0.25 inches tall; records having smaller values are
shown as smaller Pie charts.
Shade sales_95 With phone_sales, retail_sales
Pie
Max Size 0.25 Units ”in” At Value 85000
The optional Vary Size By clause controls how MI Pro varies the Pie chart size. This clause is
discussed above (see Graduated Symbols).
Each chart is placed on the original map object’s centroid, unless a Position clause is used.
The Style clause specifies a comma-separated list of Brush styles; specify one Brush style for
each expression specified in the With clause. Brush style settings are optional; if you omit these
settings, MI Pro uses any Brush preferences saved by the user.
The following example creates a thematic map layer which positions each pie chart directly
above each map object’s centroid.
Shade sales_95 With phone_sales, retail_sales
Pie Angle 180
Max Size 0.5 Units ”in” At Value 85000
Vary Size By ”SQRT”
Border Pen (1, 2, 0)
Position Center Above
Style Brush(2, RED, 0), Brush(2, BLUE, 0)
Bar Chart Maps
In a Bar map (Syntax 6, above), MapInfo Professional creates a small bar chart for each map
object. The With clause specifies a comma-separated list of expressions to comprise each
thematic chart.
If you place the optional keyword Stacked before the keyword Bar, MI Pro draws a stacked bar
chart; otherwise, MI Pro draws bars side-by-side. If you omit the keyword Stacked, you can
include the keyword Normalized to specify that the bars have independent scales.
When you create a Stacked bar chart map, you can include the optional Fixed keyword to
specify that all bar charts in the thematic layer should appear in the same size (e.g., half an inch
tall) regardless of the numeric values for that map object. If you omit the Fixed keyword, MI
Pro sizes each object’s bar chart according to the net sum of the values in the chart.
The Frame Brush... clause specifies a fill style used for the background behind the bars.
The Position clause controls both the orientation of the bar charts (horizontal or vertical bars)
and the position of the charts relative to object centroids. If the Position clause specifies Left or
Right, the bars are horizontal, otherwise the bars are vertical.
The Style clause specifies a comma-separated list of Brush styles. Specify one Brush style for
each expression specified in the With clause.
The following example creates a thematic map layer which positions each bar chart directly
above each map object’s centroid.
Shade sales_93
With phone_sales, retail_sales
Bar
Max Size 0.4 Units ”in” At Value 1245000
Vary Size By ”CONST”
Border Pen (1, 2, 0)
Position Center Above
Style Brush(2, RED, 0), Brush(2, BLUE, 0)
See Also
Create Ranges, Create Styles, Map, Set Legend, Set Map, Set Shade
Sin( ) function
Purpose
Returns the sine of a number.
Syntax
Sin( num_expr )
num_expr is a numeric expression representing an angle in radians
Return Value
Float
Description
The Sin( ) function returns the sine of the numeric num_expr value, which represents an angle
in radians. The result returned from Sin( ) will be between one and minus one.
To convert a degree value to radians, multiply that value by DEG_2_RAD. To convert a radian
value into degrees, multiply that value by RAD_2_DEG. The codes DEG_2_RAD and
RAD_2_DEG are defined in MAPBASIC.DEF.
Example
Include ”mapbasic.def”
Dim x, y As Float
x = 30 * DEG_2_RAD
y = Sin(x)
’ y will now be equal to 0.5
’ since the sine of 30 degrees is 0.5
See Also
Acos( ), Asin( ), Atn( ), Cos( ), Tan( )
Space$( ) function
Purpose
Returns a string consisting only of spaces.
Syntax
Space$( num_expr )
num_expr is a SmallInt numeric expression
Return Value
String
Description
The Space$( ) function returns a string num_expr characters long, consisting entirely of space
characters.
If the num_expr value is less than or equal to zero, the Space$( ) function returns a null string.
Example
Dim filler As String
filler = Space$(7)
’ filler is now equal to the string ” ”
’ (7 spaces)
Note ”Hello” + filler + ”world!”
’this displays the message ”Hello world!”
See Also
String$( )
SphericalArea( ) function
Purpose
Returns the area using as calculated in a Latitude/Longitude non-projected coordinate system
using great circle based algorithms.
Syntax
SphericalArea( expr, unit_name )
expr is an object expression
unit_name is a string representing the name of an area unit (e.g., ”sq km”)
Return Value
Float
Description
The SphericalArea( ) function returns the area of the geographical object specified by obj_expr.
The function returns the area measurement in the units specified by the unit_name parameter;
for example, to obtain an area in acres, specify ”acre” as the unit_name parameter. See the Set
Area Units statement for the list of available unit names.
The SphericalArea() function will always return the area as calculated in a Latitude/Longitude
non-projected coordinate system using spherical algorithms. A value of -1 will be returned for
data that is in a NonEarth coordinate system since this data can’t be converted into a Latitude/
longitude coordinate system.
Only regions, ellipses, rectangles, and rounded rectangles have any area. By definition, the
SphericalArea( ) of a point, arc, text, line, or polyline object is zero. The SphericalArea( )
function returns approximate results when used on rounded rectangles. MapBasic calculates
the area of a rounded rectangle as if the object were a conventional rectangle.
Examples
The following example shows how the SphericalArea( ) function can calculate the area of a
single geographic object. Note that the expression tablename.obj (as in states.obj) represents
the geographical object of the current row in the specified table.
Dim f_sq_miles As Float
Open Table ”states”
Fetch First From states
f_sq_miles = Area(states.obj, ”sq mi”)
You can also use the SphericalArea( ) function within the SQL Select statement, as shown in
the following example.
Select state, SphericalArea(obj, ”sq km”)
From states Into results
See Also
CartesianArea( ), SphericalArea( )
SphericalDistance( ) function
Purpose
Returns the distance between two locations.
Syntax
SphericalDistance ( x1 , y1 , x2 , y2 , unit_name )
x1 and x2 are x-coordinates (e.g., longitude)
y1 and y2 are y-coordinates (e.g., latitude)
unit_name is a string representing the name of a distance unit (e.g., ”km”)
Return Value
Float
Description
The SphericalDistance( ) function calculates the distance between two locations.
The function returns the distance measurement in the units specified by the unit_name
parameter; for example, to obtain a distance in miles, specify ”mi” as the unit_name parameter.
See the Set Distance Units statement for the list of available unit names.
The x- and y-coordinate parameters must use MapBasic’s current coordinate system. By
default, MapInfo Professional expects coordinates to use a longitude, latitude coordinate
system. You can reset MapBasic’s coordinate system through the Set CoordSys statement.
The SphericalDistance( ) function always returns a value as calculated in a Latitude/
Longitude non-projected coordinate system using great circle based algorithms. A value of -1
will be returned for data that is in a NonEarth coordinate system since this data can’t be
converted into a Latitude/longitude coordinate system.
Example
Dim dist, start_x, start_y, end_x, end_y As Float
Open Table ”cities”
Fetch First From cities
start_x = CentroidX(cities.obj)
start_y = CentroidY(cities.obj)
Fetch Next From cities
end_x = CentroidX(cities.obj)
end_y = CentroidY(cities.obj)
dist = SphericalDistance(start_x,start_y,end_x,end_y,”mi”)
See Also
Distance( ), CartesianDistance( )
SphericalObjectLen( ) function
Purpose
Returns the geographic length of a line or polyline object.
Syntax
SphericalObjectLen( expr , unit_name )
obj_expr is an object expression
unit_name is a string representing the name of a distance unit (e.g., ”km”)
Return Value
Float
Description
The SphericalObjectLen( ) function returns the length of an object expression. Note that only
line and polyline objects have length values greater than zero; to measure the circumference of
a rectangle, ellipse, or region, use the Perimeter( ) function.
The SphericalObjectLen( ) function always returns a value as calculated in a Latitude/
Longitude non-projected coordinate system using spherical algorithms. A value of -1 will be
returned for data that is in a NonEarth coordinate system since this data can’t be converted into
a Latitude/longitude coordinate system.
The SphericalObjectLen( ) function returns a length measurement in the units specified by the
unit_name parameter; for example, to obtain a length in miles, specify ”mi” as the unit_name
parameter. See the Set Distance Units statement for the list of valid unit names.
Example
Dim geogr_length As Float
Open Table ”streets”
Fetch First From streets
geogr_length = SphericalObjectLen(streets.obj, ”mi”)
’ geogr_length now represents the length of the
’ street segment, in miles
See A
SphericalObjectLen ( ), CartesianObjectLen( )
SphericalPerimeter( ) function
Purpose
Returns the perimeter of a graphical object.
Syntax
SphericalPerimeter( obj_expr , unit_name )
obj_expr is an object expression
unit_name is a string representing the name of a distance unit (e.g., ”km”)
Return Value
Float
Description
The SphericalPerimeter( ) function calculates the perimeter of the obj_expr object. The
Perimeter( ) function is defined for the following object types: ellipses, rectangles, rounded
rectangles, and polygons. Other types of objects have perimeter measurements of zero. The
SphericalPerimeter( ) function returns a length measurement in the units specified by the
unit_name parameter; for example, to obtain a length in miles, specify ”mi” as the unit_name
parameter. See the Set Distance Units statement for the list of valid unit names.
The SphericalPerimeter( ) function always returns a value as calculated in a Latitude/
Longitude non-projected coordinate system using spherical algorithms. A value of -1 will be
returned for data that is in a NonEarth coordinate system since this data can’t be converted into
a Latitude/longitude coordinate system. The SphericalPerimeter( ) function returns
approximate results when used on rounded rectangles. MapBasic calculates the perimeter of a
rounded rectangle as if the object were a conventional rectangle.
Example
The following example shows how you can use the SphericalPerimeter( ) function to
determine the perimeter of a particular geographic object.
Dim perim As Float
Open Table ”world”
Fetch First From world
perim = SphericalPerimeter(world.obj, ”km”)
’ The variable perim now contains
’ the perimeter of the polygon that’s attached to
’ the first record in the World table.
You can also use the SphericalPerimeter( ) function within the SQL Select statement. The
following Select statement extracts information from the States table, and stores the results in a
temporary table called Results. Because the Select statement includes the
SphericalPerimeter( ) function, the Results table will include a column showing each state’s
perimeter.
Open Table ”states”
Select state, Perimeter(obj, ”mi”)
From states
Into results
See Also
CartesianPerimeter( ), Perimeter( )
Sqr( ) function
Purpose
Returns the square root of a number.
Syntax
Sqr( num_expr )
num_expr is a positive numeric expression
Return Value
Float
Description
The Sqr( ) function returns the square root of the numeric expression specified by num_expr.
Since the square root operation is undefined for negative real numbers, num_expr should
represent a value greater than or equal to zero.
Taking the square root of a number is equivalent to raising that number to the power 0.5.
Accordingly, the expression Sqr(n) is equivalent to the expression n ^ 0.5; the Sqr( ) function,
however, provides the fastest calculation of square roots.
Example
Dim n As Float
n = Sqr(25)
See Also
Cos(), Sin(), Tan()
StatusBar statement
Purpose
Displays or hides the status bar, or displays a brief message on it.
Syntax
StatusBar { Show | Hide }
[ Message message ]
[ ViewDisplayPopup { On | Off } ]
[ EditLayerPopup { On | Off } ]
message is a message to display on the status bar.
Description
Use the StatusBar statement to show or hide the status bar, or to display a brief message on the
status bar.
To print a message to the status bar, use the optional Message clause.
StatusBar Message ”Calculating coordinates...”
MapInfo Professional automatically updates the status bar as the user selects various buttons
and menu items. Therefore, a message displayed on the status bar may disappear quickly.
Therefore, you should not rely on status bar messages to display important prompts.
To display a message that does not disappear, use the Print statement to print a message to the
Message window.
Use the ViewDisplayPopup parameter to allow the user to change view from the status bar. If
this parmaeter is set to yes, the user will be able to change the zoom level, scale, and cursor
location settings from the status bar.
Use the EditLayerPopup parameter to allow the user to set the editable layer of a Map window
from the status bar. If this parameter is set to yes, the user will be able to select the editable
layer from the status bar.
Stop statement
Purpose
Suspends a running MapBasic application, for debugging purposes.
Syntax
Stop
Restrictions
You cannot issue a Stop statement from within a user-defined function or within a dialog’s
handler procedure; therefore you cannot issue a Stop statement to debug a Dialog statement
while the dialog is still on the screen.
Description
The Stop statement is a debugging aid. It suspends the application which is running, and
returns control to the user; presumably, the user in this case is a MapBasic programmer who is
debugging a program.
When the Stop occurs, a message appears in the MapBasic window identifying the program
line number of the Stop.
Following a Stop, you can use the MapBasic window to investigate the current status of the
program. If you type:
? Dim
into the MapBasic window, MapInfo Professional displays a list of the local variables in use by
the suspended program. Similarly, if you type:
? Global
into the MapBasic window, MI Pro displays a list of the global variables in use.
To display the contents of a variable, type a question mark followed by the variable name. To
modify the contents of the variable, type a statement of this form:
variable_name = new_value
where variable_name is the name of a local or global variable, and new_value is an expression
representing the new value to assign to the variable.
To resume the execution of the application, choose File > Continue; note that, while a program
is stopped, Continue appears on the File menu instead of Run. You can also restart a program
by typing a Continue statement into the MapBasic window.
During a Stop, MI Pro keeps the application file open. As long as this file remains open, the
application cannot be recompiled. If you use a Stop statement, and you then wish to recompile
your application, choose File > Continue before attempting to recompile.
Str$( ) function
Purpose
Returns a string representing an expression (e.g., a printout of a number).
Syntax
Str$( expression )
expression is a numeric, Date, Pen, Brush, Symbol, Font, Logical or Object expression
Return Value
String
Description
The Str$( ) function returns a string which represents the value of the specified expression.
If the expression is a negative number, the first character in the returned string is the minus sign
(-). If the expression is a positive number, the first character in the string is a space.
Depending on the number of digits of accuracy in the expression you specify, and depending
on how many of the digits are to the left of the decimal point, the Str$( ) function may return a
string which represents a rounded value. If you need to control the number of digits of
accuracy displayed in a string, use the Format$( ) function.
If the expression is an Object expression, the Str$( ) function returns a string, indicating the
object type: Arc, Ellipse, Frame, Line, Point, Polyline, Rectangle, Region, Rounded Rectangle,
or Text.
If the expression is an Object expression of the form tablename.obj and if the current row from
that table has no graphic object attached, Str$( ) returns a null string. Note: Passing an
uninitialized Object variable to the Str$( ) function generates an error.
If the expression is a Date, the output from Str$( ) depends on how the user’s computer is
configured. For example, the following expression:
Str$( NumberToDate(19951231) )
might return “12/31/1995” or “1995/12/31” (etc.) depending on the date formatting in use on
the user’s computer. To control how Str$( ) formats dates, use the Set Format statement.
If the expression is a number, the Str$( ) function uses a period as the decimal separator, even if
the user’s computer is set up to use another character as decimal separator. The Str$( ) function
never includes thousands separators in the return string. To produce a string that uses the
thousands separator and decimal separator specified by the user, use the FormatNumber$( )
function.
Example
Dim s_spelled_out As String, f_profits As Float
f_profits = 123456
s_spelled_out = ”Annual profits: $” + Str$(f_profits)
See Also
Format$( ), FormatNumber$( ), Set Format, Val( )
String$( ) function
Purpose
Returns a string built by repeating a specified character some number of times.
Syntax
String$( num_expr, string_expr )
num_expr is a positive integer numeric expression
string_expr is a string expression
Return Value
String
Description
The String$( ) function returns a string num_expr characters long; this result string consists of
num_expr occurrences of the first character from the string_expr string. Thus, the num_expr
expression should be a positive integer value, indicating the desired length of the result (in
characters).
Example
Dim filler As String
filler = String$(5, ”ABCDEFGH”)
’ at this point, filler contains the string ”AAAAA”
’ (5 copies of the 1st character from the string)
See Also
Space$( )
StringCompare( ) function
Purpose
Performs case-sensitive string comparisons.
Syntax
StringCompare( string1, string2 )
string1 and string2 are String expressions
Return Value
SmallInt: -1 if first string precedes second; 1 if first string follows second; zero if strings are
equal
Description
The StringCompare( ) function performs case-sensitive string comparisons. MapBasic string
comparisons which use the “=” operator are case-insensitive. Thus, a comparison expression
such as the following:
If ”ABC” = ”abc” Then
evaluates as TRUE, because string comparisons are case-insensitive.
The StringCompare( ) function performs a case-sensitive string comparison and returns an
indication of how the strings compare.
Example
The function call:
StringCompare(”ABC”, ”abc”)
returns a value of -1, since “A” precedes “a” in the set of character codes.
See Also
Like( ), StringCompareIntl( )
StringCompareIntl( ) function
Purpose
Performs language-sensitive string comparisons.
Syntax
StringCompareIntl( string1 , string2 )
string1 and string2 are the string expressions being compared
Return Value
SmallInt: -1 if first string precedes second; 1 if first string follows second; zero if strings are
equal.
Description
The StringCompareIntl( ) function performs language-sensitive string comparisons. Call this
function if you need to determine the alphabetical order of two strings, and the strings contain
characters that are outside the ordinary U.S. character set (e.g., umlauts).
The comparison uses whatever language settings are in use on the user’s computer. For
example, a Windows user can control language settings through the Control Panel.
See Also
Like( ), StringCompare( )
StringToDate( ) function
Purpose
Returns a Date value, given a String.
Syntax
StringToDate ( datestring )
datestring is a String expression representing a date
Return Value
Date
Description
The StringToDate( ) function returns a Date value, given a string that represents a date.
MapBasic interprets the date string according to the date-formatting options that are set up on
the user’s computer. Computers within the U.S. are usually configured to format dates as
Month/Day/Year, but computers in other countries are often configured with a different order
(e.g., Day/Month/Year) or a different separator character (e.g., a period instead of a /).
To force the StringToDate( ) function to apply U.S. formatting conventions, use the Set Format
statement. Note: Applications compiled with version 3.0 of the MapBasic compiler
automatically apply U.S. number- and date-formatting, even if you do not use the Set Format
statement. When U.S. formatting conventions apply, the datestring parameter must use the
forward-slash character (/) to separate the day, month, and year components of the date. in
versions preceding 3.x. If you run the appplication on version 4.0 or greater, the output is
determined by your local settings.
Note: To avoid the entire issue of how the user’s computer is set up, call NumberToDate( )
instead of StringToDate( ). The NumberToDate( ) function is not affected by how the
user’s computer is set up.
The datestring argument must indicate the month (1 - 12, represented as one or two digits) and
the day of the month (1 - 31, represented as one or two digits).
You can specify the year as a four-digit number or as a two-digit number, or you can omit the
year entirely. If you do not specify a year, MapInfo Professional uses the current year. If you
specify the year as a two-digit number(e.g., 96), MI Pro uses the current century or the century
as determined by the Set Date Window statement
Example
The following example specifies date strings with U.S. formatting: Month/Day/Year. Before
calling StringToDate( ), this program calls Set Format to guarantee that the U.S. date strings
are interpreted correctly, regardless of how the system is configured.
Dim d_start, d_end As Date
In this example, the variable Date1 = 19890120, Date2 = 20101203 and MyYear = 1990.
DIM Date1, Date2 as Date
DIM MyYear As Integer
Set Format Date ”US”
Set Date Window 75
Date1 = StringToDate(”1/20/89”)
Date2 = StringToDate(”12/3/10”)
MyYear = Year(”12/30/90”)
These results are due to the Set Date Window statement which allows you to control the
century value when given a two-digit year.
See Also
NumberToDate( ), Set Format, Str$( )
StyleAttr( ) function
Purpose
Returns one attribute of a Pen, Brush, Font, or Symbol style.
Syntax
StyleAttr( style , attribute )
style is a Pen, Brush, Font, or Symbol style value
attribute is an Integer code specifying which component of the style should be returned
Return Value
String or Integer, depending on the attribute parameter
Description
The StyleAttr( ) function returns information about a Pen, Brush, Symbol, or Font style.
Each style type consists of several components. For example, a Brush style definition consists of
three components: pattern, foreground color, and background color. When you call the
StyleAttr( ) function, the attribute parameter controls which style attribute is returned.
The attribute parameter must be one of the codes in the table below. Codes in the left column
(e.g., PEN_WIDTH) are defined in MAPBASIC.DEF.
* MapInfo 3.0 symbols refers to the symbol set that came with MapInfo for Windows 3.0 and
that has been maintained in subsequent versions of MapInfo Professional.
Error Conditions
ERR_FCN_ARG_RANGE error generated if an argument is outside of the valid range.
Example
The following example uses the CurrentPen( ) function to determine the pen style currently in
use by MapInfo Professional, then uses the StyleAttr( ) function to determine the thickness of
the pen, in pixels.
Include ”mapbasic.def”
Dim cur_width As Integer
cur_width = StyleAttr(CurrentPen(), PEN_WIDTH)
See Also
MakePen( ), MakeBrush( ), MakeFont( ), MakeSymbol( ), Pen( ), Brush( ), Font( ), Symbol( )
Sub Main
Dim x, result As Float
Call Cube(2, result)
’ result now contains the value: 8 (2 x 2 x 2)
x = 1
Call Cube(x + 2, result)
’ result now contains the value: 27 (3 x 3 x 3)
End Sub
Symbol clause
Purpose
Specifies a symbol style for point objects.
Syntax 1 (MapInfo 3.0 Symbol Syntax)
Symbol ( shape, color, size )
shape is an Integer, 31 or larger, specifying which character to use from MapInfo Professional’s
standard symbol set. To create an invisible symbol, use 31; see table below. The standard set of
symbols includes symbols 31 through 67, but the user can customize the symbol set by using
the Symbol application.
Note: MapInfo 3.0 symbols refers to the symbol set that came with MapInfo for Windows 3.0
and that has been maintained in subsequent versions of MapInfo Professional.
color is an Integer RGB color value; see the RGB( ) function.
size is an Integer point size, from 1 to 48.
Syntax 2 (TrueType Font Syntax)
Symbol ( shape, color, size, fontname, fontstyle, rotation )
shape is an Integer, 31 or larger, specifying which character to use from a TrueType font. To
create an invisible symbol, use 31.
color is an Integer RGB color value; see the RGB( ) function.
size is an Integer point size, from 1 to 48.
fontname is a string representing a TrueType font name (e.g., “WingDings”).
fontstyle is an Integer code controlling attributes such as bold; see table below.
rotation is a floating-point number representing a rotation angle, in degrees.
Syntax 3 (Custom Bitmap File Syntax)
Symbol ( filename, color, size, customstyle )
filename is a string up to 31 characters long, representing the name of a bitmap file. The file
must be in the CustSymb directory.
color is an Integer RGB color value; see the RGB( ) function.
size is an Integer point size, from 1 to 48.
customstyle is an Integer code controlling color and background attributes. See table below.
Syntax 4
Symbol symbol_expr
symbol_expr is a Symbol expression, which can either be the name of a Symbol variable, or a
function call that returns a Symbol value, e.g., MakeSymbol( shape, color, size).
Description
Note: The Symbol clause specifies the settings that dictate the appearance of a point object.
Note that Symbol is a clause, not a complete MapBasic statement. Various object-related
statements, such as Create Point, allow you to specify a Symbol clause; this lets you
specify the symbol style of the new object.
Some MapBasic statements (e.g., Alter Object...Info OBJ_INFO_SYMBOL) take a Symbol
expression as a parameter (e.g., the name of a Symbol variable), rather than a full Symbol
clause (the keyword Symbol followed by the name of a Symbol variable).
Set Map
Layer 1 Display Global
Global Symbol MakeSymbol(34,RED,18)
See Also
MakeFontSymbol( ), MakeCustomSymbol( ), MakeSymbol( ), StyleAttr( )
SystemInfo( ) function
Purpose
Returns information about the operating system or software version.
Syntax
SystemInfo( attribute )
attribute is an Integer code indicating which system attribute to query
Return Value
SmallInt, Logical, or String
Description
The SystemInfo( ) function returns information about MapInfo Professional’s system status.
The attribute can be any of the codes listed in the table below. The codes are defined in
MAPBASIC.DEF.
Error Conditions
ERR_FCN_ARG_RANGE error generated if an argument is outside of the valid range
Example
The following example uses the SystemInfo( ) function to determine what type of MapInfo
software is running. The program only calls a DDE-related procedure if the program is running
some version of MapInfo Professional.
Declare Sub DDE_Setup
TableInfo( ) function
Purpose
Returns information about an open table.
Syntax
TableInfo( table_id , attribute )
table_id is a String representing a table name, a positive Integer table number, or 0 (zero)
attribute is an Integer code indicating which aspect of the table to return
Return Value
String, SmallInt, or Logical, depending on the attribute parameter specified
Description
The TableInfo( ) function returns one piece of information about an open table.
The table_id can be a String representing the name of the open table. Alternately, table_id can be
a table number. If table_id is 0 (zero), the TableInfo( ) function returns information about the
most recently opened, most recently created table; or a table that has just been renmed. This
allows a MapBasic program to determine the working name of a table in cases where the Open
Table statement did not include an As clause. If there are no open tables, or if the most recently-
opened table has already been closed, the TableInfo( ) function generates an error.
The attribute parameter can be any value from the table below. Codes in the left column (e.g.,
TAB_INFO_NAME) are defined in MAPBASIC.DEF.
Error Conditions
ERR_TABLE_NOT_FOUND error generated if the specified table was not available
ERR_FCN_ARG_RANGE error generated if an argument is outside of the valid range
Example
Include ”mapbasic.def”
Dim i_numcols As SmallInt, L_mappable As Logical
Open Table ”world”
i_numcols = TableInfo(”world”, TAB_INFO_NCOLS)
L_mappable = TableInfo(”world”, TAB_INFO_MAPPABLE)
See Also
Open Table
Tan( ) function
Purpose
Returns the tangent of a number.
Syntax
Tan( num_expr )
num_expr is a numeric expression representing an angle in radians
Return Value
Float
Description
The Tan( ) function returns the tangent of the numeric num_expr value, which represents an
angle in radians.
To convert a degree value to radians, multiply that value by DEG_2_RAD. To convert a radian
value into degrees, multiply that value by RAD_2_DEG. (Note that your program will need to
Include “MAPBASIC.DEF” in order to reference DEG_2_RAD or RAD_2_DEG).
Example
Include ”mapbasic.def”
Dim x, y As Float
x = 45 * DEG_2_RAD
y = Tan(x)
’ y will now be equal to 1,
’ since the tangent of 45 degrees is 1
See Also
Acos( ), Asin( ), Atn( ), Cos( ), Sin( )
TempFileName$( ) function
Purpose
Returns a name that can be used when creating a temporary file.
Syntax
TempFileName$( dir )
dir is the string that specifies the directory that will store the file; “” specifies the system
temporary storage directory.
Return Value
Returns a string that specifies a unique file name, including its path.
Description
Use the TempFileName$( ) function when you need to create a temporary file, but you do not
know what file name to use.
When you call TempFileName$( ), MapBasic returns a string representing a file name. The
TempFileName$( ) function does not actually create the file. To create the file, issue an Open
File statement.
If the dir parameter is an empty string (“”), the returned file name will represent a file in the
system’s temporary storage directory, such as “G:\TEMP\~MAP0023.TMP”.
In a networked environment, it is possible that two users could attempt to create the same file
at the same time. If you try to create a file using a filename returned by TempFileName$( ), and
an error occurs because that file already exists, it is likely that another network user created the
file moments after your program called TempFileName$( ). To reduce the likelihood of such
file conflicts, issue the Open File statement immediately after calling TempFileName$( ). To
eliminate all chances of file sharing conflicts, create an error handler, and enable the error
handler (by issuing an OnError statement) before issuing the Open File statement.
See Also
FileExists( )
TextSize( ) function
Purpose
Returns the point size of a text object in a window.
Syntax
TextSize( window_id , text_obj )
window_id is the Integer window identifier of a Map or Layout window. Call FrontWindow( )
or WindowID( ) to obtain window identifiers.
text_obj is a text object.
Note: If the text object is from a Map window, the window ID must be the ID of a Map
window. If the text object is from a Layout, the window ID must be the ID of a Layout
window.
Return Value
Float
Description
The TextSize() function will return the point size of a text object in a window at its current
zoom level. This function correlates to selecting a text object and selecting Edit>Get Info or
pressing F7.
Example
If the active window is a map and a text object is selected:
print TextSize(FrontWindow(), selection.obj)
See Also
Font
Time( ) Function
Purpose
The time function returns the current system time in string format. The time may be returned in
12- or 24-hour time format.
Syntax
StringVar = Time ( Format )
Description
StringVar is a string variable which will be given the system time in HH:MM:SS format.
Format is an integer value indicating the format of the string to return. The time will be
returned in 24-hour format if Format is 24. Any other value will return the time in 12-hour
format.
Timer( ) function
Purpose
Returns the number of elapsed seconds.
Syntax
Timer( )
Return Value
Integer
Description
The Timer( ) function returns the number of seconds that have elapsed since Midnight, January
1, 1970. By calling the Timer( ) function before and after a particular operation, you can time
how long the operation took (in seconds).
Example
Declare Sub Ubi
start = Timer()
Call Ubi
elapsed = Timer() - start
’
’ elapsed now contains the number of seconds
’ that it took to execute the procedure Ubi
’
ToolHandler procedure
Purpose
A reserved procedure name; works in conjunction with a special ToolButton (the MapBasic
tool).
Syntax
Declare Sub ToolHandler
Sub ToolHandler
statement_list
End Sub
statement_list is a list of statements to execute when the user clicks with the MapBasic tool
Description
ToolHandler is a special-purpose MapBasic procedure name, which operates in conjunction
with the MapBasic tool.
Defining a ToolHandler procedure is a simple way to add a custom button to MapInfo
Professional’s Main ButtonPad. However, the button associated with a ToolHandler procedure
is restricted; you cannot use custom icons or drawing modes with the ToolHandler’s button. To
create a custom button which has no restrictions, use the Alter ButtonPad and Create
ButtonPad statements.
If the user runs an application which contains a procedure named ToolHandler, a plus-shaped
tool (the MapBasic tool) appears on the Main ButtonPad. The MapBasic tool is enabled
whenever a Browser, Map, or Layout window is the active window. If the user selects the
MapBasic tool and clicks in the Browser, Map, or Layout window, MapBasic automatically calls
the ToolHandler procedure.
A ToolHandler procedure can use the CommandInfo( ) function to determine where the user
clicked. If the user clicked in a Browser, CommandInfo( ) returns the row and column where
the user clicked. If the user clicked in a Map, CommandInfo( ) returns the map coordinates of
the location where the user clicked; these coordinates are in MapBasic’s current coordinate
system (see the Set CoordSys statement).
If the user clicked in a Layout window, CommandInfo( ) returns the layout coordinates (e.g.,
distance from the upper left corner of the page) where the user clicked; these coordinates are in
MapBasic’s current paper units (see the Set Paper Units statement).
By calling CommandInfo( ), you can also detect whether the user held down the shift key and/
or the Control key while clicking. This allows you to write applications which react differently
to click events than to shift-click events.
To make the MapBasic tool the active tool, issue the statement:
Run Menu Command M_TOOLS_MAPBASIC
For a ToolHandler procedure to take effect, the user must run the application. If an application
contains a special procedure name - such as ToolHandler - the application “goes to sleep”
when the Main procedure runs out of statements to execute.
The Main procedure may be explicit or implied. The application is said to be “sleeping”
because the ToolHandler procedure is still in memory, although it may be inactive. If the user
selects the MapBasic tool and clicks with it, MapBasic automatically calls the ToolHandler
procedure, so that the procedure may react to the click event.
When any procedure in an application executes the End Program statement, the application is
completely removed from memory. In other words, a program which executes an End Program
statement is no longer sleeping - it is terminated altogether. Thus, you can use the End Program
statement to terminate a ToolHandler procedure once it is no longer wanted. Conversely, you
should be careful not to issue an End Program statement while the ToolHandler procedure is
still needed.
Depending on the circumstances, a ToolHandler procedure may need to issue a Set CoordSys
statement before determining the coordinates of where the user clicked. If the ToolHandler
procedure is called because the user clicked in a Browser, no Set CoordSys statement is
necessary.
If the user clicks in a Layout window, the ToolHandler procedure may need to issue a Set
CoordSys Layout statement before determining where the user clicked in the layout. If the user
clicks in a Map window, and the application’s current coordinate system does not match the
coordinate system of the Map (because the application has issued a Set CoordSys statement),
the ToolHandler procedure may need to issue a Set CoordSys statement before determining
where the user clicked in the map.
Example
The following program sets up a ToolHandler procedure that will be called if the user selects
the MapBasic tool, then clicks on a Map, Browser, or Layout window. In this example, the
ToolHandler simply displays the location where the user clicked.
Include ”mapbasic.def”
Declare Sub ToolHandler
Note ”Ready to test the MapBasic tool.”
Sub ToolHandler
Note ”x:” + Round(CommandInfo(CMD_INFO_X), 0.1) + Chr$(10) +
” y:” + Round(CommandInfo(CMD_INFO_Y), 0.1)
End Sub
See Also
CommandInfo( )
TriggerControl( ) function
Purpose
Returns the ID of the last dialog control chosen by the user.
Syntax
TriggerControl( )
Return Value
Integer
Description
Within a Dialog statement’s handler procedure, the TriggerControl( ) function returns the
control ID of the last control which the user operated.
Each control in a Dialog can have its own dedicated handler procedure; alternately, one
procedure can act as the handler for two or more controls. A procedure which handles multiple
controls can use the TriggerControl( ) function to detect which control the user clicked.
Error Conditions
ERR_INVALID_TRIG_CONTROL error generated if the TriggerControl( ) function is called
when no dialog is active
See Also
Alter Control, Dialog, Dialog Preserve, Dialog Remove, ReadControlValue( )
TrueFileName$( ) function
Purpose
Returns a full file specification, given a partial specification.
Syntax
TrueFileName$( file_spec )
file_spec is a String representing a partial file specification (e.g., “C:parcels.tab”)
Description
This function returns a full file specification (including full drive name and full directory
name), given a partial specification.
In some circumstances, you may need to process a partial file specification. For example, on a
DOS system, the following file specification is partial (it includes a drive letter, C:, but it omits
the current directory name):
”C:parcels.tab”
If the current directory on drive C: is “\mapinfo\data” then the following function call:
TrueFileName$(”C:parcels.tab”)
returns the string:
”C:\mapinfo\data\parcels.tab”
If your application prompts the user to type in the name of a hard drive or file path, you may
want to use TrueFileName$( ) to expand the path entered by the user into a full path.
The TrueFileName$( ) function does not verify the existence of the named file; it merely
expands the partial drive letter and directory path. To determine whether a file exists, use the
FileExists( ) function.
See Also
ProgramDirectory$( )
Type statement
Purpose
Defines a custom variable type which can be used in later Dim and Global statements.
Syntax
Type type_name
element_name As var_type
[ ... ]
End Type
type name is the name you define for the data type
element_name is the name you define for each element of the type
var_type is the data type of that element
Restrictions
Any Type statements must appear at the “global” level in a program file (i.e. outside of any sub
procedure). You cannot issue a Type statement through the MapBasic window. You cannot pass
a Type variable as a by-value parameter to a procedure or function. You cannot write a Type
variable to a file using a Put statement.
Description
The Type statement creates a new data type composed of elements of existing data types. You
can address each element of a variable of a custom type using an expression structured as
variable_name.element_name. A Type can contain elements of other custom types.and elements
which are arrays. You can also declare arrays of variables of a custom Type. You cannot copy
the entire contents of a Type variable to another Type variable using an assignment of the form
var_name = var_name.
Example
Type Person
fullname As String
age As Integer
dateofbirth As Date
End Type
UBound( ) function
Purpose
Returns the current size of an array.
Syntax
UBound( array )
array is the name of an array variable
Return Value
Integer
Description
The UBound( ) function returns an integer value indicating the current size (or “upper bound”)
of an array variable.
Every array variable has an initial size, which can be zero or larger. This initial size is specified
in the variable’s Dim or Global statement. However, an array’s size can be reset through the
ReDim statement. The UBound() function returns an array’s current size, as an Integer value
indicating how many elements can currently be stored in the array.
A MapBasic array can have up to 32,767 items.
Example
Dim matrix(10) As Float
Dim depth As Integer
depth = UBound(matrix)
’ depth now has a value of 10
ReDim matrix(20)
depth = UBound(matrix)
’ depth now has a value of 20
See Also
Dim, Global, ReDim
UCase$( ) function
Purpose
Returns a string, converted to upper-case.
Syntax
UCase$( string_expr )
string_expr is a string expression
Return Value
String
Description
The UCase$( ) function returns the string which is the upper-case equivalent of the string
expression string_expr.
Conversion from lower to upper case only affects alphabetic characters (A through Z); numeric
digits and punctuation marks are not affected. Thus, the function call:
UCase$(”A#12a”)
returns the string value “A#12A”.
Example
Dim regular, upper_case As String
UnDim statement
Purpose
Undefines a variable.
Syntax
UnDim variable_name
variable_name is the name of a variable that was declared through the MapBasic window or
through a workspace.
Restrictions
The UnDim statement cannot be used in a compiled MapBasic program; it may only be used
within a workspace or entered through the MapBasic window.
Description
After you use the Dim statement to create a variable, you can use the UnDim statement to
destroy that variable definition. For example, suppose you type a Dim statement into the
MapBasic window to declare the variable X:
Dim X As Integer
Now suppose you want to redefine X to be a Float. The following statements redefine X:
UnDim X
Dim X As Float
See Also
Dim, ReDim
UnitAbbr$( ) function
Purpose
Returns a string representing the abbreviated version of a standard MapInfo Professional unit
name.
Syntax
UnitAbbr$ ( unit_name )
unit_name is a String representing a standard MI Pro unit name (e.g., “km”)
Return Value
String expression, representing an abbreviated unit name (e.g., “km”)
Description
The unit_name parameter must be one of MI Pro’s standard, English-language unit names,
such as “km” (for kilometers) or “sq km” (for square kilometers).
The UnitAbbr$( ) function returns an abbreviated version of the unit name. The exact string
returned depends on whether the user is running the English-language version of MI Pro or a
translated version. For example, if a user is running the German-language version of MI Pro,
the following function call returns the German translation of “sq km”:
UnitAbbr$(”sq km”)
For a listing of MI Pro’s standard distance unit names (e.g., “km”), see the Set Distance Units
statement. For a listing of area unit names (e.g., “sq km”), see the Set Area Units statement. For
a listing of paper unit names (e.g., “in” for inches on a page layout), see the Set Paper Units
statement.
The unit_name parameter can also be “degree” (in which case, UnitAbbr$( ) returns “deg”).
See Also
Set Area Units, Set Distance Units, Set Paper Units, UnitName$( )
UnitName$( ) function
Purpose
Returns a string representing the full version of a standard MapInfo Professional unit name.
Syntax
UnitName$ ( unit_name )
unit_name is a String representing a standard MI Pro unit name (e.g., “km”)
Return Value
String expression, representing a full unit name (e.g., “kilometers”)
Description
The unit_name parameter must be one of MI Pro’s standard, English-language unit names,
such as “km” (for kilometers) or “sq km” (for square kilometers).
The UnitName$( ) function returns a string representing the full version of the unit name. The
exact string returned depends on whether the user is running the English-language version of
MI Pro or a translated version. For example, if a user is running the French-language version of
MI Pro, the following function call returns the French translation of “square kilometers”:
UnitName$(”sq km”)
For a listing of MI Pro’s standard distance unit names (e.g., “km”), see the Set Distance Units
statement. For a listing of area unit names (e.g., “sq km”), see the Set Area Units statement. For
a listing of paper unit names (e.g., “in” for inches on a page layout), see the Set Paper Units
statement.
The unit_name parameter can also be “degree” (in which case, UnitName$( ) returns
“degrees”).
See Also
Set Area Units, Set Distance Units, Set Paper Units, UnitAbbr$( )
Unlink statement
Purpose
Use the Unlink statement to unlink a table which was downloaded and linked from a remote
database with the Server Link Table statement.
Syntax
Unlink TableName
TableName is the name of an open MapInfo linked table.
Description
Unlinking a table removes the link to the remote database. This statement doesn’t work if edits
are pending (in other words, the user must first commit or rollback). All metadata associated
with the table linkage is removed. Fields that were marked non-editable are now editable. The
end product is a normal MapInfo base table.
Example
Unlink ”City_1k”
See Also
Server Link Table, Commit Table
Update statement
Purpose
Modifies one or more rows in a table.
Syntax
Update table Set column = expr [, column = expr, ...]
[ Where RowID = idnum ]
table is the name of an open table
column is the name of a column
expr is an expression to assign to a column
idnum is the number of a row in the table
Description
The Update statement modifies one or more columns in a table. By default, the Update
statement will affect all rows in the specified table. However, if the statement includes a Where
Rowid clause, only one particular row will be updated. The Set clause specifies what sort of
changes should be made to the affected row or rows.
To update the map object that is attached to a row, specify the column name Obj in the Set
clause; see example below.
Examples
In the following example, we have a table of employee data; each record states the employee’s
department and salary. Let’s say we wish to give a seven percent raise to all employees of the
marketing department currently earning less than $20,000. The example below uses a Select
statement to select the appropriate employee records, and then uses an Update statement to
modify the salary column accordingly.
Select * From employees
Where department =”marketing” And salary < 20000
Update Selection
Set salary = salary * 1.07
By using a Where RowID clause, you can tell MapBasic to only apply the Set operation to one
particular row of the table. The following example updates the salary column of the tenth
record in the employees table:
Update employees
Set salary = salary * 1.07
Where Rowid = 10
The next example stores a point object in the first row of a table:
Update sites
Set Obj = CreatePoint(x, y)
Where Rowid = 1
See Also
Insert
Val( ) function
Purpose
Returns the numeric value represented by a string.
Syntax
Val( string_expr )
string_expr is a string expression
Return Value
Float
Description
The Val( ) function returns a number based on the string_expr string expression. Val( ) ignores
any white spaces (tabs, spaces, line feeds) at the start of the string_expr string, then tries to
interpret the first character(s) as a numeric value. The Val( ) function then stops processing the
string as soon as it finds a character that is not part of the number.
If the first non-white-space character in the string is not a period, a digit, a minus sign, or an
ampersand character (&), Val( ) returns zero. (The ampersand is used in hexadecimal notation;
see example below.)
Note: If the string includes a decimal separator, it must be a period, regardless of whether the
user’s computer is set up to use some other character as the decimal separator. Also, the string
cannot contain thousands separators. To remove thousands separators from a numeric string,
call the DeformatNumber$( ) function.
Example
Dim f_num As Float
f_num = Val(”12 thousand”)
’ f_num is now equal to 12
f_num = Val(”12,345”)
’ f_num is now equal to 12
f_num = Val(”Eighteen”)
’ f_num is now equal to 0 (zero)
f_num = Val(”&H1A”)
’ f_num is now equal to 26 (which equals hexadecimal 1A)
See Also
DeformatNumber$( ), Format$( ), Set Format, Str$( )
Weekday( ) function
Purpose
Returns an integer from 1 to 7, indicating the weekday of a specified date.
Syntax
Weekday( date_expr )
date_expr is a date expression
Return Value
SmallInt value from 1 to 7, inclusive; 1 represents Sunday.
Description
The Weekday( ) function returns an integer representing the day-of-the-week component (one
to seven) of the specified date.
The Weekday( ) function only works for dates on or after January 1, in the year 100. If date_expr
specifies a date before the year 100, the Weekday( ) function returns a value of zero.
Example
If Weekday( CurDate() ) = 6 Then
’
’ then the date is a Friday
’
End If
See Also
CurDate( ), Day( ), Month( ), Year( )
While...Wend statement
Purpose
Defines a loop which executes as long as a specified condition evaluates as TRUE.
Syntax
While condition
statement_list
Wend
condition is a conditional expression which controls when the loop should stop
statement_list is the group of statements to execute with each iteration of the loop
Restrictions
You cannot issue a While...Wend statement through the MapBasic window.
Description
The While...Wend statement provides loop control. MapBasic evaluates the condition; if it is
TRUE, MapBasic will execute the statement_list (and then evaluate the condition again, etc.).
As long as the condition remains TRUE, MapBasic will repeatedly execute the statement_list.
When and if the condition becomes FALSE, MapBasic will skip the statement_list, and continue
execution with the first statement following the Wend keyword.
Note that a statement of this form:
While condition
statement_list
Wend
is functionally identical to a statement of this form:
Do While condition
statement_list
Loop
The While...Wend syntax is provided for stylistic reasons (i.e. for the sake of those
programmers who prefer the While...Wend syntax over the Do...Loop syntax).
Example
Dim psum As Float, i As Integer
Open Table ”world”
Fetch First From world
i = 1
While i <= 10
psum = psum + world.population
Fetch Next From world
i = i + 1
Wend
See Also
Do...Loop, For...Next
WinChangedHandler procedure
Purpose
A reserved procedure, called automatically when a Map window is panned or zoomed, or
whenever a map layer is added or removed.
Syntax
Declare Sub WinChangedHandler
Sub WinChangedHandler
statement_list
End Sub
statement_list is a list of statements to execute when the map is panned or zoomed
Description
WinChangedHandler is a special-purpose MapBasic procedure name. If the user runs an
application containing a procedure named WinChangedHandler, the application “goes to
sleep” when the Main procedure runs out of statements to execute. As long as the sleeping
application remains in memory, MapBasic calls WinChangedHandler whenever a Map
window’s extents are modified (e.g., the Map is scrolled, zoomed or re-sized). Within the
WinChangedHandler procedure, call CommandInfo( ) to determine the Integer window ID of
the affected window.
Multiple MapBasic applications can be “sleeping” at the same time. When a Map window
changes, MapBasic automatically calls all sleeping WinChangedHandler procedures, one after
another.
Under some circumstances, MapBasic may call a WinChangedHandler procedure as a result of
an event which did not affect the map extents. For example, drawing a new object may trigger
the WinChangedHandler procedure. To halt a sleeping application and remove it from
memory, use End Program.
Auto-scrolling Map Windows
MapInfo Professional automatically scrolls the Map window if the user clicks with the mouse
and then drags to the edge of the window. If the user auto-scrolls a Map window, MI Pro calls
WinChangedHandler after the tool action is completed or canceled.
For example, if you use MI Pro’s Ruler tool and you autoscroll the window during each
segment, MI Pro calls WinChangedHandler once, after you double-click to complete the
measurement (or after you press Esc to cancel the Ruler tool). If the user auto-scrolls while
using a custom MapBasic tool, MI Pro calls the tool’s handler procedure, and then calls
WinChangedHandler.
MI Pro will not call WinChangedHandler if the user auto-scrolls but then returns to the original
location before completing the operation or pressing Esc.
To disable the autoscroll feature, use the Set Window statement.
Example
For an example of using a WinChangedHandler procedure, see the OverView sample program.
See Also
CommandInfo( ), WinClosedHandler
WinClosedHandler procedure
Purpose
A reserved procedure, called automatically when a Map, Browse, Graph, Layout,
Redistricting, or MapBasic window is closed.
Syntax
Declare Sub WinClosedHandler
Sub WinClosedHandler
statement_list
End Sub
statement_list is a list of statements to execute when a window is closed
Description
WinClosedHandler is a special-purpose MapBasic sub procedure name. If the user runs an
application containing a procedure named WinClosedHandler, the application “goes to sleep”
when the Main procedure runs out of statements to execute. As long as the sleeping application
remains in memory, MapBasic automatically calls the WinClosedHandler procedure whenever
a window is closed. Within the WinClosedHandler procedure, you can use issue the function
call:
CommandInfo( CMD_INFO_WIN )
to determine the window identifier of the closed window.
Note: When any procedure in an application executes the End Program statement, the
application is completely removed from memory. Thus, you can use the End Program
statement to terminate a WinClosedHandler procedure once it is no longer wanted.
Conversely, you should be careful not to issue an End Program statement while the
WinClosedHandler procedure is still needed.
Multiple MapBasic applications can be “sleeping” at the same time. When a window is closed,
MapBasic automatically calls all sleeping WinClosedHandler procedures, one after another.
See Also
CommandInfo( ), EndHandler, RemoteMsgHandler, SelChangedHandler, ToolHandler,
WinChangedHandler
WindowID( ) function
Purpose
Returns a MapInfo Professional window identifier.
Syntax
WindowID( window_num )
window_num is a number or a numeric code; see table below
Return Value
Integer
Description
A window identifier is an Integer value which uniquely identifies an existing window. Several
MapBasic statements (e.g., Set Map) take window identifiers as parameters.
The following table lists the various ways that you can specify the window_num parameter:
Value of
Result
window_num
Positive Smallint value MI Pro returns the window ID of a document window, such as a
(1, 2, ... n ) Map or Browse window. For example, if you specify 1, MI Pro
returns the Integer ID of the first document window. Note that n
is the number of open document windows; call NumWindows( )
to determine n.
Negative Smallint MI Pro returns the window ID of a window, which may be a
value (-1,-2, ...-m) document window or a floating window such as the Info window.
Note that m is the total number of windows owned by MI Pro; call
NumAllWindows( ) to determine m. Using this syntax, you could
call WindowID( ) within a loop to build a list of the ID numbers
of all open windows.
Zero ( 0 ) MI Pro returns the window ID of the most recently opened
document window, custom legend window, or ButtonPad;
returns zero if no windows are open.
Window code (e.g., If you specify a window code with a value from 1001 to 1013, MI
WIN_RULER) Pro returns the ID of a special window. Window codes are defined
in MAPBASIC.DEF. For example, the code WIN_RULER (with a
value of 1007) represents the window used by MI Pro’s Ruler tool.
Error Conditions
ERR_BAD_WINDOW_NUM error generated if the window_num parameter is invalid
See Also
FrontWindow( ), NumWindows( )
WindowInfo( ) function
Purpose
Returns information about a window.
Syntax
WindowInfo ( window_spec , attribute )
window_spec is a number or a code that specifies which window you want to query
attribute is an Integer code indicating which information about the window to return
Return Value
Depends on the attribute parameter.
Description
The WindowInfo( ) function returns one piece of information about an existing window.
Many of the values that you pass as the parameters to WindowInfo( ) are defined in the
standard MapBasic definitions file, MAPBASIC.DEF. Your program should Include
“MAPBASIC.DEF” if you are going to call WindowInfo( ).
The following table lists the various ways that you can specify the window_spec parameter:
Value of
Description
window_spec
Integer window ID You can use an Integer window ID (which you can obtain by
calling the WindowID( ) function or the FrontWindow( )
function) to specify which window you want to query.
Positive Smallint value The function queries a document window, such as a Map or
(1, 2, ... n ) Browser window. For example, specify 1 to retrieve information
on the first document window. Note that n is the number of
open document windows; call NumWindows( ) to determine n.
Negative Smallint The function queries a window, which may be a document
value (-1,-2, ...-m) window or a floating window such as the Info window. Note
that m is the total number of windows owned by MapInfo
Professional; call NumAllWindows( ) to determine m. Using
this syntax, you could call WindowInfo( ) within a loop to
query every open window.
Zero ( 0 ) The function queries the most recently-opened window. If no
windows are open, an error occurs.
Window code (e.g., If you specify a window code with a value from 1001 to 1013,
WIN_RULER) the function queries a special system window. Window codes
are defined in MAPBASIC.DEF. For example, MAPBASIC.DEF
contains the code WIN_RULER (with a value of 1007), which
represents the window used by MapInfo Professional’s Ruler
tool.
The attribute parameter dictates which window attribute the function should return.
Theattribute parameter must be one of the codes from the table belowe
If you specify WIN_INFO_TYPE as the attribute, WindowInfo( ) returns one of these values:
WinFocusChangedHandler procedure
Purpose
A reserved procedure name, called automatically when the window focus changes.
Description
If a MapBasic application contains a sub procedure called WinFocusChangedHandler, MapInfo
Professional calls the sub procedure automatically, whenever the window focus changes. This
behavior applies to all MI Pro window types (Browsers, Maps, etc.). Within the
WinFocusChangedHandler procedure, you can obtain the Integer window ID of the current
window by calling CommandInfo(CMD_INFO_WIN).
The WinFocusChangedHandler procedure should not use the Note statement and should not
open or close any windows. These restrictions are similar to those for other handlers, such as
SelChangedHandler.
The WinFocusChangedHandler procedure should be as short as possible, to avoid slowing
system performance.
Example
The following example shows how to enable or disable a menu item, depending on whether
the active window is a Map window.
Include ”mapbasic.def”
Include ”menu.def”
Declare Sub Main
Declare sub WinFocusChangedHandler
Sub Main
’ At this point, we could create a custom menu item
’ which should only be enabled if the current window
’ is a Map window...
End Sub
Sub WinFocusChangedHandler
Dim i_win_type As SmallInt
i_win_type=WindowInfo(CommandInfo(CMD_INFO_WIN),WIN_INFO_TYPE)
Year( ) function
Purpose
Returns the year component of a date value.
Syntax
Year( date_expr )
date_expr is a date expression
Return Value
SmallInt
Description
If Set Date Window is off then the year also depends on your system clock, If your system
clock says that today is 2/2/1998, then the year function returns, 1993, if your system clock
says that today is 1/4/2004, then the year function returns 2093. MapInfo Professional uses the
current century.
Examples
The following example shows how you can use the Year( ) function to extract only the year
component of a particular date value.
If Year( CurDate() ) = 1994 Then
’ ...then it is still 1994...
End If
You can also use the Year( ) function within the SQL Select statement. The following Select
statement selects only particular rows from the Orders table. This example assumes that the
Orders table has a Date column, called OrderDate. The Select statement’s Where clause tells
MI Pro to only select the orders from December of 1993.
Open Table ”orders”
Select * From orders
Where Month(orderdate) = 12 And Year(orderdate) = 1993
See Also
CurDate( ), Day( ), Month( ), Weekday( ), DateWindow( )
The following numeric operators act on two numeric values, producing a numeric result.
Two of these operators are also used in other contexts. The plus sign acting on a pair of
strings concatenates them into a new string value. The minus sign acting on a single
number is a negation operator, producing a numeric result. The ampersand also performs
string concatenation.
The comparison operators compare two items of the same general type to produce a logical
value of TRUE or FALSE. Although you cannot directly compare numeric data with non-
numeric data (e.g., String expressions), a comparison expression can compare Integer,
Appendix B: Summary of Operators
SmallInt, and Float data types. Comparison operators are often used in conditional
expressions, such as If...Then.
The logical operators operate on logical values to produce a logical result of TRUE or
FALSE:
The geographic operators act on objects to produce a logical result of TRUE or FALSE:
Precedence
A special type of operators are parentheses, which enclose expressions within
expressions. Proper use of parentheses can alter the order of processing in an expression,
altering the default precedence. The table below identifies the precedence of MapBasic
operators. Operators which appear on a single row have equal precedence. Operators of
higher priority are processed first. Operators of the same precedence are evaluated left to
right in the expression (with the exception of exponentiation, which is evaluated right to
left).
The table below summarizes the rules that dictate MapBasic’s automatic type
conversions. Within this chart, the token Integer represents an integer value, which can be
an Integer variable, a SmallInt variable, or an Integer constant. The token Number
represents a numeric expression which is not necessarily an integer.
'====================================================================
' General Purpose defines
'====================================================================
'--------------------------------------------------------------------
' Macros
'--------------------------------------------------------------------
Define CLS Print Chr$(12)
'--------------------------------------------------------------------
' Logical constants
'--------------------------------------------------------------------
Define TRUE 1
Define FALSE 0
'--------------------------------------------------------------------
' Angle conversion
'--------------------------------------------------------------------
Define DEG_2_RAD 0.01745329252
Define RAD_2_DEG 57.29577951
'--------------------------------------------------------------------
' Colors
'--------------------------------------------------------------------
Define BLACK 0
Define WHITE 16777215
Define RED 16711680
Define GREEN 65280
Define BLUE 255
Define CYAN 65535
Define MAGENTA 16711935
'--------------------------------------------------------------------
'Maximum length for character string
'--------------------------------------------------------------------
Define MAX_STRING_LENGTH 32767
'====================================================================
' ButtonPadInfo() defines
'====================================================================
Define BTNPAD_INFO_FLOATING 1
Define BTNPAD_INFO_WIDTH 2
Define BTNPAD_INFO_NBTNS 3
Define BTNPAD_INFO_X 4
Define BTNPAD_INFO_Y 5
Define BTNPAD_INFO_WINID 6
'====================================================================
' ColumnInfo() defines
'====================================================================
Define COL_INFO_NAME 1
Define COL_INFO_NUM 2
Define COL_INFO_TYPE 3
Define COL_INFO_WIDTH 4
Define COL_INFO_DECPLACES 5
Define COL_INFO_INDEXED 6
Define COL_INFO_EDITABLE 7
'--------------------------------------------------------------------
' Column type defines, returned by ColumnInfo(<col_ref>,
COL_INFO_TYPE)
'--------------------------------------------------------------------
Define COL_TYPE_CHAR 1
Define COL_TYPE_DECIMAL 2
Define COL_TYPE_INTEGER 3
Define COL_TYPE_SMALLINT 4
Define COL_TYPE_DATE 5
Define COL_TYPE_LOGICAL 6
Define COL_TYPE_GRAPHIC 7
Define COL_TYPE_FLOAT 8
'====================================================================
' CommandInfo() defines
'====================================================================
Define CMD_INFO_X 1
Define CMD_INFO_Y 2
Define CMD_INFO_SHIFT 3
Define CMD_INFO_CTRL 4
Define CMD_INFO_X2 5
Define CMD_INFO_Y2 6
Define CMD_INFO_TOOLBTN 7
Define CMD_INFO_MENUITEM 8
Define CMD_INFO_WIN 1
Define CMD_INFO_SELTYPE 1
Define CMD_INFO_ROWID 2
Define CMD_INFO_INTERRUPT 3
Define CMD_INFO_STATUS 1
Define CMD_INFO_MSG 1000
Define CMD_INFO_DLG_OK 1
Define CMD_INFO_DLG_DBL 1
Define CMD_INFO_FIND_RC 3
Define CMD_INFO_FIND_ROWID 4
Define CMD_INFO_XCMD 1
Define CMD_INFO_CUSTOM_OBJ 1
Define CMD_INFO_TASK_SWITCH 1
Define CMD_INFO_EDIT_TABLE 1
Define CMD_INFO_EDIT_STATUS 2
Define CMD_INFO_EDIT_ASK 1
Define CMD_INFO_EDIT_SAVE 2
Define CMD_INFO_EDIT_DISCARD 3
Define CMD_INFO_HL_WINDOW_ID 17
Define CMD_INFO_HL_TABLE_NAME 18
Define CMD_INFO_HL_ROWID 19
Define CMD_INFO_HL_LAYER_ID 20
Define CMD_INFO_HL_FILE_NAME 21
'--------------------------------------------------------------------
' Task Switch, returned by CommandInfo(CMD_INFO_TASK_SWITCH)
'--------------------------------------------------------------------
Define SWITCHING_OUT_OF_MAPINFO 0
Define SWITCHING_INTO_MAPINFO 1
'====================================================================
' FileAttr() defines
'====================================================================
Define FILE_ATTR_MODE 1
Define FILE_ATTR_FILESIZE 2
'--------------------------------------------------------------------
' File Access modes, returned by FileAttr(<file_id>, FILE_ATTR_MODE)
'--------------------------------------------------------------------
Define MODE_INPUT 0
Define MODE_OUTPUT 1
Define MODE_APPEND 2
Define MODE_RANDOM 3
Define MODE_BINARY 4
'====================================================================
' IntersectNodes(obj1, obj2, mode) parameters
'====================================================================
Define INCL_CROSSINGS 1
Define INCL_COMMON 6
Define INCL_ALL 7
'====================================================================
' LayerInfo() defines
'====================================================================
Define LAYER_INFO_NAME 1
Define LAYER_INFO_EDITABLE 2
Define LAYER_INFO_SELECTABLE 3
Define LAYER_INFO_ZOOM_LAYERED 4
Define LAYER_INFO_ZOOM_MIN 5
Define LAYER_INFO_ZOOM_MAX 6
Define LAYER_INFO_COSMETIC 7
Define LAYER_INFO_PATH 8
Define LAYER_INFO_DISPLAY 9
Define LAYER_INFO_OVR_LINE 10
Define LAYER_INFO_OVR_PEN 11
Define LAYER_INFO_OVR_BRUSH 12
Define LAYER_INFO_OVR_SYMBOL 13
Define LAYER_INFO_OVR_FONT 14
Define LAYER_INFO_LBL_EXPR 15
Define LAYER_INFO_LBL_LT 16
Define LAYER_INFO_LBL_CURFONT 17
Define LAYER_INFO_LBL_FONT 18
Define LAYER_INFO_LBL_PARALLEL 19
Define LAYER_INFO_LBL_POS 20
Define LAYER_INFO_ARROWS 21
Define LAYER_INFO_NODES 22
Define LAYER_INFO_CENTROIDS 23
Define LAYER_INFO_TYPE 24
Define LAYER_INFO_LBL_VISIBILITY 25
Define LAYER_INFO_LBL_ZOOM_MIN 26
Define LAYER_INFO_LBL_ZOOM_MAX 27
Define LAYER_INFO_LBL_AUTODISPLAY 28
Define LAYER_INFO_LBL_OVERLAP 29
Define LAYER_INFO_LBL_DUPLICATES 30
Define LAYER_INFO_LBL_OFFSET 31
Define LAYER_INFO_LBL_MAX 32
Define LAYER_INFO_LBL_PARTIALSEGS 33
Define LAYER_INFO_HOTLINK_EXPR 34
Define LAYER_INFO_HOTLINK_MODE 35
Define LAYER_INFO_HOTLINK_RELATIVE 36
'--------------------------------------------------------------------
' Display Modes, returned by LayerInfo() for LAYER_INFO_DISPLAY
'--------------------------------------------------------------------
Define LAYER_INFO_DISPLAY_OFF 0
Define LAYER_INFO_DISPLAY_GRAPHIC 1
Define LAYER_INFO_DISPLAY_GLOBAL 2
Define LAYER_INFO_DISPLAY_VALUE 3
'--------------------------------------------------------------------
' Label Linetypes, returned by LayerInfo() for LAYER_INFO_LBL_LT
'--------------------------------------------------------------------
Define LAYER_INFO_LBL_LT_NONE 0
Define LAYER_INFO_LBL_LT_SIMPLE 1
Define LAYER_INFO_LBL_LT_ARROW 2
'--------------------------------------------------------------------
' Label Positions, returned by LayerInfo() for LAYER_INFO_LBL_POS
'--------------------------------------------------------------------
Define LAYER_INFO_LBL_POS_CC 0
Define LAYER_INFO_LBL_POS_TL 1
Define LAYER_INFO_LBL_POS_TC 2
Define LAYER_INFO_LBL_POS_TR 3
Define LAYER_INFO_LBL_POS_CL 4
Define LAYER_INFO_LBL_POS_CR 5
Define LAYER_INFO_LBL_POS_BL 6
Define LAYER_INFO_LBL_POS_BC 7
Define LAYER_INFO_LBL_POS_BR 8
'--------------------------------------------------------------------
' Layer Types, returned by LayerInfo() for LAYER_INFO_TYPE
'--------------------------------------------------------------------
Define LAYER_INFO_TYPE_NORMAL 0
Define LAYER_INFO_TYPE_COSMETIC 1
Define LAYER_INFO_TYPE_IMAGE 2
Define LAYER_INFO_TYPE_THEMATIC 3
Define LAYER_INFO_TYPE_GRID 4
'--------------------------------------------------------------------
' Label visibility modes, returned by LayerInfo() for
LAYER_INFO_LBL_VISIBILITY
'--------------------------------------------------------------------
Define LAYER_INFO_LBL_VIS_OFF 1
Define LAYER_INFO_LBL_VIS_ZOOM 2
Define LAYER_INFO_LBL_VIS_ON 3
'--------------------------------------------------------------------
' Hotlink activation modes, returned by LayerInfo() for
LAYER_INFO_HOTLINK_MODE
'--------------------------------------------------------------------
Define HOTLINK_MODE_LABEL 1
Define HOTLINK_MODE_OBJ 2
Define HOTLINK_MODE_BOTH 3
'====================================================================
' MapperInfo() defines
'====================================================================
Define MAPPER_INFO_ZOOM 1
Define MAPPER_INFO_SCALE 2
Define MAPPER_INFO_CENTERX 3
Define MAPPER_INFO_CENTERY 4
Define MAPPER_INFO_MINX 5
Define MAPPER_INFO_MINY 6
Define MAPPER_INFO_MAXX 7
Define MAPPER_INFO_MAXY 8
Define MAPPER_INFO_LAYERS 9
Define MAPPER_INFO_EDIT_LAYER 10
Define MAPPER_INFO_XYUNITS 11
Define MAPPER_INFO_DISTUNITS 12
Define MAPPER_INFO_AREAUNITS 13
Define MAPPER_INFO_SCROLLBARS 14
Define MAPPER_INFO_DISPLAY 15
Define MAPPER_INFO_NUM_THEMATIC 16
Define MAPPER_INFO_COORDSYS_CLAUSE 17
Define MAPPER_INFO_COORDSYS_NAME 18
Define MAPPER_INFO_MOVE_DUPLICATE_NODES 19
Define MAPPER_INFO_DIST_CALC_TYPE 20
Define MAPPER_INFO_DISPLAY_DMS 21
Define MAPPER_INFO_COORDSYS_CLAUSE_WITH_BOUNDS 22
Define MAPPER_INFO_CLIP_TYPE 23
Define MAPPER_INFO_CLIP_REGION 24
'--------------------------------------------------------------------
' Display Modes, returned by MapperInfo() for MAPPER_INFO_DISPLAY_DMS
'--------------------------------------------------------------------
Define MAPPER_INFO_DISPLAY_DECIMAL 0
Define MAPPER_INFO_DISPLAY_DEGMINSEC 1
Define MAPPER_INFO_DISPLAY_MGRS 2
'--------------------------------------------------------------------
' Display Modes, returned by MapperInfo() for MAPPER_INFO_DISPLAY
'--------------------------------------------------------------------
Define MAPPER_INFO_DISPLAY_SCALE 0
Define MAPPER_INFO_DISPLAY_ZOOM 1
Define MAPPER_INFO_DISPLAY_POSITION 2
'--------------------------------------------------------------------
' Distance Calculation Types
'--------------------------------------------------------------------
Define MAPPER_INFO_DIST_SPHERICAL 0
Define MAPPER_INFO_DIST_CARTESIAN 1
'--------------------------------------------------------------------
' Clip Types
'--------------------------------------------------------------------
Define MAPPER_INFO_CLIP_DISPLAY_ALL 0
Define MAPPER_INFO_CLIP_DISPLAY_POLYOBJ 1
Define MAPPER_INFO_CLIP_OVERLAY 2
'====================================================================
' MenuItemInfoByID() and MenuItemInfoByHandler() defines
'====================================================================
Define MENUITEM_INFO_ENABLED 1
Define MENUITEM_INFO_CHECKED 2
Define MENUITEM_INFO_CHECKABLE 3
Define MENUITEM_INFO_SHOWHIDEABLE 4
Define MENUITEM_INFO_ACCELERATOR 5
Define MENUITEM_INFO_TEXT 6
Define MENUITEM_INFO_HELPMSG 7
Define MENUITEM_INFO_HANDLER 8
Define MENUITEM_INFO_ID 9
'====================================================================
' ObjectGeography() defines
'====================================================================
Define OBJ_GEO_MINX 1
Define OBJ_GEO_LINEBEGX 1
Define OBJ_GEO_POINTX 1
Define OBJ_GEO_MINY 2
Define OBJ_GEO_LINEBEGY 2
Define OBJ_GEO_POINTY 2
Define OBJ_GEO_MAXX 3
Define OBJ_GEO_LINEENDX 3
Define OBJ_GEO_MAXY 4
Define OBJ_GEO_LINEENDY 4
Define OBJ_GEO_ARCBEGANGLE 5
Define OBJ_GEO_TEXTLINEX 5
Define OBJ_GEO_ROUNDRADIUS 5
Define OBJ_GEO_CENTROID 5
Define OBJ_GEO_ARCENDANGLE 6
Define OBJ_GEO_TEXTLINEY 6
Define OBJ_GEO_TEXTANGLE 7
'====================================================================
' ObjectInfo() defines
'====================================================================
Define OBJ_INFO_TYPE 1
Define OBJ_INFO_PEN 2
Define OBJ_INFO_SYMBOL 2
Define OBJ_INFO_TEXTFONT 2
Define OBJ_INFO_BRUSH 3
Define OBJ_INFO_NPNTS 20
Define OBJ_INFO_TEXTSTRING 3
Define OBJ_INFO_SMOOTH 4
Define OBJ_INFO_FRAMEWIN 4
Define OBJ_INFO_NPOLYGONS 21
Define OBJ_INFO_TEXTSPACING 4
Define OBJ_INFO_TEXTJUSTIFY 5
Define OBJ_INFO_FRAMETITLE 6
Define OBJ_INFO_TEXTARROW 6
Define OBJ_INFO_FILLFRAME 7
Define OBJ_INFO_REGION 8
Define OBJ_INFO_PLINE 9
Define OBJ_INFO_MPOINT 10
Define OBJ_INFO_NONEMPTY 11
'--------------------------------------------------------------------
' Object types, returned by ObjectInfo(<obj>, OBJ_INFO_TYPE)
'--------------------------------------------------------------------
Define OBJ_TYPE_ARC 1
Define OBJ_TYPE_ELLIPSE 2
Define OBJ_TYPE_LINE 3
Define OBJ_TYPE_PLINE 4
Define OBJ_TYPE_POINT 5
Define OBJ_TYPE_FRAME 6
Define OBJ_TYPE_REGION 7
Define OBJ_TYPE_RECT 8
Define OBJ_TYPE_ROUNDRECT 9
Define OBJ_TYPE_TEXT 10
Define OBJ_TYPE_MPOINT 11
Define OBJ_TYPE_COLLECTION 12
'====================================================================
' SearchInfo() defines
'====================================================================
Define SEARCH_INFO_TABLE 1
Define SEARCH_INFO_ROW 2
'====================================================================
' SelectionInfo() defines
'====================================================================
Define SEL_INFO_TABLENAME 1
Define SEL_INFO_SELNAME 2
Define SEL_INFO_NROWS 3
'====================================================================
' Server statement and function defines
'====================================================================
'--------------------------------------------------------------------
' Return Codes
'--------------------------------------------------------------------
Define SRV_SUCCESS 0
Define SRV_SUCCESS_WITH_INFO 1
Define SRV_ERROR -1
Define SRV_INVALID_HANDLE -2
Define SRV_NEED_DATA 99
Define SRV_NO_MORE_DATA 100
'--------------------------------------------------------------------
' Special values for the status associated with a fetched value
'--------------------------------------------------------------------
Define SRV_NULL_DATA -1
Define SRV_TRUNCATED_DATA -2
'--------------------------------------------------------------------
' Server_ColumnInfo() Attr defines
'--------------------------------------------------------------------
Define SRV_COL_INFO_NAME 1
Define SRV_COL_INFO_TYPE 2
Define SRV_COL_INFO_WIDTH 3
Define SRV_COL_INFO_PRECISION 4
Define SRV_COL_INFO_SCALE 5
Define SRV_COL_INFO_VALUE 6
Define SRV_COL_INFO_STATUS 7
Define SRV_COL_INFO_ALIAS 8
'--------------------------------------------------------------------
' Column types, returned by
Server_ColumnInfo(<stmt>,<colno>,SRV_COL_INFO_TYPE)
'--------------------------------------------------------------------
Define SRV_COL_TYPE_NONE 0
Define SRV_COL_TYPE_CHAR 1
Define SRV_COL_TYPE_DECIMAL 2
Define SRV_COL_TYPE_INTEGER 3
Define SRV_COL_TYPE_SMALLINT 4
Define SRV_COL_TYPE_DATE 5
Define SRV_COL_TYPE_LOGICAL 6
Define SRV_COL_TYPE_FLOAT 8
Define SRV_COL_TYPE_FIXED_LEN_STRING 16
Define SRV_COL_TYPE_BIN_STRING 17
'--------------------------------------------------------------------
' Server_DriverInfo() Attr defines
'--------------------------------------------------------------------
Define SRV_DRV_INFO_NAME 1
Define SRV_DRV_INFO_NAME_LIST 2
Define SRV_DRV_DATA_SOURCE 3
'--------------------------------------------------------------------
' Server_ConnectInfo() Attr defines
'--------------------------------------------------------------------
Define SRV_CONNECT_INFO_DRIVER_NAME 1
Define SRV_CONNECT_INFO_DB_NAME 2
Define SRV_CONNECT_INFO_SQL_USER_ID 3
Define SRV_CONNECT_INFO_DS_NAME 4
Define SRV_CONNECT_INFO_QUOTE_CHAR 5
'--------------------------------------------------------------------
' Fetch Directions used by Server_Fetch()
'--------------------------------------------------------------------
Define SRV_FETCH_NEXT -1
Define SRV_FETCH_PREV -2
Define SRV_FETCH_FIRST -3
Define SRV_FETCH_LAST -4
'====================================================================
' StringCompare(<str_1>, <str_2>) return values
'====================================================================
Define STR_LT -1
Define STR_GT 1
Define STR_EQ 0
'====================================================================
' StyleAttr() defines
'====================================================================
Define PEN_WIDTH 1
Define PEN_PATTERN 2
Define PEN_COLOR 4
Define PEN_INDEX 5
Define PEN_INTERLEAVED 6
Define BRUSH_PATTERN 1
Define BRUSH_FORECOLOR 2
Define BRUSH_BACKCOLOR 3
Define FONT_NAME 1
Define FONT_STYLE 2
Define FONT_POINTSIZE 3
Define FONT_FORECOLOR 4
Define FONT_BACKCOLOR 5
Define SYMBOL_CODE 1
Define SYMBOL_COLOR 2
Define SYMBOL_POINTSIZE 3
Define SYMBOL_ANGLE 4
Define SYMBOL_FONT_NAME 5
Define SYMBOL_FONT_STYLE 6
Define SYMBOL_KIND 7
Define SYMBOL_CUSTOM_NAME 8
Define SYMBOL_CUSTOM_STYLE 9
'--------------------------------------------------------------------
' Symbol kinds returned by StyleAttr(<symbol>, SYMBOL_KIND)
'--------------------------------------------------------------------
Define SYMBOL_KIND_VECTOR 1
Define SYMBOL_KIND_FONT 2
Define SYMBOL_KIND_CUSTOM 3
'====================================================================
' SystemInfo() defines
'====================================================================
Define SYS_INFO_PLATFORM 1
Define SYS_INFO_APPVERSION 2
Define SYS_INFO_MIVERSION 3
Define SYS_INFO_RUNTIME 4
Define SYS_INFO_CHARSET 5
Define SYS_INFO_COPYPROTECTED 6
Define SYS_INFO_APPLICATIONWND 7
Define SYS_INFO_DDESTATUS 8
Define SYS_INFO_MAPINFOWND 9
Define SYS_INFO_NUMBER_FORMAT 10
Define SYS_INFO_DATE_FORMAT 11
Define SYS_INFO_DIG_INSTALLED 12
Define SYS_INFO_DIG_MODE 13
Define SYS_INFO_MIPLATFORM 14
Define SYS_INFO_MDICLIENTWND 15
Define SYS_INFO_PRODUCTLEVEL 16
Define SYS_INFO_APPIDISPATCH 17
'--------------------------------------------------------------------
' Platform, returned by SystemInfo(SYS_INFO_PLATFORM)
'--------------------------------------------------------------------
Define PLATFORM_SPECIAL 0
Define PLATFORM_WIN 1
Define PLATFORM_MAC 2
Define PLATFORM_MOTIF 3
Define PLATFORM_X11 4
Define PLATFORM_XOL 5
'--------------------------------------------------------------------
' Version, returned by SystemInfo(SYS_INFO_MIPLATFORM)
'--------------------------------------------------------------------
Define MIPLATFORM_SPECIAL 0
Define MIPLATFORM_WIN16 1
Define MIPLATFORM_WIN32 2
Define MIPLATFORM_POWERMAC 3
Define MIPLATFORM_MAC68K 4
Define MIPLATFORM_HP 5
Define MIPLATFORM_SUN 6
'====================================================================
' TableInfo() defines
'====================================================================
Define TAB_INFO_NAME 1
Define TAB_INFO_NUM 2
Define TAB_INFO_TYPE 3
Define TAB_INFO_NCOLS 4
Define TAB_INFO_MAPPABLE 5
Define TAB_INFO_READONLY 6
Define TAB_INFO_TEMP 7
Define TAB_INFO_NROWS 8
Define TAB_INFO_EDITED 9
Define TAB_INFO_FASTEDIT 10
Define TAB_INFO_UNDO 11
Define TAB_INFO_MAPPABLE_TABLE 12
Define TAB_INFO_USERMAP 13
Define TAB_INFO_USERBROWSE 14
Define TAB_INFO_USERCLOSE 15
Define TAB_INFO_USEREDITABLE 16
Define TAB_INFO_USERREMOVEMAP 17
Define TAB_INFO_USERDISPLAYMAP 18
Define TAB_INFO_TABFILE 19
Define TAB_INFO_MINX 20
Define TAB_INFO_MINY 21
Define TAB_INFO_MAXX 22
Define TAB_INFO_MAXY 23
Define TAB_INFO_SEAMLESS 24
Define TAB_INFO_COORDSYS_MINX 25
Define TAB_INFO_COORDSYS_MINY 26
Define TAB_INFO_COORDSYS_MAXX 27
Define TAB_INFO_COORDSYS_MAXY 28
Define TAB_INFO_COORDSYS_CLAUSE 29
Define TAB_INFO_COORDSYS_NAME 30
Define TAB_INFO_NREFS 31
'--------------------------------------------------------------------
' Table type defines, returned by TableInfo(<tab_ref>, TAB_INFO_TYPE)
'--------------------------------------------------------------------
Define TAB_TYPE_BASE 1
Define TAB_TYPE_RESULT 2
Define TAB_TYPE_VIEW 3
Define TAB_TYPE_IMAGE 4
Define TAB_TYPE_LINKED 5
'====================================================================
' WindowInfo() defines
'====================================================================
Define WIN_INFO_NAME 1
Define WIN_INFO_TYPE 3
Define WIN_INFO_WIDTH 4
Define WIN_INFO_HEIGHT 5
Define WIN_INFO_X 6
Define WIN_INFO_Y 7
Define WIN_INFO_TOPMOST 8
Define WIN_INFO_STATE 9
Define WIN_INFO_TABLE 10
Define WIN_INFO_LEGENDS_MAP 10
Define WIN_INFO_OPEN 11
Define WIN_INFO_WND 12
Define WIN_INFO_WINDOWID 13
Define WIN_INFO_WORKSPACE 14
Define WIN_INFO_CLONEWINDOW 15
Define WIN_INFO_SYSMENUCLOSE 16
Define WIN_INFO_AUTOSCROLL 17
Define WIN_INFO_SMARTPAN 18
Define WIN_INFO_SNAPMODE 19
Define WIN_INFO_SNAPTHRESHOLD 20
Define WIN_INFO_PRINTER_NAME 21
Define WIN_INFO_PRINTER_ORIENT 22
Define WIN_INFO_PRINTER_COPIES 23
Define WIN_INFO_PRINTER_PAPERSIZE 24
Define WIN_INFO_PRINTER_LEFTMARGIN 25
Define WIN_INFO_PRINTER_RIGHTMARGIN 26
Define WIN_INFO_PRINTER_TOPMARGIN 27
Define WIN_INFO_PRINTER_BOTTOMMARGIN 28
Define WIN_INFO_PRINTER_BORDER 29
Define WIN_INFO_PRINTER_TRUECOLOR 30
Define WIN_INFO_PRINTER_DITHER 31
Define WIN_INFO_PRINTER_METHOD 32
Define WIN_INFO_PRINTER_TRANSPRASTER 33
Define WIN_INFO_PRINTER_TRANSPVECTOR 34
Define WIN_INFO_EXPORT_BORDER 35
Define WIN_INFO_EXPORT_TRUECOLOR 36
Define WIN_INFO_EXPORT_DITHER 37
Define WIN_INFO_EXPORT_TRANSPRASTER 38
Define WIN_INFO_EXPORT_TRANSPVECTOR 39
'--------------------------------------------------------------------
' Window types, returned by WindowInfo(<win_id>, WIN_INFO_TYPE)
'--------------------------------------------------------------------
Define WIN_MAPPER 1
Define WIN_BROWSER 2
Define WIN_LAYOUT 3
Define WIN_GRAPH 4
Define WIN_BUTTONPAD 19
Define WIN_TOOLBAR 25
Define WIN_CART_LEGEND 27
Define WIN_3DMAP 28
Define WIN_HELP 1001
Define WIN_MAPBASIC 1002
Define WIN_MESSAGE 1003
Define WIN_RULER 1007
Define WIN_INFO 1008
Define WIN_LEGEND 1009
Define WIN_STATISTICS 1010
Define WIN_MAPINFO 1011
'--------------------------------------------------------------------
' Version 2 window types no longer used in version 3 or version 4
'--------------------------------------------------------------------
Define WIN_TOOLPICKER 1004
Define WIN_PENPICKER 1005
Define WIN_SYMBOLPICKER 1006
'--------------------------------------------------------------------
' Window states, returned by WindowInfo(<win_id>, WIN_INFO_STATE)
'--------------------------------------------------------------------
Define WIN_STATE_NORMAL 0
Define WIN_STATE_MINIMIZED 1
Define WIN_STATE_MAXIMIZED 2
'--------------------------------------------------------------------
' Print orientation, returned by WindowInfo(<win_id>,
WIN_INFO_PRINTER_ORIENT)
'--------------------------------------------------------------------
Define WIN_PRINTER_PORTRAIT 1
Define WIN_PRINTER_LANDSCAPE 2
'
====================================================================
' Set Next Document Style defines
'====================================================================
Define WIN_STYLE_STANDARD 0
Define WIN_STYLE_CHILD 1
Define WIN_STYLE_POPUP_FULLCAPTION 2
Define WIN_STYLE_POPUP 3
'====================================================================
' LabelInfo return type defines
'====================================================================
Define LABEL_INFO_OBJECT 1
Define LABEL_INFO_POSITION 2
Define LABEL_INFO_ANCHORX 3
Define LABEL_INFO_ANCHORY 4
Define LABEL_INFO_OFFSET 5
Define LABEL_INFO_ROWID 6
Define LABEL_INFO_TABLE 7
Define LABEL_INFO_EDIT 8
Define LABEL_INFO_EDIT_VISIBILITY 9
Define LABEL_INFO_EDIT_ANCHOR 10
Define LABEL_INFO_EDIT_OFFSET 11
Define LABEL_INFO_EDIT_FONT 12
Define LABEL_INFO_EDIT_PEN 13
Define LABEL_INFO_EDIT_TEXT 14
Define LABEL_INFO_EDIT_TEXTARROW 15
Define LABEL_INFO_EDIT_ANGLE 16
Define LABEL_INFO_EDIT_POSITION 17
Define LABEL_INFO_EDIT_TEXTLINE 18
Define LABEL_INFO_SELECT 19
Define LABEL_INFO_DRAWN 20
'====================================================================
' LegendInfo attribute codes
'====================================================================
Define LEGEND_INFO_MAP_ID 1
Define LEGEND_INFO_ORIENTATION 2
Define LEGEND_INFO_NUM_FRAMES 3
'====================================================================
' Return codes for LEGEND_INFO_ORIENTATION
'====================================================================
Define ORIENTATION_PORTRAIT 1
Define ORIENTATION_LANDSCAPE 2
Define ORIENTATION_CUSTOM 3
'
====================================================================
' LegendFrameInfo attribute codes
'====================================================================
Define FRAME_INFO_TYPE 1
Define FRAME_INFO_MAP_LAYER_ID 2
Define FRAME_INFO_REFRESHABLE 3
Define FRAME_INFO_POS_X 4
Define FRAME_INFO_POS_Y 5
Define FRAME_INFO_WIDTH 6
Define FRAME_INFO_HEIGHT 7
Define FRAME_INFO_TITLE 8
Define FRAME_INFO_TITLE_FONT 9
Define FRAME_INFO_SUBTITLE 10
Define FRAME_INFO_SUBTITLE_FONT 11
Define FRAME_INFO_BORDER_PEN 12
Define FRAME_INFO_NUM_STYLES 13
Define FRAME_INFO_VISIBLE 14
Define FRAME_INFO_COLUMN 15
Define FRAME_INFO_LABEL 16
'====================================================================
' Return codes for FRAME_INFO_TYPE
'====================================================================
Define FRAME_TYPE_STYLE 1
Define FRAME_TYPE_THEME 2
'====================================================================
' LegendStyleInfo attribute codes
'====================================================================
Define LEGEND_STYLE_INFO_TEXT 1
Define LEGEND_STYLE_INFO_FONT 2
Define LEGEND_STYLE_INFO_OBJ 3
'====================================================================
' DateWindow attribute codes
'====================================================================
Define DATE_WIN_SESSION 1
Define DATE_WIN_CURPROG 2
'====================================================================
' Codes passed to the Map3DInfo function to get info about a map3d win.
'====================================================================
Define MAP3D_INFO_SCALE 1
Define MAP3D_INFO_RESOLUTION_X 2
Define MAP3D_INFO_RESOLUTION_Y 3
Define MAP3D_INFO_BACKGROUND 4
Define MAP3D_INFO_UNITS 5
Define MAP3D_INFO_LIGHT_X 6
Define MAP3D_INFO_LIGHT_Y 7
Define MAP3D_INFO_LIGHT_Z 8
Define MAP3D_INFO_LIGHT_COLOR 9
Define MAP3D_INFO_CAMERA_X 10
Define MAP3D_INFO_CAMERA_Y 11
Define MAP3D_INFO_CAMERA_Z 12
Define MAP3D_INFO_CAMERA_FOCAL_X 13
Define MAP3D_INFO_CAMERA_FOCAL_Y 14
Define MAP3D_INFO_CAMERA_FOCAL_Z 15
Define MAP3D_INFO_CAMERA_VU_1 16
Define MAP3D_INFO_CAMERA_VU_2 17
Define MAP3D_INFO_CAMERA_VU_3 18
Define MAP3D_INFO_CAMERA_VPN_1 19
Define MAP3D_INFO_CAMERA_VPN_2 20
Define MAP3D_INFO_CAMERA_VPN_3 21
Define MAP3D_INFO_CAMERA_CLIP_NEAR 22
Define MAP3D_INFO_CAMERA_CLIP_FAR 23
'====================================================================
' Codes passed to the PrismMapInfo function to get info about a
PrismMap win.
'====================================================================
Define PRISMMAP_INFO_SCALE 1
Define PRISMMAP_INFO_BACKGROUND 4
Define PRISMMAP_INFO_LIGHT_X 6
Define PRISMMAP_INFO_LIGHT_Y 7
Define PRISMMAP_INFO_LIGHT_Z 8
Define PRISMMAP_INFO_LIGHT_COLOR 9
Define PRISMMAP_INFO_CAMERA_X 10
Define PRISMMAP_INFO_CAMERA_Y 11
Define PRISMMAP_INFO_CAMERA_Z 12
Define PRISMMAP_INFO_CAMERA_FOCAL_X 13
Define PRISMMAP_INFO_CAMERA_FOCAL_Y 14
Define PRISMMAP_INFO_CAMERA_FOCAL_Z 15
Define PRISMMAP_INFO_CAMERA_VU_1 16
Define PRISMMAP_INFO_CAMERA_VU_2 17
Define PRISMMAP_INFO_CAMERA_VU_3 18
Define PRISMMAP_INFO_CAMERA_VPN_1 19
Define PRISMMAP_INFO_CAMERA_VPN_2 20
Define PRISMMAP_INFO_CAMERA_VPN_3 21
Define PRISMMAP_INFO_CAMERA_CLIP_NEAR 22
Define PRISMMAP_INFO_CAMERA_CLIP_FAR 23
Define PRISMMAP_INFO_INFOTIP_EXPR 24
'====================================================================
' Codes to pass to LocateFile$()
'====================================================================
Define LOCATE_PREF_FILE 0
Define LOCATE_DEF_WOR 1
Define LOCATE_CLR_FILE 2
Define LOCATE_PEN_FILE 3
Define LOCATE_FNT_FILE 4
Define LOCATE_ABB_FILE 5
Define LOCATE_PRJ_FILE 6
Define LOCATE_MNU_FILE 7
Define LOCATE_CUSTSYMB_DIR 8
Define LOCATE_THMTMPLT_DIR 9
Define LOCATE_GRAPH_DIR 10
'====================================================================
' Codes to pass to GetFolderPath$()
'====================================================================
Define FOLDER_MI_APPDATA -1
Define FOLDER_MI_LOCAL_APPDATA -2
Define FOLDER_MI_PREFERENCE -3
Define FOLDER_MI_COMMON_APPDATA -4
Define FOLDER_APPDATA 26
Define FOLDER_LOCAL_APPDATA 28
Define FOLDER_COMMON_APPDATA 35
Define FOLDER_COMMON_DOCS 46
Define FOLDER_MYDOCS 5
Define FOLDER_MYPICS 39
'====================================================================
' Codes passed to the SessionInfo() function
'====================================================================
Define SESSION_INFO_COORDSYS_CLAUSE1
Define SESSION_INFO_DISTANCE_UNITS2
Define SESSION_INFO_AREA_UNITS3
Define SESSION_INFO_PAPER_UNITS4
'====================================================================
' Abbreviated list of error codes
'
' The following are error codes described in the Reference manual. All
' other errors are listed in ERRORS.DOC.
'====================================================================
Define ERR_BAD_WINDOW 590
Define ERR_BAD_WINDOW_NUM 648
'====================================================================
' Backward Compatibility defines
'
' These defines are provide so that existing MapBasic code will
continue
' to compile & run correctly. Please use the new define (on the right)
' when writing new code.
'====================================================================
Define OBJ_ARC OBJ_TYPE_ARC
Define OBJ_ELLIPSE OBJ_TYPE_ELLIPSE
Define OBJ_LINE OBJ_TYPE_LINE
Define OBJ_PLINE OBJ_TYPE_PLINE
Define OBJ_POINT OBJ_TYPE_POINT
Define OBJ_FRAME OBJ_TYPE_FRAME
Define OBJ_REGION OBJ_TYPE_REGION
Define OBJ_RECT OBJ_TYPE_RECT
Define OBJ_ROUNDRECT OBJ_TYPE_ROUNDRECT
Define OBJ_TEXT OBJ_TYPE_TEXT
'====================================================================
' end of MAPBASIC.DEF
'====================================================================
showing/hiding the menu Modal dialog boxes 206 Numeric operators 643
bar 342 Modifying an object. See specific NumTables( ) function 357
Menus, list of standard names object type NumWindows( ) function 358
and IDs 40–41 Arc, Ellipse, Frame, Line,
Merging objects. See Combining Point, Polyline,
O
objects Rectangle, Region,
Object model. See User’s Guide or
Messages Rounded Rectangle, Text
online Help
displaying in a Note dialog Module-level variables 214
Object variables 214
353 Month( ) function 352
ObjectInfo( ) function 361–364
displaying on the status bar Most-recently-used list (File
ObjectLen( ) function 365
587 menu) 146
ObjectNodeX( ) function 366–367
opening the Message Mouse actions 521
ObjectNodeY( ) function 368
window 394 Mouse cursor
Objects Check statement 369–370
printing to the Message customizing shape of 32
Objects Clean statement 371
window 406 displaying coordinates of
Objects Combine statement
Metadata 541
372–373
code example 348 MRU list (File menu) 146
Objects Disaggregate statement
keys 346–348 MultiListBox controls 104–105
374–375
managing in tables 346–348 Multipoint objects
Objects Enclose statement 376
reading keys 274 combining 90
Objects Erase statement 377–378
Metadata statement 346–348 creating 152–153
Objects Intersect statement
Metric units inserting nodes 50–51
379–380
area 512
Objects Overlay statement 381
distance 520
N Objects Snap statement 382–383
Microsoft Access databases
Natural Break thematic ranges Objects Split statement 384–385
connection string attributes
164 Objects, creating
482
Network file sharing 523 arcs 120
Mid$( ) function 349
Nodes buffer regions 156
MidByte$( ) function 350
adding 49, 381, 396 by buffering 67, 154–157
MIF files
displaying 543 by combining objects 90
exporting 240–242
extracting a range of nodes by intersecting objects 395
importing 283–287
from an object 243 circles 129–130, 133
Military grid reference format
maximum number per convex hull 155
337, 541
object 158, 170 ellipses 129–130, 133
Min( ) aggregate function
querying number of nodes frames 134–135
469–470
362 lines 140, 141
Minimizing MapInfo
querying x/y coordinates map labels 61
Set Window statement
366–367, 368 multipoint 152–153
564–570
removing 49 points 159–160, 161
suppressing progress bars
Noselect keyword 469 polylines 158
554
Note statement 353 rectangles 167
Minimum bounding rectangle
Null handling 499 regions 169–170
of an object 341
NumAllWindows( ) function 354 rounded rectangles 172
of entire table 606
Number of characters in a string text 177–178, 179
Minimum( ) function 351
316 Voronoi polygons 156
Mixed case, converting to 416
NumberToDate( ) function 355
Mod operator 643
NumCols( ) function 356
Set Legend statement 533–534 Spaces, trimming from a string String functions
Set Map statement 535–546 322, 448 capitalization 310, 416, 620
Set Map3D statement 547–548 Speed, improving comparison 591, 592
Set Next Document statement animation layers 25–26 converting codes to strings
549–550 screen updates 522 83
Set Paper Units statement 551 table editing 561–562 converting strings to codes
Set PrismMap statement 552–553 SphericalArea( ) function 582 57
Set ProgressBars statement 554 SphericalDistance( ) function 583 converting strings to dates
Set Resolution statement 557 SphericalObjectLen( ) function 524–525, 593–594
Set Shade statement 558 584 converting strings to
Set Style statement 559–560 SphericalPerimeter( ) function numbers 524–525, 627
Set Table statement 561–562 585 converting values to strings
Set Target statement 563 Splitting objects 384–385 589
Set Window statement 564–570 Spreadsheets, using as tables extracting part of a string
Sgn( ) function 571 425–429 311, 349, 350, 442
Shadow text 257–258 SQL Select 466–473 finding a substring within a
Shapefiles 428 SQL Server databases string 292
Shift key connection string attributes formatting a number 203,
detecting shift-click 93 485–487 262–264, 266, 524–525
effect on drawing tools 32– Sqr( ) function 586 formatting based on locale
33 Starting other applications 524–525
selecting multiple list items Run Application statement length of string 316
104–105 449 locale settings 524–525
Shortcut menus Run Program statement 453 pattern matching 317
defined 40–41 StaticText controls 111 repeated strings 590
disabling 149 Statistical calculations spaces 581
example 41 average 22, 469–470 trimming spaces from end
list of menu names and IDs count 22, 469–470 448
40–41 min/max 22, 469–470 trimming spaces from start
Show/Hide menu commands quantile 165 322
147 standard deviation 164 String variables 214
Showing sum 22, 469–470 String$( ) function 590
ButtonPads 30–33 weighted average 22, StringCompare( ) function 591
dialog controls 35–36 470–471 StringCompareIntl( ) function
menu bar 342 Statistics window 592
Shutting down the connection closing 87 StringToDate( ) function 593–594
Server Disconnect 495 modifying 564–570 Structures 618
Simulating a menu selection 452 opening 394 StyleAttr() function 595–597
Sin( ) function 580 Status bar help 31, 122 Styles. See specific type
Small integer variables 214 StatusBar Pen, Brush, Font, Symbol
Smart redraw 539 statement 587 Sub procedures. See Procedures
Snap tolerance Stop statement 588 Sub...End Sub statement 598–599
controlling 569–570 Str$( ) function 589 Subtotals, calculating 469–470
Snapping nodes 382–383 Street addresses, finding 251–253 Sum( ) aggregate function
Sorting rows in a table 471–472 String concatenation 469–470
Sounds, beeping 62 & operator 643
Space$( ) function 581 + operator 643
Tooltip help 31, 122 User interface. See ButtonPads, Windows, modifying
Totals, calculating 469–470 Dialogs, Menus, Windows adding map layers 25–26
Transparent fill patterns 65 browser windows 513
Trapping errors. See Error forcing windows to redraw
V
handling 626
Val( ) function 627
TriggerControl( ) function 616 general window settings
Variable length strings 214
Trigonometric functions 564–570
Variables
arc-cosine 18 graph windows 526–529
arrays 215, 423–424, 619
arc-sine 58 layout windows 531–532
custom types 618
arc-tangent 60 legend window 533–534
global variables 276
cosine 119 map windows 535–546
initializing 216
sine 580 redistrict windows 555–556
list of types 213–214
tangent 608 removing map layers 436
local variables 213–217
Trimming spaces Windows, opening
module-level variables 214
from end of string 448 Browse statement 63–64
reading another
from start of string 322 Create Redistricter
application’s variables
TrueFileName$( ) function 617 statement 168
276
TrueType fonts, using as symbols Graph statement 278–279
restrictions on names 216
328 Layout statement 309
strings variables 215
TrueType symbols 600–602 Map statement 331–332
undefining 621
Type statement 618 Open Window statement
Version number
394
.MBX version 603
Windows, printing
U MapInfo version 604
to a file 455–456
UBound( ) function 619 Vertices. See Nodes
to an output device 408
UCase$( ) function 620 Voronoi polygons
Windows, querying
Unchecking Create Object 156
3D Map window settings
dialog check boxes (custom)
333–335
35–36
W general window settings
dialog check boxes
Weekday( ) function 628 633–637
(standard) 37–38
Weighted averages 22, 470–471 ID of a window 632
menu items 44–45
While...Wend statement 629 ID of front window 267
Underlined text 257–258
Wildcards, matching 317 map window settings
UnDim statement 621
WinChangedHandler procedure 304–308, 336–339
Undo system, disabling 561–562
630 number of document
UnitAbbr$( ) function 622
WinClosedHandler procedure windows 358
UnitName$( ) function 623
631 total number of windows
Units of measure
WindowID( ) function 632 354
abbreviated names 622
WindowInfo( ) function 633–637 WinFocusChangedHandler
area 512
Windows Latin 1 character set procedure 638
distance 520
641 WKS files, opening 425–429
full names 623
Windows operating system WMF files, creating 455–456
paper 551
16- v. 32-bit 604 Workspaces
Unlink statement 624
Windows, closing loading 449
Unselecting 86
Close Window statement 87 saving 457
Update statement 625
preventing user from closing Write # statement 639
Update Window statement 626
windows 567 WtAvg( ) aggregate function
Upper case, converting to 620
470–471
X
XCMDs 94, 200–201
XFCNs 198–199
XLS files, opening 425–429
Y
Year( ) function 640