Map Basic Reference
Map Basic Reference
Version 12.0
Reference
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 Pitney
Bowes Software Inc., One Global View, Troy, New York 12180-8399.
2013 Pitney Bowes Software Inc. All rights reserved. Pitney Bowes Software Inc. is a wholly owned subsidiary
of Pitney Bowes Inc. Pitney Bowes, the Corporate logo, MapInfo, Group 1 Software, and MapBasic are trademarks of Pitney Bowes Software Inc. All other marks and trademarks are property of their respective holders.
Contact information for all Pitney Bowes Software Inc. offices is located at: http://www.pb.com/contact-us.
2013 Adobe Systems Incorporated. All rights reserved. Adobe, the Adobe logo, Acrobat and the Adobe PDF
logo are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States and/or
other countries.
2013 OpenStreetMap contributors, CC-BY-SA; see OpenStreetMap http://www.openstreetmap.org (license
2006-2013 TomTom International BV. All Rights Reserved. This material is proprietary and the subject of
copyright protection and other intellectual property rights owned or licensed to TomTom. The use of this material is subject to the terms of a license agreement. You will be held liable for any unauthorized copying or disclosure of this material.
Microsoft Bing: All contents of the Bing service are Copyright 2013 Microsoft Corporation and/or its suppliers,
One Microsoft Way, Redmond, WA 98052, USA. All rights reserved. Microsoft or its suppliers own the title,
copyright, and other intellectual property rights in the Bing service and content. Microsoft, Windows, Windows
Live, Windows logo, MSN, MSN logo (butterfly), Bing, and other Microsoft products and services may also be
either trademarks or registered trademarks of Microsoft in the United States and/or other countries.
This product contains 7-Zip, which is licensed under GNU Lesser General Public License, Version 3, 29 June
2007 with the unRAR restriction. The license can be downloaded from http://www.7-zip.org/license.txt. The
GNU License may be downloaded from http://www.gnu.org/licenses/lgpl.html. The source code is available
from http://www.7-zip.org.
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.
June 06, 2013
Contents
Chapter 1: Introduction to MapBasic......................................................................23
Type Conventions..............................................................................................................24
Language Overview...........................................................................................................24
MapBasic Fundamentals..................................................................................................25
Variables........................................................................................................................25
Looping and Branching..................................................................................................25
Output and Printing........................................................................................................25
Procedures (Main and Subs).........................................................................................25
Error Handling................................................................................................................26
Functions...........................................................................................................................26
Custom Functions..........................................................................................................26
Data-Conversion Functions...........................................................................................26
Date and Time Functions...............................................................................................27
Math Functions...............................................................................................................27
String Functions.............................................................................................................27
Working With Tables.........................................................................................................28
Creating and Modifying Tables.......................................................................................28
Querying Tables.............................................................................................................29
Working With Remote Data............................................................................................29
Working With Files (Other Than Tables) ........................................................................30
File Input/Output.............................................................................................................30
File and Directory Names..............................................................................................30
Working With Maps and Graphical Objects....................................................................31
Creating Map Objects....................................................................................................31
Modifying Map Objects...................................................................................................31
Querying Map Objects...................................................................................................32
Working With Object Styles............................................................................................32
Working With Map Windows..........................................................................................33
Working With Legend Designer Windows......................................................................33
MapBasic 12.0
Reference
MapBasic 12.0
Reference
DateWindow( ) function................................................................................................246
Day( ) function .............................................................................................................247
DDEExecute statement................................................................................................248
DDEInitiate( ) function..................................................................................................248
DDEPoke statement.....................................................................................................252
DDERequest$( ) function.............................................................................................253
DDETerminate statement.............................................................................................254
DDETerminateAll statement.........................................................................................255
Declare Function statement.........................................................................................256
Declare Method statement...........................................................................................258
Declare Sub statement................................................................................................260
Define statement..........................................................................................................261
DeformatNumber$( ) function......................................................................................262
Delete statement..........................................................................................................263
Dialog statement..........................................................................................................264
Dialog Preserve statement...........................................................................................270
Dialog Remove statement............................................................................................271
Dim statement..............................................................................................................272
Distance( ) function......................................................................................................276
Do Case...End Case statement...................................................................................277
Do...Loop statement.....................................................................................................279
Drop Index statement...................................................................................................280
Drop Map statement.....................................................................................................281
Drop Table statement...................................................................................................282
End MapInfo statement................................................................................................283
End Program statement...............................................................................................283
EndHandler procedure.................................................................................................284
EOF( ) function.............................................................................................................284
EOT( ) function.............................................................................................................285
EPSGToCoordSysString$( ) function...........................................................................286
Erase( ) function...........................................................................................................287
Err( ) function...............................................................................................................287
Error statement............................................................................................................289
Error$( ) function..........................................................................................................289
Exit Do statement.........................................................................................................290
Exit For statement........................................................................................................290
Exit Function statement................................................................................................291
Exit Sub statement.......................................................................................................292
10
MapBasic 12.0
Exp( ) function..............................................................................................................292
Export statement..........................................................................................................293
ExtractNodes( ) function..............................................................................................296
Farthest statement.......................................................................................................297
Fetch statement...........................................................................................................299
FileAttr( ) function.........................................................................................................301
FileExists( ) function.....................................................................................................302
FileOpenDlg( ) function................................................................................................302
FileSaveAsDlg( ) function............................................................................................304
Find statement.............................................................................................................305
Find Using statement...................................................................................................309
Fix( ) function...............................................................................................................310
Font clause...................................................................................................................311
For...Next statement.....................................................................................................313
ForegroundTaskSwitchHandler procedure...................................................................314
Format$( ) function.......................................................................................................315
FormatDate$( ) function...............................................................................................317
FormatNumber$( ) function..........................................................................................318
FormatTime$( ) function...............................................................................................319
FME Refresh Table statement.....................................................................................321
FrontWindow( ) function...............................................................................................321
Function...End Function statement..............................................................................322
Geocode statement......................................................................................................324
GeocodeInfo( ) function...............................................................................................328
Get statement...............................................................................................................331
GetCurrentPath$( ) function.........................................................................................332
GetDate( ) function ......................................................................................................333
GetFolderPath$( ) function ..........................................................................................334
GetGridCellValue( ) function........................................................................................335
GetMetadata$( ) function.............................................................................................336
GetPreferencePath$( ) function ..................................................................................336
GetSeamlessSheet( ) function ....................................................................................337
GetTime() function ......................................................................................................338
Global statement..........................................................................................................339
Goto statement.............................................................................................................340
Graph statement..........................................................................................................340
GridTableInfo( ) function...............................................................................................342
GroupLayerInfo function..............................................................................................342
Reference
11
12
MapBasic 12.0
Log( ) function..............................................................................................................396
LTrim$( ) function.........................................................................................................397
Main procedure............................................................................................................398
MakeBrush( ) function..................................................................................................399
MakeCustomSymbol( ) function...................................................................................400
MakeDateTime( ) function............................................................................................401
MakeFont( ) function ...................................................................................................401
MakeFontSymbol( ) function........................................................................................402
MakePen( ) function.....................................................................................................403
MakeSymbol( ) function...............................................................................................404
Map statement.............................................................................................................405
Map3DInfo( ) function...................................................................................................408
MapperInfo( ) function..................................................................................................410
Maximum( ) function.....................................................................................................415
MBR( ) function............................................................................................................416
Menu Bar statement.....................................................................................................416
MenuItemInfoByHandler( ) function.............................................................................417
MenuItemInfoByID( ) function......................................................................................418
Metadata statement.....................................................................................................419
MGRSToPoint( ) function.............................................................................................421
Mid$( ) function............................................................................................................423
MidByte$( ) function.....................................................................................................423
Minimum( ) function......................................................................................................424
Minute( ) function ........................................................................................................425
Month( ) function .........................................................................................................425
Nearest statement........................................................................................................426
Note statement.............................................................................................................429
NumAllWindows( ) function..........................................................................................430
NumberToDate( ) function ...........................................................................................430
NumberToDateTime( ) function ...................................................................................431
NumberToTime( ) function............................................................................................431
NumCols( ) function.....................................................................................................432
NumTables( ) function..................................................................................................433
NumWindows( ) function..............................................................................................434
ObjectDistance( ) function ...........................................................................................434
ObjectGeography( ) function........................................................................................435
ObjectInfo( ) function....................................................................................................437
ObjectLen( ) function....................................................................................................441
Reference
13
ObjectNodeHasM( ) function........................................................................................442
ObjectNodeHasZ( ) function........................................................................................443
ObjectNodeM( ) function..............................................................................................444
ObjectNodeX( ) function...............................................................................................445
ObjectNodeY( ) function...............................................................................................446
ObjectNodeZ( ) function...............................................................................................447
Objects Check statement.............................................................................................448
Objects Clean statement..............................................................................................450
Objects Combine statement.........................................................................................451
Objects Disaggregate statement..................................................................................452
Objects Enclose statement..........................................................................................454
Objects Erase statement..............................................................................................455
Objects Intersect statement.........................................................................................457
Objects Move statement..............................................................................................458
Objects Offset statement..............................................................................................459
Objects Overlay statement...........................................................................................461
Objects Pline statement...............................................................................................461
Objects Snap statement...............................................................................................462
Objects Split statement................................................................................................464
Offset( ) function...........................................................................................................466
OffsetXY( ) function......................................................................................................467
OnError statement........................................................................................................468
Open Connection statement........................................................................................469
Open File statement.....................................................................................................471
Open Report statement................................................................................................473
Open Table statement..................................................................................................473
Open Window statement..............................................................................................475
Overlap( ) function........................................................................................................476
OverlayNodes( ) function.............................................................................................477
Pack Table statement...................................................................................................478
PathToDirectory$( ) function........................................................................................479
PathToFileName$( ) function.......................................................................................479
PathToTableName$( ) function.....................................................................................480
Pen clause...................................................................................................................481
PenWidthToPoints( ) function.......................................................................................484
Perimeter( ) function.....................................................................................................484
PointsToPenWidth( ) function.......................................................................................486
PointToMGRS$( ) function...........................................................................................486
14
MapBasic 12.0
PointToUSNG$( ) function............................................................................................488
Print statement.............................................................................................................489
Print # statement..........................................................................................................490
PrintWin statement.......................................................................................................491
PrismMapInfo( ) function..............................................................................................492
ProgramDirectory$( ) function......................................................................................494
ProgressBar statement................................................................................................495
Proper$( ) function.......................................................................................................497
ProportionOverlap( ) function.......................................................................................498
Put statement...............................................................................................................498
Randomize statement..................................................................................................499
RasterTableInfo( ) function...........................................................................................500
RegionInfo( ) function...................................................................................................502
ReadControlValue( ) function.......................................................................................502
ReDim statement.........................................................................................................505
Register Table statement.............................................................................................506
Relief Shade statement................................................................................................513
Reload Symbols statement..........................................................................................513
RemoteMapGenHandler procedure.............................................................................514
RemoteMsgHandler procedure....................................................................................514
RemoteQueryHandler( ) function.................................................................................515
Remove Cartographic Frame statement......................................................................517
Remove Designer Frame statement............................................................................517
Remove Designer Text statement................................................................................517
Remove Map statement...............................................................................................518
Rename File statement................................................................................................519
Rename Table statement.............................................................................................520
Reproject statement.....................................................................................................521
Resume statement.......................................................................................................521
RGB( ) function............................................................................................................522
Right$( ) function..........................................................................................................523
Rnd( ) function..............................................................................................................524
Rollback statement.......................................................................................................524
Rotate( ) function..........................................................................................................525
RotateAtPoint( ) function..............................................................................................526
Round( ) function..........................................................................................................527
RTrim$( ) function.........................................................................................................528
Run Application statement...........................................................................................528
Reference
15
16
MapBasic 12.0
Reference
17
18
MapBasic 12.0
TempFileName$( ) function..........................................................................................739
Terminate Application statement..................................................................................740
TextSize( ) function.......................................................................................................741
Time( ) function............................................................................................................741
Timer( ) function...........................................................................................................742
ToolHandler procedure.................................................................................................743
TriggerControl( ) function.............................................................................................744
TrueFileName$( ) function...........................................................................................745
Type statement.............................................................................................................746
UBound( ) function.......................................................................................................747
UCase$( ) function.......................................................................................................747
UnDim statement.........................................................................................................748
UnitAbbr$( ) function....................................................................................................749
UnitName$( ) function..................................................................................................750
Unlink statement..........................................................................................................750
Update statement.........................................................................................................751
Update Window statement...........................................................................................752
URL clause...................................................................................................................753
USNGToPoint( ) function..............................................................................................753
Val( ) function...............................................................................................................754
Weekday( ) function.....................................................................................................755
WFS Refresh Table statement.....................................................................................756
WKTToCoordSysString$( ) function.............................................................................757
While...Wend statement...............................................................................................758
WinChangedHandler procedure..................................................................................759
WinClosedHandler procedure......................................................................................760
WindowID( ) function....................................................................................................760
WindowInfo( ) function.................................................................................................762
WinFocusChangedHandler procedure.........................................................................767
Write # statement.........................................................................................................768
Year( ) function.............................................................................................................769
Reference
19
MICloseSession( ) procedure.........................................................................................775
MICreateSession( ) function...........................................................................................776
MICreateSessionFull( ) function.....................................................................................776
MIErrorDlg( ) function.....................................................................................................778
MIFindFtpFile( ) function.................................................................................................779
MIFindNextFtpFile( ) function.........................................................................................780
MIGetContent( ) function................................................................................................781
MIGetContentBuffer( ) function......................................................................................781
MIGetContentLen( ) function..........................................................................................782
MIGetContentString( ) function......................................................................................782
MIGetContentToFile( ) function......................................................................................783
MIGetContentType( ) function........................................................................................784
MIGetCurrentFtpDirectory( ) function...........................................................................784
MIGetErrorCode( ) function............................................................................................785
MIGetErrorMessage( ) function......................................................................................786
MIGetFileURL( ) function................................................................................................786
MIGetFtpConnection( ) function.....................................................................................787
MIGetFtpFile( ) function..................................................................................................788
MIGetFtpFileFind( ) function...........................................................................................789
MIGetFtpFileName( ) procedure.....................................................................................790
MIGetHttpConnection( ) function...................................................................................791
MIIsFtpDirectory( ) function............................................................................................791
MIIsFtpDots( ) function...................................................................................................792
MIOpenRequest( ) function.............................................................................................793
MIOpenRequestFull( ) function......................................................................................794
MIParseURL( ) function...................................................................................................795
MIPutFtpFile( ) function..................................................................................................796
MIQueryInfo( ) function...................................................................................................797
MIQueryInfoStatusCode( ) function...............................................................................798
MISaveContent( ) function..............................................................................................799
MISendRequest( ) function.............................................................................................800
MISendSimpleRequest( ) function.................................................................................801
MISetCurrentFtpDirectory( ) function............................................................................801
MISetSessionTimeout( ) function...................................................................................802
20
MapBasic 12.0
MIXmlDocumentDestroy( ) procedure...........................................................................808
MIXmlDocumentGetNamespaces( ) function................................................................808
MIXmlDocumentGetRootNode( ) function....................................................................809
MIXmlDocumentLoad( ) function...................................................................................809
MIXmlDocumentLoadXML( ) function...........................................................................810
MIXmlDocumentLoadXMLString( ) function.................................................................811
MIXmlDocumentSetProperty( ) function.......................................................................812
MIXmlGetAttributeList( ) function..................................................................................813
MIXmlGetChildList( ) function........................................................................................814
MIXmlGetNextAttribute( ) function................................................................................814
MIXmlGetNextNode( ) function.......................................................................................815
MIXmlNodeDestroy( ) procedure...................................................................................816
MIXmlNodeGetAttributeValue( ) function......................................................................816
MIXmlNodeGetFirstChild( ) function..............................................................................817
MIXmlNodeGetName( ) function....................................................................................817
MIXmlNodeGetParent( ) function...................................................................................818
MIXmlNodeGetText( ) function.......................................................................................819
MIXmlNodeGetValue( ) function.....................................................................................819
MIXmlNodeListDestroy( ) procedure.............................................................................820
MIXmlSCDestroy( ) procedure.......................................................................................821
MIXmlSCGetLength( ) function......................................................................................821
MIXmlSCGetNamespace( ) function..............................................................................822
MIXmlSelectNodes( ) function........................................................................................822
MIXmlSelectSingleNode( ) function...............................................................................823
Reference
21
22
MapBasic 12.0
Introduction to MapBasic
This manual describes every statement and function in the MapBasic Development
Environment programming language. To learn about the concepts behind MapBasic programming, or to learn about using the MapBasic development environment, see the MapBasic User Guide.
In this section:
Type Conventions
Type Conventions
This manual uses the following conventions to designate specific items in the text:
Convention
If, Call, Map, Browse, Area
Meaning
Bold words with the first letter capitalized are
MapBasic keywords.
Within this manual, the first letter of each keyword
is capitalized; however, when you write MapBasic
programs, you may enter keywords in upper-,
lower-, or mixed-case.
[ window_id ], [ Interactive ]
{ On | Off }
"Note "Hello,world!"
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 ( ).
24
MapBasic 12.0
MapBasic Fundamentals
Variables
Declare local or global variables:
Dim,Global
Type
Branching:
PrintWin
Save Window
Call a procedure:
Call
Exit a procedure:
Exit Sub
Main procedure:
Main
Reference
25
Error Handling
Error Handling
Set up an error handler:
OnError
Err( ), Error$( )
Resume
Simulate an error:
Error
Functions
Custom Functions
Define a custom function:
Exit a function:
Exit Function
Data-Conversion Functions
26
Asc( )
Chr$( )
Val( )
Str$( ), Format$( )
NumberToDate( ), StringToDate( )
ConvertToRegion( ), ConvertToPline( )
LabelInfo( )
PointToMGRS$( )
MGRSToPoint( )
PointToUSNG$(obj, datumid)
USNGToPoint(string)
MapBasic 12.0
CurDate( )
Time( )
NumberToDate( ), StringToDate( )
CurTime( ), CurDateTime( )
GetDate( ), GetTime( )
StringToDateTime( ), StringToTime( )
Math Functions
Trigonometric functions:
Geographic functions:
Random numbers:
Randomize, Rnd( )
Sign-related functions:
Abs( ), Sgn( )
Truncating fractions:
String Functions
Upper / lower case:
Find a sub-string:
InStr( )
Reference
27
LTrim$( ), RTrim$( )
Len( )
Chr$( ), Asc( )
Compare strings:
Space$( ), String$( )
UnitAbbr$( ), UnitName$( )
PointToMGRS$( )
MGRSToPoint( )
EPSGToCoordSysString$( )
PointToUSNG$(obj, datumid)
USNGToPoint(string)
28
Open Table
Create Table
Register Table
Import/export tables/files:
Import, Export
Open Report
Pack a table:
Pack Table
Set Table
MapBasic 12.0
Commit Table
Rollback
Rename a table:
Rename Table
Delete a table:
Drop Table
Querying Tables
Position the row cursor:
Fetch, EOT( )
Select, SelectionInfo( )
NumTables( ), TableInfo( )
NumCols( ), ColumnInfo( )
Create Query
GetMetadata$( ), Metadata
TableInfo( ), GetSeamlessSheet( )
Server_Connect( ), Server_ConnectInfo( )
Server_ColumnInfo( ), Server_NumCols( )
Server_Execute( )
Save changes:
Server
Discard changes:
Server Rollback
Server Close
Reference
29
Server Refresh
Unlink
Server Disconnect
Server_DriverInfo( ), Server_NumDrivers( )
Server_GetODBCHConn( )
Server_GetODBCHStmt( )
Open File
Close a file:
Close File
Delete a file:
Kill
Rename a file:
Rename File
Copy a file:
Save File
Write to a file:
Register Table
30
MapBasic 12.0
PathToTableName$( ), PathToDirectory$( ),
PathToFileName$( )
TrueFileName$( )
FileOpenDlg( ), FileSaveAsDlg( )
TempFileName$( )
Locate files:
LocateFile$( ), GetFolderPath$( )
Creation functions:
Advanced operations:
Insert, Update
Create regions:
Objects Enclose
Alter Object
ConvertToRegion( ), ConvertToPLine( )
Offset objects:
Set Target
Merge objects:
Reference
31
Rotate( ), RotateAtPoint( )
Split objects:
Set Resolution
Insert, Update
Objects Check
Object processing:
Set CoordSys
ObjectInfo( )
32
MapBasic 12.0
ObjectInfo( )
Alter Object
Reload Symbols
Style clauses:
Map
Create/edit 3DMaps:
Add Map
Remove Map
AutoLabel
Set Map
Reference
33
Create ButtonPad
Modify a ButtonPad:
Alter ButtonPad
Modify a button:
Alter Button
ButtonPadInfo( )
CommandInfo( )
Dialog Boxes
Display a standard dialog box:
Dialog
CommandInfo(CMD_INFO_DLG_OK)
Set ProgressBars
Menus
34
Create Menu
MapBasic 12.0
MenuItemInfoByHandler( ), MenuItemInfoByID(
)
Windows
Show or hide a window:
Map, Browse, Graph, Layout, Create Redistricter, Create Legend, Create Cartographic Legend, LegendFrameInfo
FrontWindow( ), WindowID( )
Print a window:
PrintWin
NumWindows( ), NumAllWindows( )
SelChangedHandler
WinClosedHandler
WinChangedHandler
WinFocusChangedHandler
RemoteMsgHandler, RemoteQueryHandler( )
RemoteMapGenHandler
ToolHandler
EndHandler
Reference
35
Set Handler
DDEInitiate( )
DDEExecute
DDEPoke
DDERequest$( )
DDETerminate, DDETerminateAll
Respond to a request:
RemoteMsgHandler, RemoteQueryHandler( ),
CommandInfo(CMD_INFO_MSG)
Integrated Mapping
Set MapInfo Professional 's parent window:
Create Legend
36
Declare Method( )
Run Program
SystemInfo( )
Run Command
Save Workspace
Run Application
MapBasic 12.0
Set Digitizer
Beep
Reference
37
Software Defects
2. Your name and organization. The person calling must be the contact person listed on the support
agreement.
3. Version of the product you are calling about.
4. The operating system name and version.
5. A brief explanation of the problem. Some details that can be helpful in this context are:
Error messages
Context in which the problem occurs
Consistency - is the problem reoccurring or occurring erratically?
Software Defects
If the issue is deemed to be a bug in the software, the representative will log the issue in Pitney Bowes
Software Inc. bug database and provide you with an incident number that you can use to track the bug.
Future upgrades and patches have fixes for many of the bugs logged against the product.
Other Resources
MapInfo-L Archive Database
Pitney Bowes Software Inc. Corporation, in conjunction with Bill Thoen, provides a web-based, searchable
archive database of MapInfo-L postings. The postings are currently organized by Discussion Threads
and Postings by Date.
Disclaimer: While Pitney Bowes Software Inc. Corporation provides this database as a service to its user
community, administration of the MapInfo-L mailing list is still provided by Bill Thoen. More information
on MapInfo-L can be obtained at the MapInfo-L web page located at http://groups.google.com/group/mapinfo-l?hl=en.
38
MapBasic 12.0
These are several new statements and functions added to the MapBasic API that
assist you in working with positioning labels and with the scale bar adornment.
In this section:
New MapBasic Functions and Statements . . . . . . . . . . . .40
Additions to Existing Functions and Statements . . . . . .40
40
MapBasic 12.0
ID
LABEL_INFO_POSITION
Integer value between 0 and 8, indicating the label's position relative to its anchor location. The return value will
match one of these codes:
LAYER_INFO_LBL_POS_AUTO (-1),
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).
LabelOverrideInfo( ) function
The LabelOverrideInfo( ) function now includes new attribute codes.
Attribute Code
ID
LBL_OVR_INFO_AUTO_POSITION 21
LBL_OVR_INFO_AUTO_SIZES
22
LBL_OVR_INFO_SUPPRESS_IF_NO_FIT
23
LBL_OVR_INFO_AUTO_SIZE_STEP 24
Reference
41
ID
LBL_OVR_INFO_CURVED_BEST_PO- 25
SITION
LBL_OVR_INFO_CURVED_FALLBACK
26
LBL_OVR_INFO_USE_ABBREVIATION
27
LBL_OVR_INFO_ABBREVIATION_EXPR
28
LBL_OVR_INFO_AUTO_CALLOUT
29
LayerInfo( ) function
The LayerInfo( ) function now includes new attribute codes.
42
Attribute Code
ID
LAYER_INFO_LBL_AUTO_POSITION
54
LAYER_INFO_LBL_AUTO_SIZES
55
LAYER_INFO_LBL_SUPPRESS_IF_NO_FIT
56
LAYER_INFO_LBL_AUTO_SIZE_STEP
57
LAY58
ER_INFO_LBL_CURVED_BEST_POSITION
LAYER_INFO_LBL_CURVED_FALL- 59
BACK
LAYER_INFO_LBL_USE_ABBREVI- 60
ATION
MapBasic 12.0
ID
LAYER_INFO_ABBREVIATION_EX- 61
PR
LAYER_INFO_LBL_AUTO_CALLOUT 62
LAYER_INFO_LBL_ORDER
63
LegendFrameInfo( ) function
The LegendFrameInfo( ) function now includes new attribute codes.
attribute code
ID
FRAME_INFO_LINE_SAMPLE_WIDTH 19
Returns line sample width in MapBasic paper units. Returns -1 for Cartographic Legend window.
FRAME_INFO_REGION_SAMPLE_WIDTH
20
FRAME_INFO_REGION_SAMPLE_HEIGHT
21
LegendInfo( ) function
The LegendInfo( ) function now includes a new attribute code.
attribute code
ID
LEGEND_INFO_NUM_TEXTFRAMES 8
MapperInfo( ) function
The MapperInfo( ) function now includes new attrbute and codes.
attribute setting
ID
MAPPER_INFO_DISPLAY
15
Small integer, indicating what aspect of the map is displayed on the status bar. Corresponds to Set Map Display. Return value will be one of these:
Reference
MAPPER_INFO_DISPLAY_SCALE (0)
MAPPER_INFO_DISPLAY_ZOOM (1)
MAPPER_INFO_DISPLAY_POSITION (2)
MAPPER_INFO_DISPLAY_CARTOGRAPHIC_SCALE
(3)
43
ID
MAPPER_INFO_LABELS_SELECT- 30
ABLE
44
MapBasic 12.0
Reference
45
A to Z MapBasic Language
Reference
This section describes the MapBasic language in detail. You will find both statements and function descriptions arranged alphabetically.
In this section:
Function and Statement Conventions . . . . . . . . . . . . . . .48
Function and Statement Descriptions . . . . . . . . . . . . . . .48
Abs( ) function
Purpose
Returns the absolute value of a number. You can call this function from the MapBasic window in MapInfo
Professional.
Syntax
Abs ( num_expr )
num_expr is a numeric expression.
48
MapBasic 12.0
Acos( ) function
Purpose
Returns the arc-cosine value of a number. You can call this function from the MapBasic window in
MapInfo Professional.
Syntax
Acos ( num_expr )
num_expr is a numeric expression between one and negative 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.
Reference
49
50
MapBasic 12.0
Reference
51
52
MapBasic 12.0
Reference
53
54
Function
Avg( col )
Count( * )
Max( col )
Min( col )
Sum( col )
Weighted average calculation that makes adjustments based on how much of an object is within
another object.
MapBasic 12.0
Reference
55
56
MapBasic 12.0
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.
Reference
57
58
MapBasic 12.0
Reference
59
Description
Legend Text Frame creates a text frame in the Legend Designer window.
If Text does not specify the Font clause, then the default font is used.
The Position clause controls the frame's position on the Legend Designer window. The upper left corner
of the Legend Designer window has the position 0, 0. Position values use paper units settings, such as
"in" (inches) or "cm" (centimeters) (see Set Paper Units statement). 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.
Example
Add Designer Text Window frontwindow()
Legend Text Frame
Text "This is My title" Font("Batang", 3, 12, 16711680)
See Also:
60
MapBasic 12.0
Reference
61
62
MapBasic 12.0
AdornmentInfo( ) function
Purpose
Returns information about adornments like scale bars. You can call this function from the MapBasic
window in MapInfo Professional.
Syntax
AdornmentInfo( window_id, attribute )
window_id is an integer window identifier. The window needs to be an adornment.
attribute is an integer code indicating what type of information to return. For values, see the table below:
Return Value
Float, smallint, integer, logical, pen, brush, font, or string, depending on the attribute parameter.
Description
There are several attributes that AdornmentInfo( ) can return. Codes are defined in MAPBASIC.DEF.
Reference
63
AdornmentInfo( ) function
Attribute setting
ID
ADORNMENT_INFO_TYPE
Integer.
Type of adornment: 0 (zero) for scale bar.
64
ADORNMENT_INFO_MAP_WINDOW- 2
ID
ADORNMENT_INFO_IS_FIXED_PO- 3
SITION
ADORNMENT_INFO_FIXED_POSI- 4
TION_X
ADORNMENT_INFO_FIXED_POSI- 5
TION_Y
ADORNMENT_INFO_FIXED_POSI- 6
TION_UNITS
ADORNMENT_INFO_DOCKED_PO- 7
SITION
ADORNMENT_INFO_DOCKED_OFF- 8
SET_X
ADORNMENT_INFO_DOCKED_OFF- 9
SET_Y
ADORNMENT_INFO_DOCKED_OFF- 10
SET_UNITS
ADORNMENT_INFO_BACKGROUND_PEN
11
ADORNMENT_INFO_BACKGROUND_BRUSH
12
ADORNMENT_INFO_SCALEBAR_TYPE
20
ADORNMENT_INFO_SCALEBAR_MAP_UNITS
21
ADORNMENT_INFO_SCALEBAR_PA- 22
PER_UNITS
Char. Paper units in the scale bar. For details about paper
units, see Set Paper Units statement.
ADORNMENT_INFO_SCALEBAR_BAR_LENGTH
23
ADORNMENT_INFO_SCALEBAR_BAR_DISPLAY_LENGTH
24
MapBasic 12.0
ID
ADORNMENT_INFO_SCALEBAR_BAR_HEIGHT
25
ADORNMENT_INFO_SCALEBAR_AUTO_SCALING
26
ADORNMENT_INFO_SCALEBAR_SHOW_CARTO_SCALE
27
ADORNMENT_INFO_SCALEBAR_BAR_PEN
28
ADORNMENT_INFO_SCALEBAR_BAR_BRUSH
29
Brush. The brush, fill style used to draw the scale bar.
ADORNMENT_INFO_SCALEBAR_BAR_FONT
30
ADORNMENT_INFO_SCALEBAR_BAR_DISPLAY_SCALE
31
ADORN32
MENT_INFO_SB_AUTOOFF_SCALE
ADORN33
MENT_INFO_SB_AUTOON_SCALE
ADORNMENT_INFO_SB_SCALE_STRING
34
ADORNMENT_INFO_SB_CARTO_VALUE
35
ADORNMENT_INFO_SB_CARTO_STRING
36
Example
print AdornmentInfo(MapperInfo(FrontWindow(), 201), 1)
Reference
65
66
MapBasic 12.0
1 for Main
2 for Drawing
3 for Tools
4 for Standard
5 for Database Management System (DBMS)
6 Web Services
7 Reserved
Reference
67
DrawMode dm_code ]
HelpMsg msg ]
ModifierKeys { On | Off } ]
{ Enable | Disable } ]
{ Check | Uncheck } ]
68
MapBasic 12.0
Reference
69
ID
Description
DM_CUSTOM_POINT
34
DM_CUSTOM_LINE
33
DM_CUSTOM_RECT
32
DM_CUSTOM_CIRCLE
30
DM_CUSTOM_ELLIPSE
31
DM_CUSTOM_POLYGON
35
DM_CUSTOM_POLYLINE
36
All of the draw modes except for DM_CUSTOM_POINT (34) 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 statement.
Note: MapBasic supports an additional draw mode that is not available to MapInfo Professional users.
If a custom ToolButton has the following Calling clause Calling M_TOOLS_SEARCH_POLYGON
(1733) then the tool allows the user to draw a polygon. When the user double-clicks to close the
polygon, MapInfo Professional 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
70
MapBasic 12.0
Reference
71
72
MapBasic 12.0
Reference
73
74
MapBasic 12.0
Reference
75
The Style clause must contain a list of definitions for the styles displayed in frame. You can only update
the Style type for a legend frame created with the NoRefresh keyword. You can update the Text of any
style. There is no way to add or remove styles from any type of frame.
Only the following clauses will be applied to thematic legends. Those are:
[ Position ( x, y ) [ Units paper_units ] ]
[ Columns number_of_columns ] |
[ Height frame_height [ Units paper_units ] ]
76
MapBasic 12.0
form:
Custom 2, 5:10, 1, 3, 4
Custom 2, 5:10, 1, 3:4 (same as above but also valid)
Custom 2, 5:10, 1 (same as above but also valid)
Long form:
Order Custom 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19,
Reference
77
Description
If Text does not specify the Font clause, then the default font is used.
78
MapBasic 12.0
Reference
79
List box, combo box: You may set which item is selected by using a numeric new_value.
Checkbox: You may set the checkbox (specify a value of 1) or clear it (value of zero).
Radio button: Setting a button's value to 1 selects that button from the radio group.
Symbol style button: You may assign a new symbol style (e.g., use the return value from the
MakeSymbol( ) function).
Pen style button: You may assign a new Pen value.
Brush style button: You may assign a new Brush value.
Font style button: You may assign a new Font value.
80
MapBasic 12.0
Reference
81
82
Menu Name
Define
ID
Description
File
M_FILE
File menu.
Edit
M_EDIT
Edit menu.
Search
M_SEARCH
Search menu.
Query
M_QUERY
Query menu.
Programs
M_PGM
Programs menu.
Tools
M_TOOLS
Tools menu.
Options
M_OPTIONS
Options menu.
Window
M_WINDOW
Window menu.
Help
M_HELP
Help menu.
Browse
M_BROWSE
MapBasic 12.0
Define
ID
Description
Map
M_MAP
Layout
M_LAYOUT
10
Graph
M_GRAPH
11
MapBasic
M_MAPBASIC
12
Redistrict
M_REDISTRICT
13
Objects
M_OBJECTS
14
Objects menu.
Table
M_TABLE
15
Table menu.
Menus 16 through 36 are shortcut menus, which appear if the user clicks with the right mouse button.
Table 2: ID Numbers for Shortcut Menus
Menu Name
Define
ID
Description
DefaultShortcut
M_SHORTCUT_DFLT
16
MapperShortcut
M_SHORTCUT_MAPPER
17
BrowserShortcut
M_SHORT18
CUT_BROWSER
LayoutShortcut
M_SHORTCUT_LAYOUT
GrapherShortcut
M_SHORT20
CUT_GRAPHER
CmdShortcut
M_SHORTCUT_CMD
21
RedistrictShortcut M_SHORTCUT_REDISTRICTER
22
The Redistricting shortcut menu; available when the Districts Browser is active.
LegendShortcut
M_SHORTCUT_LEGEND
23
GrapherShortcut
M_SHORTCUT_GRAPHTDG
24
Reference
19
83
Define
ID
Description
3DMapShortcut
M_SHORTCUT_3DMAP
25
MessageWinShort- M_SHORTcut
CUT_MSG_WIN
26
StatisticsWinShort- M_SHORTcut
CUT_STAT_WIN
27
AdornmentShort- M_SHORTcut
CUT_ADORNMENT
32
LcLayersShortcut M_SHORTCUT_LC_LAYERS
33
LcMapsShortcut
34
The menu you get when you right-click a Map node in the
layer list
LcGroupsShortcut M_SHORT35
CUT_LC_GROUPS
TableAdornment- M_SHORT36
Shortcut
CUT_TABLEADORNMENT
M_SHORTCUT_LC_MAPS
Define
ID
Description
3DWindow
M_3DMAP
28
3D Map window.
Graph
M_GRAPHTDG
29
Graph menu.
Legend
M_LEGEND
31
Legend menu.
When altering a Custom menu (even if you create it with an Custom ID, such as 999), you are required
to use the Custom menuname, not the Custom ID, to alter it.
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
84
MapBasic 12.0
Reference
85
86
MapBasic 12.0
Reference
87
88
MapBasic 12.0
ID
OBJ_INFO_PEN
OBJ_INFO_SYMBOL
OBJ_INFO_BRUSH
OBJ_INFO_SMOOTH
Reference
89
ID
OBJ_INFO_FRAMEWIN
OBJ_INFO_FRAMETITLE
OBJ_INFO_TEXTFONT
OBJ_INFO_TEXTSTRING
OBJ_INFO_TEXTSPACING
OBJ_INFO_TEXTJUSTIFY
OBJ_INFO_TEXTARROW
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
Dim
x =
y =
o_cable As Object
x, y As Float
ObjectGeography(o_cable, OBJ_GEO_LINEENDX)
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.
90
MapBasic 12.0
ID
OBJ_GEO_MINX
OBJ_GEO_MINY
OBJ_GEO_MAXX
OBJ_GEO_MAXY
OBJ_GEO_ARCBEGANGLE
OBJ_GEO_ARCENDANGLE
OBJ_GEO_LINEBEGX
OBJ_GEO_LINEBEGY
OBJ_GEO_LINEENDX
OBJ_GEO_LINEENDY
OBJ_GEO_POINTX
OBJ_GEO_POINTY
OBJ_GEO_ROUNDRADIUS
OBJ_GEO_TEXTLINEX
OBJ_GEO_TEXTLINEY
OBJ_GEO_TEXTANGLE
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 statement
and the Create Region statement. 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 statement or a 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
Reference
91
92
MapBasic 12.0
Reference
93
94
MapBasic 12.0
ApplicationDirectory$( ) function
Purpose
Returns a string containing the path from which the current MapBasic application is executing. You can
call this function from the MapBasic window in MapInfo Professional.
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$( ) function, ApplicationName$( ) function
Reference
95
ApplicationName$( ) function
ApplicationName$( ) function
Purpose
Returns a string containing the name of the current MapBasic application that is running. You can call
this function from the MapBasic window in MapInfo Professional.
Syntax
ApplicationName$( )
Return Value
String expression representing the name of the MapBasic program.
Description
By calling the ApplicationName$( ) function from within a compiled MapBasic application, you can determine the name of the running application. If no application is running (if you call the function by typing
into the MapBasic window), then ApplicationName$( ) returns an empty string.
To determine the path from which the current MapBasic application is executing call the ApplicationDirectory$( ) function.
Example
Dim sAppName As String
sAppName = ApplicationName$( )
' At this point, sAppName might look like this:
'
' "Test.MBX"
See Also:
ApplicationDirectory$( ) function
Area( ) function
Purpose
Returns the geographical area of an Object. You can call this function from the MapBasic window in
MapInfo Professional.
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").
96
MapBasic 12.0
AreaOverlap( ) function
Purpose
Returns the area resulting from the overlap of two closed objects. You can call this function from the
MapBasic window in MapInfo Professional.
Syntax
AreaOverlap( object1, object2 )
object1 and object2 are closed objects.
Reference
97
Asc( ) function
Return Value
A float value representing the area (in MapBasic's current area units) of the overlap of the two objects.
Restrictions
AreaOverlap( ) only works on closed objects. If both objects are not closed (such as points and lines),
then you may see an error message. Closed objects are objects that can produce an area, such as regions
(polygons).
See Also:
Overlap( ) function, ProportionOverlap( ) function, Set Area Units statement
Asc( ) function
Purpose
Returns the character code for the first character in a string expression. You can call this function from
the MapBasic window in MapInfo Professional.
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
98
MapBasic 12.0
Asin( ) function
Purpose
Returns the arc-sine value of a number. You can call this function from the MapBasic window in MapInfo
Professional.
Syntax
Asin( num_expr )
num_expr is a numeric expression from one to negative 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 negative one, the expression num_expr should represent a
value no larger than one (1) and no smaller than negative one (-1).
Example
Include "MAPBASIC.DEF"
Dim x, y As Float
x = 0.5
y = Asin(x) * RAD_2_DEG
' y will now be equal to 30,
' since the sine of 30 degrees is 0.5
See Also:
Acos( ) function, Atn( ) function, Cos( ) function, Sin( ) function, Tan( ) function
Reference
99
Ask( ) function
Ask( ) function
Purpose
Displays a dialog box, asking the user a yes or no (OK or Cancel) question. You can call this function
from the MapBasic window in MapInfo Professional.
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?" While the length of the
prompt string passed to the Ask function can be approximately 2000 characters long,only the first 299
will display in the dialog.
The dialog box 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 box (e.g., by pressing the Esc 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 box 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 statement, Note statement, Print statement
100
MapBasic 12.0
Atn( ) function
Purpose
Returns the arc-tangent value of a number. You can call this function from the MapBasic window in
MapInfo Professional.
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
val = Atn(1) * RAD_2_DEG
'val is now 45, since the
'Arc tangent of 1 is 45 degrees
See Also:
Acos( ) function, Asin( ) function, Cos( ) function, Sin( ) function, Tan( ) function
AutoLabel statement
Purpose
Draws labels in a Map window, and stores the labels in the Cosmetic layer. You can issue this statement
from the MapBasic window in MapInfo Professional.
Syntax
AutoLabel
[ Window window_id ]
Reference
101
Beep statement
[ { 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 and the Layer clause,
all layers are labeled.
The Overlap clause controls whether MapInfo Professional draws labels that overlap other labels. This
setting defaults to Off (MapInfo Professional will not draw overlapping labels). To force MapInfo Professional to draw a label for every map object, regardless of whether the labels overlap, specify Overlap
On. The Duplicates clause controls whether MapInfo Professional 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 statement
Beep statement
Purpose
Makes a beeping sound. You can issue this statement from the MapBasic window in MapInfo Professional.
Syntax
Beep
Description
The Beep statement sends a sound to the speaker.
102
MapBasic 12.0
Browse statement
Purpose
Opens a new Browser window. You can issue this statement from the MapBasic window in MapInfo
Professional.
Syntax
Browse expression_list From table
[ Position ( x, y ) [ Units paper_units ] ]
[ Width window_width [ Units paper_units ] ]
[ Height window_height [ Units paper_units ] ]
[ Row n ]
[ Column n ]
[ Min | Max ]
expression_list is either an asterisk or a comma-separated list of column expressions.
table is a string representing the name of an open table.
x, y specifies the position of the upper left corner of the Browser, in paper_units.
paper_units is a string representing a paper unit name (for example, "cm" for centimeters).
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 the 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. For details about paper units, see Set Paper Units statement. The y
coordinate specifies the distance from the top of the MapInfo Professional 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, MapInfo Professional 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 Professional. Conversely, if the Browse statement
includes the Min keyword, the Browser window is minimized immediately.
Reference
103
BrowserInfo( ) function
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 statement, Set Window statement
BrowserInfo( ) function
Purpose
Returns information about a Browser window, such as: the total number of rows or columns in the Browser
window; or the row number, column number, or value contained in the current cell. You can call this
function from the MapBasic window in MapInfo Professional.
Syntax
BrowserInfo( window_id, attribute )
window_id is an integer window identifier.
attribute is an integer code indicating what type of information to return. For values, see the table later
in this description.
Return Value
Float, logical, or string depending on the attribute parameter.
104
MapBasic 12.0
ID
Return Value
BROWSER_INFO_NROWS
BROWSER_INFO_NCOLS
BROWSER_INFO_CURRENT_ROW 3
BROWSER_INFO_CURRENT_COLUMN
BROWSER_INFO_CURRENT_CELL_VALUE
Error Conditions
ERR_BAD_WINDOW (590) error generated if parameter is not a valid window number.
ERR_FCN_ARG_RANGE (644) error generated if an argument is outside of the valid range.
ERR_WANT_BROWSER_WIN (312) error generated if window id is not a Browser window.
See Also:
FrontWindow( ) function, WindowID( ) function
Brush clause
Purpose
Specifies a fill style for graphic objects. You can use this clause in the MapBasic window in MapInfo
Professional.
Syntax
Brush brush_expr
brush_expr is a Brush expression, such as MakeBrush( pattern, fgcolor, bgcolor ). (See MakeBrush(
) function for more information.) or a Brush variable.
Reference
105
Brush clause
Description
The Brush clause specifies a brush stylein 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 statement, 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 statement), 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
foreground color
background color
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 box.
To specify a transparent background when calling the MakeBrush( ) function specify -1 as the background color.
The available patterns appear as follows. Pattern 2 produces a solid fill; pattern 1 produces no fill.
106
MapBasic 12.0
For a comprehensive list of fill patterns, see the MapInfo Professional Helplaunch MapInfo Professional
and select Help > MapInfo Professional Help Topics and then search for MapInfo Professional Fill
Pattern Table.
See Also:
CurrentBrush( ) function, MakeBrush( ) function, Pen clause, Font clause, Symbol clause
Buffer( ) function
Purpose
Returns a region object that represents a buffer region (the area within a specified buffer distance of an
existing object). You can call this function from the MapBasic window in MapInfo Professional.
Reference
107
ButtonPadInfo( ) function
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 statement As Buffer. 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 Cartesian 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 statement
ButtonPadInfo( ) function
Purpose
Returns information about a ButtonPad. You can call this function from the MapBasic window in MapInfo
Professional.
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.
108
MapBasic 12.0
ID
ButtonPadInfo( ) returns:
BTNPAD_INFO_FLOATING
BTNPAD_INFO_WIDTH
BTNPAD_INFO_NBTNS
BTNPAD_INFO_X
BTNPAD_INFO_Y
BTNPAD_INFO_WINID
BTNPAD_INFO_DOCK_POSITION
BTNPAD_INFO_DOCK_NONE (0)
BTNPAD_INFO_DOCK_LEFT (1)
BTNPAD_INFO_DOCK_TOP (2)
BTNPAD_INFO_DOCK_RIGHT (3)
BTNPAD_INFO_DOCK_BOTTOM (4)
Example
Include "mapbasic.def"
If ButtonPadInfo("Main", BTNPAD_INFO_FLOATING) Then
'...then the Main pad is floating; now let's dock it.
Alter ButtonPad "Main" ToolbarPosition(0,0) Fixed
End If
See Also:
Alter ButtonPad statement
Reference
109
Call statement
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...End Sub statement). Alternately, a program running under MapInfo Professional 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 Sub 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 byreference 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
110
MapBasic 12.0
CartesianArea( ) function
Purpose
Returns the area as calculated in a flat, projected coordinate system using a Cartesian algorithm. You
can call this function from the MapBasic window in MapInfo Professional.
Syntax
CartesianArea( 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").
Reference
111
CartesianBuffer( ) function
Return Value
Float
Description
The CartesianArea( ) function returns the Cartesian 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 data is 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 Select statement, as shown in the following
example.
Select lakes, CartesianArea(obj, "sq km")
From lakes Into results
See Also:
Area( ) function, SphericalArea( ) function
CartesianBuffer( ) function
Purpose
Returns a region object that represents a buffer region (the area within a specified buffer distance of an
existing object). You can call this function from the MapBasic window in MapInfo Professional.
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.
112
MapBasic 12.0
CartesianConnectObjects( ) function
Purpose
Returns an object representing the shortest or longest distance between two objects. You can call this
function from the MapBasic window in MapInfo Professional.
Syntax
CartesianConnectObjects( object1, object2, min )
object1 and object2 are object expressions.
min is a logical expression where TRUE calculates the minimum distance between the objects, and
FALSE calculates the maximum distance between objects.
Reference
113
CartesianDistance( ) function
Return Value
This statement returns a single section, two-point Polyline object representing either the closest distance
(min == TRUE) or farthest distance (min == FALSE) between object1 and object2.
Description
One point of the resulting Polyline object is on object1 and the other point is on object2. Note that the
distance between the two input objects can be calculated using the ObjectLen( ) function. If there are
multiple instances where the minimum or maximum distance exists (e.g., the two points returned are
not uniquely the shortest distance and there are other points representing "ties") then these functions
return one of the instances. There is no way to determine if the object returned is uniquely the shortest
distance.
CartesianConnectObjects( ) returns a Polyline object connecting object1 and object2 in the shortest
(min == TRUE) or longest (min == FALSE) way using a cartesian calculation method. If the calculation
cannot be done using a cartesian distance method (e.g., if the MapBasic Coordinate System is Lat/Long),
then this function will produce an error.
CartesianDistance( ) function
Purpose
Returns the distance between two locations. You can call this function from the MapBasic window in
MapInfo Professional.
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 Set Distance Units statement for the
list of available unit names.
The CartesianDistance( ) function always returns a value using a cartesian algorithm. A value of -1 is
returned for data that is in a Latitude/Longitude coordinate system, since Latitude/Longitude data is not
projected and not cartesian.
114
MapBasic 12.0
CartesianObjectDistance( ) function
Purpose
Returns the distance between two objects. You can call this function from the MapBasic window in
MapInfo Professional.
Syntax
CartesianObjectDistance( object1, object2, unit_name )
object1 and object2 are object expressions.
unit_name is a string representing the name of a distance unit.
Return Value
Float
Description
CartesianObjectDistance( ) returns the minimum distance between object1 and object2 using a cartesian
calculation method with the return value in unit_name. If the calculation cannot be done using a cartesian
distance method (e.g., if the MapBasic Coordinate System is Lat/Long), then this function will produce
an error.
CartesianObjectLen( ) function
Purpose
Returns the geographic length of a line or polyline object. You can call this function from the MapBasic
window in MapInfo Professional.
Reference
115
CartesianOffset( ) function
Syntax
CartesianObjectLen( 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 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 coordinate 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( ) function, CartesianObjectLen( ) function, ObjectLen( ) function
CartesianOffset( ) function
Purpose
Returns a copy of the input object offset by the specified distance and angle using a Cartesian DistanceType. You can call this function from the MapBasic window in MapInfo Professional.
Syntax
CartesianOffset( object, angle, distance, units )
object is the object being offset.
angle is the angle to offset the object.
distance is the distance to offset the object.
units is a string representing the unit in which to measure distance.
116
MapBasic 12.0
CartesianOffsetXY( ) function
Purpose
Returns a copy of the input object offset by the specified X and Y offset values using a cartesian DistanceType. You can call this function from the MapBasic window in MapInfo Professional.
Syntax
CartesianOffsetXY( object, xoffset, yoffset, units )
object is the object being offset.
xoffset and yoffset are the distance along the x and y axes to offset the object.
units is a string representing the unit in which to measure distance.
Return Value
Object
Reference
117
CartesianPerimeter( ) function
Description
This function produces a new object that is a copy of the input object offset by xoffset along the X-axis
and yoffset along the Y-axis. The unit string, similar to that used for ObjectLen( ) function or Perimeter(
) function, is the unit for the distance values. The DistanceType used is Cartesian. If the coordinate
system of the input object is Lat/Long, an error will occur, since Cartesian DistanceTypes are not valid
for Lat/Long. This is signified by returning a NULL object. The coordinate system used is the coordinate
system of the input object.
There are some considerations for Spherical measurements that do not hold for Cartesian measurements.
If you move an object that is in Lat/Long, the shape of the object remains the same, but the area of the
object will change. This is because you are picking one offset delta in degrees, and the actual measured
distance for a degree is different at different locations.
For the Offset functions, the actual offset delta is calculated at some fixed point on the object (e.g., the
center of the bounding box), and then that value is converted from the input units into the coordinate
system's units. If the coordinate system is Lat/Long, the conversion to degrees uses the fixed point. The
actual converted distance measurement could vary at different locations on the object. The distance
from the input object and the new offset object is only guaranteed to be exact at the single fixed point
used.
Example
CartesianOffset(Rect, 45, 100, "mi")
See Also:
CartesianOffset( ) function
CartesianPerimeter( ) function
Purpose
Returns the perimeter of a graphical object. You can call this function from the MapBasic window in
MapInfo Professional.
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.
118
MapBasic 12.0
Centroid( ) function
Purpose
Returns the centroid (center point) of an object. You can call this function from the MapBasic window
in MapInfo Professional.
Syntax
Centroid( obj_expr )
obj_expr is an object expression.
Return Value
Point object
Reference
119
CentroidX( ) function
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:
Alter Object statement, CentroidX( ) function, CentroidY( ) function
CentroidX( ) function
Purpose
Returns the x-coordinate of the centroid of an object. You can call this function from the MapBasic
window in MapInfo Professional.
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.).
120
MapBasic 12.0
CentroidY( ) function
Purpose
Returns the y-coordinate of the centroid of an object. You can call this function from the MapBasic
window in MapInfo Professional.
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.
Reference
121
CharSet clause
Example
Dim y As Float
Open Table "world"
Fetch First From world
y = CentroidY(world.obj)
See Also:
Centroid( ) function, CentroidX( ) function, Set CoordSys statement
CharSet clause
Purpose
Specifies which character set MapBasic uses for interpreting character codes.
Note: See the MapInfo Professional User Guide documentation for changes affecting this clause.
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 the Open File statement, 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.
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 (for example, 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
122
MapBasic 12.0
Comments
"Neutral"
"ISO8859_1"
"ISO8859_2"
"ISO8859_3"
"ISO8859_4"
"ISO8859_5"
"ISO8859_6"
"ISO8859_7"
"ISO8859_8"
"ISO8859_9"
"PackedEUCJapanese"
"WindowsLatin2"
"WindowsArabic"
"WindowsCyrillic"
"WindowsGreek"
"WindowsHebrew"
"WindowsTurkish"
"WindowsTradChinese"
"WindowsSimpChinese"
"WindowsJapanese"
"WindowsKorean"
"CodePage437"
"CodePage850"
"CodePage852"
"CodePage855"
"CodePage857"
Reference
123
ChooseProjection$( ) function
Character Set
Comments
"CodePage860"
"CodePage861"
"CodePage863"
"CodePage864"
"CodePage865"
"CodePage869"
"LICS"
"LMBCS"
Note: You never need to specify a CharSet clause in an Open Table statement. Each table's .TAB
file contains information about the character set used by the table. When opening a table, MapInfo
Professional reads the character set information directly from the .TAB file, then automatically
performs any necessary character translations.
To force MapInfo Professional to save a table in a specific character set, include a CharSet clause in
the Commit Table statement.
See Also:
Commit Table statement, Create Table statement, Export statement, Open File statement, Register
Table statement
ChooseProjection$( ) function
Purpose
Displays the Choose Projection dialog box and returns the coordinate system selected by the user.
You can call this function from the MapBasic window in MapInfo Professional.
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 box 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 box is displayed. If
false, then the dialog box is not displayed and the default boundary is used.
124
MapBasic 12.0
Chr$( ) function
Purpose
Returns a one-character string corresponding to a specified character code. You can call this function
from the MapBasic window in MapInfo Professional.
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.
Reference
125
126
MapBasic 12.0
Example
Open File "cxdata.txt" For INPUT As #1
'
' read from the file... then, when done:
'
Close File #1
See Also:
Open File statement
Reference
127
128
MapBasic 12.0
Window description
Help
Info
LayerControl
Legend
MapBasic
The MapBasic window. You can also refer to this window by its define
code: WIN_MAPBASIC.
Message
The Message window (which appears when you issue a Print statement). Its define code: WIN_MESSAGE.
MoveMapTo
Ruler
Statistics
TableList
The Table List window. Its' define code is WIN_TABLE_LIST. In an integrated mapping application this refers to the modal version.
Note: The window IDs for Table List, Layer Control, and Move Map To are ignored by the Set Window
statement, WindowInfo( ) function, and WindowID( ) function.
Reference
129
ColumnInfo( ) function
Saving Themes and Cosmetic Objects
The user may want to save thematic layers or cosmetic objects before closing the window. To prompt
the user to save themes or cosmetic objects, include the Interactive keyword.
If you omit the Interactive keyword, the Close Window statement will not prompt the user to save
themes or cosmetic objects. If you include the Interactive keyword, dialog boxes will prompt the user
to save themes and/or cosmetic objects, if such prompts are appropriate. (The user will not be prompted
if the window has no themes or cosmetic objects.)
Example
Close Window Legend
See Also:
Open Window statement, Print statement, Set Window statement
ColumnInfo( ) function
Purpose
Returns information about a column in an open table. You can call this function from the MapBasic
window in MapInfo Professional.
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 this table.
130
attribute setting
ID
ColumnInfo( ) returns:
COL_INFO_NAME
MapBasic 12.0
ID
ColumnInfo( ) returns:
COL_INFO_NUM
COL_INFO_TYPE
COL_INFO_WIDTH
COL_INFO_DECPLACES
COL_INFO_INDEXED
COL_INFO_EDITABLE
If the ColumnInfo( ) function call specifies COL_INFO_TYPE as its attribute parameter, MapBasic returns
one of the values from the table below:
ColumnInfo( ) returns:
ID
COL_TYPE_CHAR
Character.
COL_TYPE_DECIMAL
Fixed-point decimal.
COL_TYPE_INTEGER
Integer (4-byte).
COL_TYPE_SMALLINT
COL_TYPE_DATE
Date.
COL_TYPE_LOGICAL
COL_TYPE_GRAPHIC
COL_TYPE_FLOAT
Floating-point decimal.
COL_TYPE_TIME
37
Time.
COL_TYPE_DATETIME
38
DateTime.
The codes listed in both of the above tables are defined in the standard MapBasic definitions file, MAPBASIC.DEF. Your program must include "MAPBASIC.DEF" if you intend to reference these codes.
Error Conditions
ERR_TABLE_NOT_FOUND (405) error generated if the specified table is not available.
ERR_FCN_ARG_RANGE (644) error generated if an argument is outside of the valid range.
Example
Include "MAPBASIC.DEF"
Dim s_col_name As String, i_col_type As SmallInt
Open Table "world"
Reference
131
Combine( ) function
s_col_name = ColumnInfo("world","col1",COL_INFO_NAME)
i_col_type = ColumnInfo("world","col1",COL_INFO_TYPE)
See Also:
NumCols( ) function, TableInfo( ) function
Combine( ) function
Purpose
Returns a region or polyline representing the union of two objects. The objects cannot be Text objects.
You can call this function from the MapBasic window in MapInfo Professional.
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( ) 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:
Input Object Type
OutputObject Type
Point or MultiPoint
Point or MultiPoint
MultiPoint
Linear
Polyline
Closed
Region
132
MapBasic 12.0
CommandInfo( ) function
Purpose
Returns information about recent events. You can call this function from the MapBasic window in MapInfo
Professional.
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 Professionalfor 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:
attribute code
ID
CMD_INFO_DLG_OK
CMD_INFO_STATUS
Reference
133
CommandInfo( ) function
Within a Custom Menu or Dialog Handler
When you call CommandInfo( ) from within the handler procedure for a custom menu command or a
custom dialog box, the attribute parameter can be one of these codes:
attribute code
ID
CMD_INFO_DLG_DBL
Logical value: TRUE if the user double-clicked on a ListBox or MultiListBox control within a custom dialog box.
This call is only valid within the handler procedure of a
custom dialog box.
CMD_INFO_MENUITEM
ID
CMD_INFO_SELTYPE
CMD_INFO_ROWID
CMD_INFO_INTERRUPT
From within the RemoteMsgHandler procedure, the RemoteQueryHandler( ) function, or the RemoteMapGenHandler procedure:
attribute code
ID
CMD_INFO_MSG
134
MapBasic 12.0
ID
CMD_INFO_WIN
ID
CMD_INFO_TASK_SWITCH
ID
CMD_INFO_X or CMD_INFO_Y
CMD_INFO_FIND_RC
CMD_INFO_FIND_ROWID
ID
CMD_INFO_CUSTOM_OBJ
CMD_INFO_X
Reference
135
CommandInfo( ) function
attribute code
ID
CMD_INFO_Y
CMD_INFO_SHIFT
Logical value: TRUE if the user held down the Shift key
while clicking.
CMD_INFO_CTRL
Logical value: TRUE if the user held down the Ctrl key
while clicking.
CMD_INFO_X2
CMD_INFO_Y2
CMD_INFO_TOOLBTN
* The CommandInfo( ) function ignores any clicks made in the top-left corner of a Browser windowabove
the select column and to the left of the column headers. It also ignores clicks made beyond the last
column or row.
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:
136
MapBasic 12.0
ID
CMD_INFO_HL_WINDOW_ID
17
CMD_INFO_HL_TABLE_NAME
18
CMD_INFO_HL_ROWID
19
CMD_INFO_HL_LAYER_ID
20
CMD_INFO_HL_FILE_NAME
21
See Also:
FrontWindow( ) function, SelectionInfo( ) function, Set Command Info statement, WindowInfo( )
function
Reference
137
138
MapBasic 12.0
Reference
139
Typically this dialog box contains a list of all columns that contain indeterminate types. In this query,
there is only one.
Click OK to display the Set Field Properties dialog box.
140
MapBasic 12.0
Use this dialog box to select the type information for this column. If there is more than one indeterminate
type, you can set each of these types one at a time. If there are columns whose type is already defined,
you will not be able to edit that information.
Click OK to save your query.
Automatic NoCollision
In the event of a conflict, MapInfo Professional 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, MapInfo Professional saves the local updates. (This is analogous to ignoring
conflicts entirely.)
Automatic DiscardUpdates
In the event of a conflict, MapInfo Professional 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 specified
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.
Reference
141
ConnectObjects( ) function
A spatial index will be created on the Object column if one is present. The supported databases include
Oracle, SQL Server, IIS (SQL Server Spatial, Universal Server), and Microsoft Access. However, to save
a table with a spatial geometry/object, (including saving a point-only table) SpatialWare is required for
SQL Server, 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 Table 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 statement
ConnectObjects( ) function
Purpose
Returns an object representing the shortest or longest distance between two objects. You can call this
function from the MapBasic window in MapInfo Professional.
Syntax
ConnectObjects( object1, object2, min )
object1 and object2 are object expressions.
min is a logical expression where TRUE calculates the minimum distance between the objects, and
FALSE calculates the maximum distance between objects.
Return Value
This statement returns a single section, two-point Polyline object representing either the closest distance
(min == TRUE) or farthest distance (min == FALSE) between object1 and object2.
Description
One point of the resulting Polyline object is on object1 and the other point is on object2. Note that the
distance between the two input objects can be calculated using the ObjectLen( ) function. If there are
multiple instances where the minimum or maximum distance exists (e.g., the two points returned are
142
MapBasic 12.0
Continue statement
Purpose
Resumes the execution of a MapBasic program (following a Stop statement). You can issue this
statement from the MapBasic window in MapInfo Professional.
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.
Reference
143
144
MapBasic 12.0
Reference
145
146
MapBasic 12.0
Reference
147
148
MapBasic 12.0
Reference
149
64
If the user clicks or double-clicks on the ListBox control, MapBasic calls the sub procedure "listbox_handler." The procedure calls the CommandInfo( ) function to determine whether the user clicked or doubleclicked. If the user double-clicked, the procedure issues a Dialog Remove statement to dismiss the
dialog box. If not for the Dialog Remove statement, the dialog box would remain on the screen until
the user clicked OK or Cancel.
Sub listbox_handler
Dim i As SmallInt
' First, since user clicked on the name of a view,
' we can enable the OK button and the Delete button.
Alter Control 2 Enable
Alter Control 3 Enable
If CommandInfo(CMD_INFO_DLG_DBL) = TRUE Then
' ...then the user DOUBLE-clicked.
' see which list item the user clicked on.
i = ReadControlValue(1) ' read user's choice.
Dialog Remove
Call go_to_view(i) ' act on user's choice.
End If
End Sub
MapBasic calls the handler procedure whether the user clicks or double-clicks. The handler procedure
must check to determine whether the event was a single- or double-click.
See Also:
Alter Control statement, Dialog statement, ReadControlValue( ) function, CommandInfo( ) function
150
MapBasic 12.0
ControlPointInfo( ) function
Purpose:
Returns raster and geographic control point coordinates for an image table. The geographic coordinates
will be in the current MapBasic coordinate system.
Reference
151
ID
ControlPointInfo() returns:
RASTER_CONTROL_POINT_X
RASTER_CONTROL_POINT_Y
GEO_CONTROL_POINT_X
GEO_CONTROL_POINT_Y
TAB_GEO_CONTROL_POINT_X
TAB_GEO_CONTROL_POINT_Y
152
MapBasic 12.0
ID control_ID ]
Calling handler ]
Title { str_expr | From Variable str_array_var } ]
Value i_selected ]
Into i_variable ]
Disable ]
Reference
153
154
MapBasic 12.0
Reference
155
ConvertToPline( ) function
ConvertToPline( ) function
Purpose
Returns a polyline object that approximates the shape of another object. You can call this function from
the MapBasic window in MapInfo Professional.
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:
Objects Enclose statement
ConvertToRegion( ) function
Purpose
Returns a region object that approximates the shape of another object. You can call this function from
the MapBasic window in MapInfo Professional.
Syntax
ConvertToRegion( object )
object is the object to convert; may not be a point, line, or text object.
Return Value
A region object
156
MapBasic 12.0
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 convexno interior angle can be greater than 180 degrees. You can call this function
from the MapBasic window in MapInfo Professional.
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)
Reference
157
CoordSys clause
See Also:
Create Object statement
CoordSys clause
Purpose
Specifies a coordinate system. You can use this clause in the MapBasic window in MapInfo Professional
(see CoordSys Earth and NonEarth Projection, CoordSys Layout Units, CoordSys Table, and
CoordSys Window).
158
MapBasic 12.0
Reference
159
CoordSys clause
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 MapInfo Professional 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 MapInfo Professional to display the Map window without any projection.
Set Map CoordSys Earth
The following example opens the table World, then uses a Commit Table 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
Table world As "RWORLD.TAB"
CoordSys Earth Projection 12, 12, "m", 0.
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
y1 = 0.19x + 2.81y - 20318.0
In this transformation, (x1, y1) represents the DCS derived coordinates, and (x, y) represents the UTM
Zone 10 base coordinates. If the DCS coordinates are measured in feet, the CoordSys clause for DCS
would be as follows:
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
160
MapBasic 12.0
CoordSys Table
Syntax
CoordSys Table tablename
tablename is the name of an open table.
Description
Use CoordSys Table to refer to the coordinate system in which a table has been saved.
CoordSys Window
Syntax
CoordSys Window window_id
window_id is an integer window identifier corresponding to a Map or Layout window.
Description
Use CoordSys Window to refer to the coordinate system already in use in a window.
Examples
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
See Also:
Commit Table statement, Set CoordSys statement, Set Map statement
CoordSysName$( ) function
Purpose
Returns coordinate system name string from MapBasic Coordinate system clause. You can call this
function from the MapBasic window in MapInfo Professional.
Reference
161
CoordSysStringToEPSG( ) function
Syntax
CoordSysName$ ( string )
Return Value
String
Example
Note CoordSysName$("Coordsys Earth Projection 1, 62")
Returns this string in the MapInfo dialog box:
Longitude / Latitude (NAD 27 for Continental US)
Note: If a coordinate system name does not exist in the MapInfow.prj file, such as when the map is in
NonEarth system in Survey Feet, then function will return an empty string.
Note CoordSysName$("CoordSys NonEarth Units " + """survey ft""" +
"Bounds (0, 0) (10, 10)")
If an invalid CoordSys clause is passed such as this (using invalid units):
Note CoordSysName$("CoordSys Earth Projection 3, 74, " + """foo""" +
"-90, 42, 42.7333333333, 44.0666666667, 1968500, 0")
Then an Error regarding the Invalid Coordinate System should be returned (Error #727).
Invalid Coordinate System: CoordSys Earth Projection <content>
CoordSysStringToEPSG( ) function
Purpose
Converts a MapBasic Coordinate System clause into an EPSG integer value for use with any MapBasic
function or statement. You can call this function from the MapBasic window in MapInfo Professional.
Syntax
CoordSysStringToEPSG ( coordsys_string )
coordsys_string is a MapBasic CoordSys clause. EPSG (European Petroleum Survey Group) value is
an integer value; for example, CoordSys Clause of "Earth Projection 1, 104" will return an EPSG code
of 4326. For a complete list of EPSG codes used with MapInfo Professional see the MAPINFOW.PRJ
file in your MapInfo Professional installation. The EPSG codes are identified by a "\p" followed by a
number.
Return Value
Integer. If no EPSG value is found, it returns -1.
Description
The CoordSysStringToEPSG( ) function is used to convert a MapBasic CoordSys clause into an integer
EPSG value.
162
MapBasic 12.0
CoordSysStringToPRJ$( ) function
Purpose
Converts MapBasic Coordinate System clause into an PRJ string. PRJ string format is used to describe
MapInfo Coordinate Systems in mapinfow.prj file. You can call this function from the MapBasic window
in MapInfo Professional.
Syntax
CoordSysStringToPRJ$( coordsys_string )
coordsys_string is a MapBasic CoordSys clause. PRJ string is an alternative definition of Coordinate
System used in the mapinfow.prj file; for example, CoordSys Clause of "Earth Projection 1, 104" will return
a PRJ string of "1,104".
Return Value
string
Description
The CoordSysStringToPRJ$( ) function is used to convert a MapBasic CoordSys clause into an integer
EPSG value.
Example
The following example displays PRJ string for Earth Projection 1, 104 Coordinate System.
print CoordSysStringToPRJ$("Earth Projection 1, 104")
See Also:
CoordSys clause
CoordSysStringToWKT$( ) function
Purpose
Converts a CoordSys clause into an WKT (Well-Known Text) string value. You can call this function
from the MapBasic window in MapInfo Professional.
Reference
163
Cos( ) function
Syntax
CoordSysStringToWKT$( coordsys_string )
coordsys_string is a CoordSys clause.
Return Value
WKT string. If no WKT string value is found, returns an empty string.
Example
The following example:
Print coordsysstringtowkt$("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")
produces the following WKT string:
PROJCS["_MI_0",GEOGCS[ ,DATUM["North_American_Datum_1983",SPHEROID["Geodet
ic Reference System of
1980",6378137,298.2572221009113],AUTHORITY["EPSG","6269"]],PRIMEM["Greenw
ich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Transverse_Mercato
r"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",123],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],P
ARAMETER["false_northing",0],UNIT["METER",1]]
See Also:
CoordSys clause
Cos( ) function
Purpose
Returns the cosine of a number. You can call this function from the MapBasic window in MapInfo Professional.
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( ) is between one (1) and negative one (-1).
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.
164
MapBasic 12.0
Example
Include "MAPBASIC.DEF"
Dim x, y As Float
x = 60 * DEG_2_RAD
y = Cos(x)
' y will now be equal to 0.5
' since the cosine of 60 degrees is 0.5
See Also:
Acos( ) function, Asin( ) function, Atn( ) function, Sin( ) function, Tan( ) function
BarType type ]
Ground Units distance_units ]
Display Units paper_units ]
BarLength paper_length ]
BarHeight paper_height ]
BarStyle [ Pen .... ] [ Brush ... ] [ Font ... ] ]
Scale [ { On | Off } ] ]
Auto [ { On | Off } ] ]
Reference
165
(0)
(1)
(2)
(3)
(4)
(5)
(6)
(7)
(8)
(x, y) in the Offset clause is measured from the anchor position. For example, if the win_position is
ADORNMENT_INFO_MAP_POS_TL (top left), then the x is to the right and the y is down. If the
win_position is ADORNMENT_INFO_MAP_POS_BR, then the x position is left and the y position is up.
In the center left (ADORNMENT_INFO_MAP_POS_CL) and center right (ADORNMENT_INFO_MAP_POS_CR), the y offset is ignored. In the center position (ADORNMENT_INFO_MAP_POS_CC), the offset is ignored completely (both x and y). In the top center (ADORNMENT_INFO_MAP_POS_TC) and bottom center (ADORNMENT_INFO_MAP_POS_BC) positions, the
x offset is ignored. For ADORNMENT_INFO_MAP_POS_ defines, see win_position.
win_width and win_height define the size of the adornment. MapInfo Professional ignores these parameters if this is a scale bar adornment, because scale bar adornment size is determined by scale bar
specific items, such as BarLength.
type specify one of the following codes; codes are defined in the MAPBASIC.DEF file.
SCALEBAR_INFO_BARTYPE_CHECKEDBAR
SCALEBAR_INFO_BARTYPE_SOLIDBAR
SCALEBAR_INFO_BARTYPE_LINEBAR
SCALEBAR_INFO_BARTYPE_TICKBAR
(0)
(1)
(2)
(3)
166
distance value
Unit Represented
"ch"
chains
"cm"
centimeters
"ft"
feet (also called International Feet; one International Foot equals exactly 30.48
cm)
"in"
inches
"km"
kilometers
"li"
links
MapBasic 12.0
Unit Represented
"m"
meters
"mi"
miles
"mm"
millimeters
"nmi"
"rd"
rods
"survey ft"
U.S. survey feet (used for 1927 State Plane coordinates; one U.S. Survey Foot
equals exactly 12/39.37 meters, or approximately 30.48006 cm)
"yd"
yards
paper_length a value in paper_units to specify how long the scale bar will be displayed. Specify the
length of the scale bar to a maximum of 34 inches or 86.3 cm on the printed map.
paper_height a value in paper_units to specify how tall the scale bar will be displayed. Specify height of
the adornment to a maximum of 44 inches or 111.76cm on the printed map.
Description
The scale bar displays as a paper_length bar in the paper_units.
Position can be Fixed relative to the mapper upper left regardless of the size of the mapper, or relative
to some anchor point on the mapper specified by win_position.
Offset is the amount the adornment will be offset from the mapper when using one of the docked
win_position.
Layout Fixed Position determines how an adornment is positioned in a layout when the adornment is
using Fixed positioning. If this is set to Geographic, then the adornment is placed on the same geographic place on the map frame in the layout as it is in the mapper. If the layout frame changes size,
then the adornment will move relative to the frame to match the geographic position. If this is set to
Frame, then the adornment will remain at a fixed position relative to the frame, as designated in the
Position clause. If the Position clause positions the adornment at (1.0, 1.0) inches, then the adornment
will be placed 1 inch to the left and one inch down from the upper left corner of the frame. Changing the
size of the frame will not change the position of the adornment. The default is Geographic.
Offset is the amount the adornment will be offset from the mapper when using one of the docked
win_positions.
The Background clause when used with Brush denotes the fill pattern to be used in the background
while creating or modifying a scale bar. When used with the Pen clause, this denotes the border to be
used in the background while creating or modifying a scale bar.
Brush is a valid Brush clause. Only Solid brushes are allowed. While values other than solid are allowed
as input without error, the type is always forced to solid. This clause is used only to provide the background
color for the adornment.
Reference
167
168
MapBasic 12.0
Reference
169
1 for Main
2 for Drawing
3 for Tools
4 for Standard
5 for Database Management System (DBMS)
6 Web Services
7 Reserved
170
MapBasic 12.0
Reference
171
172
MapBasic 12.0
Description
Calling M_FILE_NEW
Calling my_procedure
If you specify a procedure name, the event calls the procedure. The procedure must be part of the same MapBasic program.
Connects through DDE to "server|topic" and sending an Execute message to the DDE server.
In the last two cases, the string sent to OLE or DDE starts with the three letters "MI:" so that the server
can detect that the message came from MapInfo. The remainder of the string contains a comma-separated
list of the values returned from the function calls CommandInfo(1) through CommandInfo(8). For complete
details on the string syntax, see the MapBasic User Guide.
Examples
Create a button pad of utilities:
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
Create a toolbar button that launches the Browser Preferences dialog, which has a menu command ID
of 222:
Create ButtonPad "Prefs" As
PushButton
HelpMsg "Browser Preferences.\nBrowser Prefs"
Reference
173
1 for Main
2 for Drawing
3 for Tools
4 for Standard
5 for Database Management System (DBMS)
6 Web Services
7 Reserved
174
MapBasic 12.0
Reference
175
176
MapBasic 12.0
Reference
177
CreateCircle( ) function
FromMapCatalog OFF retrieves the unique map styles for the live table from the server. This table must
be a live access table that supports per record styles for this to occur. If the live table does not support
per record styles than the behavior is to revert to the default behavior for live tables, which is to get the
default styles from the MapCatalog (FromMapCatalog ON).
If a Label is defined, specify expression as 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 is searched for metadata values for the title, subtitle, column and
label. If no metadata value exists for the 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
' here, you would store the Map window's ID in i_map_id,
' and store the Layout window's ID in i_layout_id.
' To obtain an ID, call FrontWindow( ) or WindowID( ).
s_title = "Legend of " + WindowInfo(i_map_id, WIN_INFO_NAME)
Set CoordSys Layout Units "in"
Create Frame
Into Window i_layout_id
(1,2) (4, 5)
Title s_title
This creates 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 statement, Alter Cartographic Frame statement, Add Cartographic
Frame statement, Remove Cartographic Frame statement, Create Legend statement, Set Window
statement, WindowInfo( ) function
CreateCircle( ) function
Purpose
Returns an Object value representing a circle. You can call this function from the MapBasic window in
MapInfo Professional.
Syntax
CreateCircle( x, y, radius )
x is a float value, indicating the x-position (for example, Longitude) of the circle's center.
178
MapBasic 12.0
Error Conditions
ERR_FCN_ARG_RANGE (644) is 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 is 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
Reference
179
180
MapBasic 12.0
Reference
181
182
MapBasic 12.0
Reference
183
184
MapBasic 12.0
Reference
185
186
MapBasic 12.0
Reference
187
form:
Custom 2, 5:10, 1, 3, 4
Custom 2, 5:10, 1, 3:4 (same as above but also valid)
Custom 2, 5:10, 1 (same as above but also valid)
Long form:
Order Custom 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19,
20, 11
Short form:
Order Custom 1:10, 12:20, 11
The list of values cannot have duplicates that will cause an error. The following causes an error:
Order Custom 1:5, 8, 4:7
This is because row ids 4 and 5 are duplicates. To see this, expand the syntax as follows (which causes
an error):
Order Custom 1, 2, 3, 4, 5, 8, 4, 5, 6, 7
The alternate syntax can be used when creating or altering a legend in the Legend Designer window.
For workspaces, the short syntax is used when legends in the Legend Designer window have more
than 50 rows with a custom order.
188
MapBasic 12.0
Reference
189
190
MapBasic 12.0
Reference
191
192
MapBasic 12.0
Grid Description
A grid surface theme is a continuous raster grid produced by an interpolation of point data. The Create
Grid statement takes a data column from a table of points and passes those points and their data values
Reference
193
194
MapBasic 12.0
IDW Interpolator
The IDW Interpolator is best suited for data values that produce arbitrary values over the grid, that is,
data that does not have any relationship or influence over neighboring data values, such as population.
This method of interpolation also works well for sparse data. The IDW Interpolator calculates the value
of grid cells that cover the mapping area. Each data point value from the source table that is considered
in the calculation for a cell value is weighted by its distance from the center of the cell. Because the interpolation is an inverse distance weighting calculation, the farther the point is from the cell, the less in-
Reference
195
196
MapBasic 12.0
Count
Minimum
Maximum
Sum
If parameter name : parameter is not provided, then a default value is used. If all default interpolator
settings are desired, then set Using num_parameters to 0.
See Also:
Create Grid statement, READ ONLY Parameter for TIN and IDW Interpolators
TIN Interpolator
The TIN Interpolator works best for terrain data and for data points that have a linear progression or relationship to each other across the grid, such as elevation or temperature. The TIN Interpolator produces
triangles from a network of points that more closely reproduces the original map terrain than the IDW
Interpolator. It draws lines between points, dividing them into triangles and connecting all the points that
it can. It creates a mesh of connectivity so that the grid points can be interpolated. The interpolation is
not influenced by the neighboring original data values, so you do not get the "false bumping" of data that
you can get with the IDW Interpolator.
The TIN settings can be manipulated to give more or less detail to the map terrain. The Tolerance setting
controls whether closely spaced points are discarded. The tolerance is a fraction of the diagonal length
of the bounding box of the points. The Distance value controls the output. For non-zero distance values,
only edges or triangles contained within a sphere centered at mesh vertices are output. This is useful
to constrain the triangulated irregular network to a specified distance; otherwise, the triangulation will
cross concave regions. The Feature Angle setting controls the angle (in degrees) that defines a sharp
edge. This setting is used for smoothing the final grid. If the difference in angle across neighboring
polygons is greater than this value, the shared edge is considered "sharp."
The TIN Interpolator settings can be controlled via the Settings button in the Create Thematic Map Step 3 of 3 dialog when creating a grid thematic map. The cell size number in this interpolator settings
dialog represents both the height and width of the cell like the IDW method. Any change to the cell size
will result in an automatic update of the grid dimensions.
TIN Interpolator Settings for Create Grid Statement
For the MapInfo Professional TIN Interpolator, when specifying the following parameters in the Grid
Statement syntax:
Using num_parameters parameter_name : parameter_value
[ parameter_name : parameter_value ... ]
the following parameter_name : parameter_values may be used:
Reference
197
198
MapBasic 12.0
Example
The following example creates an index for the "Capital" field of the World table.
Open Table "world" Interactive
Create Index on World(Capital)
See Also:
Alter Table statement, Create Table statement, Drop Index statement, Commit Table statement
Reference
199
CreateLine( ) function
After you issue the Create Legend statement, determine the new window's integer ID by calling WindowID( 0 ). Use that window ID in subsequent statements (such as the Set Window statement).
The new Theme Legend window is created according to the parent and style settings that you specify
through the Set Next Document statement.
See Also:
Create Cartographic Legend statement, Open Window statement, Set Next Document statement,
Set Window statement
CreateLine( ) function
Purpose
Returns an Object value representing a line. You can call this function from the MapBasic window in
MapInfo Professional.
Syntax
CreateLine( x1, y1, x2, y2 )
x1 is a float value, indicating the x-position (for example,) of the line's starting point.
y1 is a float value, indicating the y-position (for example, 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.
200
MapBasic 12.0
Reference
201
202
MapBasic 12.0
Reference
203
204
MapBasic 12.0
Reference
205
206
Control code
Effect
(-
The menu item is a horizontal separator line; such a menu item cannot have a
handler. Example: (-
($
This special code represents the File menu's most-recently-used (MRU) list. It
may only appear once in the menu system, and it may not be used on a shortcut
MapBasic 12.0
Effect
menu. To eliminate the MRU list from the File menu, either delete this code from
MAPINFOW.MNU or re-create the File menu by issuing a Create Menu statement.
(>
This special code represents the Window menu's list of open windows. It may only
appear once in the menu system.
! ... ^ ...
If a caret (^) appears within the text string of a checkable menu item, the item
toggles between alternate text (for example, Show... vs. Hide...) instead
of toggling between checked and unchecked. The text before the caret appears
when the item is "checked." Example: !Hide Status Bar^Show Status Bar
!+
Reference
207
Effect
/W {letter | %number}
To specify a function key as a Windows accelerator, the accelerator code must include a percent sign
(%) followed by a number. The number 112 corresponds to F1, 113 corresponds to F2, etc.
Note: The Create Menu Bar As Default statement removes and un-defines all custom menus created
through the Create Menu statement. Alternately, if you need to un-define one, 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 MapInfo Professional menu (for example, "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.
208
Description
Calling M_FILE_NEW
MapBasic 12.0
Description
command (the File > New command, in this example).
Calling my_procedure
If you specify a procedure name, MapInfo Professional handles the event by calling the procedure.
In the last two cases, the string sent to OLE or DDE starts with the three letters "MI:" (so that the server
can detect that the message came from MapInfo Professional). The remainder of the string contains a
comma-separated list of the values returned from relevant CommandInfo( ) function calls. For complete
details on the string syntax, see the MapBasic User Guide.
Examples
The following example uses the Create Menu statement to create a custom menu, then adds the custom
menu to MapInfo Professional's menu bar. This example removes the Window menu (ID 6) and the Help
menu (ID 7), and then adds the custom menu, the Window menu, and the Help menu back to the menu
bar. This technique guarantees that the last two menus will always be Window, and Help.
Declare Sub Main
Declare Sub addsub
Declare Sub editsub
Declare Sub delsub
Sub Main
Create Menu "DataEntry" As
"Add" Calling addsub,
"Edit" Calling editsub,
"Delete" Calling delsub
Alter Menu Bar Remove ID 6, ID 7
Alter Menu Bar Add "DataEntry", ID 6, ID 7
End Sub
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 Chr$(9) function to insert a Tab character into the menu item name, so that the
remaining text is shifted to the right.
Include "MENU.DEF"
Create Menu "File" As
"New" Calling M_FILE_NEW,
"Open" +Chr$(9)+"Ctrl+O/W^O" Calling M_FILE_OPEN,
"(-",
Reference
209
210
MapBasic 12.0
Reference
211
212
MapBasic 12.0
Reference
213
214
MapBasic 12.0
Reference
215
216
MapBasic 12.0
Reference
217
218
MapBasic 12.0
CreatePoint( ) function
Purpose
Returns an Object value representing a point. You can call this function from the MapBasic window in
MapInfo Professional.
Syntax
CreatePoint( x, y )
x is a float value, representing an x-position (for example, Longitude).
y is a float value, representing a y-position (for example, 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 reconfigure 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 statement.
Reference
219
220
MapBasic 12.0
Reference
221
222
MapBasic 12.0
Reference
223
224
MapBasic 12.0
Reference
225
226
MapBasic 12.0
Reference
227
228
MapBasic 12.0
Reference
229
230
MapBasic 12.0
Reference
231
232
MapBasic 12.0
Reference
233
234
MapBasic 12.0
Reference
235
236
MapBasic 12.0
Reference
237
CreateText( ) function
"http://INSERT_OPEN_STREET_MAP_SERVER_NAME_HERE/{LEVEL}/{ROW}/{COL}.pn
g"
AttributionText "required attribution text" Font("Arial",255,16,0,255)
MinLevel 0
MaxLevel 15
Height 256
CoordSys Earth Projection 10, 157, 7, 0 Bounds(-20037508.34,20037508.34) (20037508.34,20037508.34)
See Also:
Alter Table statement, Create Index statement, Create Map statement, Drop Table statement, Export
statement, Import statement, Open Table statement
CreateText( ) function
Purpose
Returns a text object created for a specific map window. You can call this function from the MapBasic
window in MapInfo Professional.
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
LAYER_INFO_LBL_POS_TL
LAYER_INFO_LBL_POS_TC
LAYER_INFO_LBL_POS_TR
LAYER_INFO_LBL_POS_CL
LAYER_INFO_LBL_POS_CR
LAYER_INFO_LBL_POS_BL
LAYER_INFO_LBL_POS_BC
LAYER_INFO_LBL_POS_BR
(0)
(1)
(2)
(3)
(4)
(5)
(6)
(7)
(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 200, representing the distance (in points) the text is offset from the anchor
location; offset is ignored if anchor is zero (centered).
Return Value
Object
238
MapBasic 12.0
Reference
239
CurDate( ) function
The Font clause specifies a text style. The point-size element of the Font is ignored if the text object is
created in a Map window; see below.
label_x, label_y specifies the position where the text object's label line is anchored.
Pen specifies the pen clause settings of callouts created in the Layout window.
text_angle is a float value indicating the angle of rotation for the text object (in degrees).
Example
When the user creates a label line in a Layout window, the Create Text Label Line Pen clause is invoked
and the workspace version is incremented to 950:
!Workspace
!Version 950
!Charset WindowsLatin1
Open Table "Data\Introductory_Data\World\WORLD" As WORLD Interactive
Map From WORLD
Position (0.0520833,0.0520833) Units "in"
Width 6.625 Units "in" Height 4.34375 Units "in"
Set Window FrontWindow()
Set Map
CoordSys Earth Projection 1, 104
Center (35.204159,-25.3575215)
Zoom 18063.92971 Units "mi"
Preserve Zoom Display Zoom
Distance Units "mi" Area Units "sq mi" XY Units "degree"
Set Map
Layer 1
Display Graphic
Global Pen (1,2,0) Brush (2,16777215,16777215) Symbol (35,0,12)
Line (1,2,0) Font ("Arial",0,9,0)
Label Line None Position Center Font ("Arial",0,9,0) Pen (1,2,0)
Description
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 reconfigure MapBasic to use a different coordinate system. If you need to create objects on a Layout
window, you must first issue a Set CoordSys Layout statement.
The x1, y1, x2, and y2 arguments define a rectangular area. When you create text in a Map window, the
text fills the rectangular area, which controls the text height; the point size specified in the Font clause
is ignored. In a Layout window, text is drawn at the point size specified in the Font clause, with the upperleft corner of the text placed at the (x1, y1) location; the (x2, y2) arguments are ignored.
See Also:
AutoLabel statement, CreateText( ) function, Font clause, Insert statement, Update statement
CurDate( ) function
Purpose
Returns the current date in YYYYMMDD format. You can call this function from the MapBasic window
in MapInfo Professional.
240
MapBasic 12.0
CurDateTime( ) function
Purpose
Returns the current date and time. You can then access the Date and Time values using the GetDate(
) function and GetTime() function. You can call this function from the MapBasic window in MapInfo
Professional.
Syntax
CurDateTime()
Return Value
DateTime, which is an integer value in nine bytes: 4 bytes for date, 5 bytes for time. Five bytes for time
include: 2 for millisec, 1 for sec, 1 for min, 1 for hour.
Example
Copy this example into the MapBasic window for a demonstration of this function.
dim X as datetime
X = CurDateTime( )
Print X
See Also:
Day( ) function, Format$( ) function, Month( ) function, StringToDate( ) function, Timer( ) function,
Weekday( ) function, Year( ) function, CurDate( ) function
Reference
241
CurrentBorderPen( ) function
CurrentBorderPen( ) function
Purpose
Returns the current border pen style currently in use. You can call this function from the MapBasic
window in MapInfo Professional.
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 statement, 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 statement).
To extract specific attributes of the Pen style (such as the color), call the StyleAttr( ) function. For more
information about Pen settings, see Pen clause.
Example
Dim p_user_pen As Pen p_user_pen = CurrentBorderPen( )
See Also:
CurrentPen( ) function, Pen clause, Set Style statement, StyleAttr( ) function
CurrentBrush( ) function
Purpose
Returns the Brush (fill) style currently in use. You can call this function from the MapBasic window in
MapInfo Professional.
Syntax
CurrentBrush( )
Return Value
Brush
242
MapBasic 12.0
CurrentFont( ) function
Purpose
Returns the Font style currently in use for Map and Layout windows. You can call this function from the
MapBasic window in MapInfo Professional.
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 box 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 statement).
To extract specific attributes of the Font style (such as the color), call the StyleAttr( ) function.
For more information about Font settings, see Font clause.
Reference
243
CurrentLinePen( ) function
Example
Dim f_user_text As Font
f_user_text = CurrentFont( )
See Also:
Font clause, MakeFont( ) function, Set Style statement, StyleAttr( ) function
CurrentLinePen( ) function
Purpose
Returns the Pen (line) style currently in use. You can call this function from the MapBasic window in
MapInfo Professional.
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 statement, 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 statement).
To extract specific attributes of the Pen style (such as the color), call the StyleAttr( ) function. For more
information about Pen settings, see Pen clause.
Example
Dim p_user_pen As Pen p_user_pen = CurrentPen( )
See Also:
CurrentBorderPen( ) function, Pen clause, Set Style statement, StyleAttr( ) function
CurrentPen( ) function
Purpose
Returns the Pen (line) style currently in use and sets the border pen to the same style as the line pen.
You can call this function from the MapBasic window in MapInfo Professional.
Syntax
CurrentPen( )
244
MapBasic 12.0
CurrentSymbol( ) function
Purpose
Returns the Symbol style currently in use. You can call this function from the MapBasic window in
MapInfo Professional.
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 box. 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 clause as a parameter (such as Set Map
statement or Shade statement).
Reference
245
CurTime( ) function
To extract specific attributes of the Symbol style (such as the color), call the StyleAttr( ) function. For
more information about Symbol settings, see Symbol clause.
Example
Dim sym_user_symbol As Symbol
sym_user_symbol = CurrentSymbol( )
See Also:
MakeSymbol( ) function, Set Style statement, StyleAttr( ) function, Symbol clause
CurTime( ) function
Purpose
Returns the current time in hours, minutes, seconds, and milliseconds. You can call this function from
the MapBasic window in MapInfo Professional.
Syntax
CurTime( )
Return Value
Time
Example
Copy this example into the MapBasic window for a demonstration of this function.
dim Y as time
Y = CurTime()
Print Y
See Also:
Day( ) function, Format$( ) function, Month( ) function, StringToDate( ) function, Timer( ) function,
Weekday( ) function, Year( ) function, CurDate( ) function, CurDateTime( ) function
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. You can call this function from the MapBasic window in MapInfo Professional.
Syntax
DateWindow( context )
context is a SmallInt that can either be DATE_WIN_CURPROG (2) or DATE_WIN_SESSION (1).
246
MapBasic 12.0
Day( ) function
Purpose
Returns the day component from a Date expression. You can call this function from the MapBasic window
in MapInfo Professional.
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( ) function, Day( ) function, Minute( ) function, Month( ) function, Second( ) function,
Timer( ) function, Weekday( ) function, Year( ) function
Reference
247
DDEExecute statement
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 (642) error generated if not running on Windows.
ERR_NO_RESPONSE_FROM_APP (697) 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( ) function, DDEPoke statement, DDERequest$( ) function
DDEInitiate( ) function
Purpose
Initiates a new DDE conversation, and returns the associated channel number.
248
MapBasic 12.0
Reference
249
DDEInitiate( ) function
The following table lists some sample application and topic names which you could use with the
DDEInitiate( ) function.
DDEInitiate( ) call
Nature of conversation
DDEInitiate("Excel", "System")
DDEInitiate("Excel", wks)
DDEInitiate("MapInfo", "System")
DDEInitiate("MapInfo" mbx)
When a MapBasic program issues a DDEInitiate( ) function call, the MapBasic program is known as
the "client" in the DDE conversation. The other Windows application is known as the "server." Within
one particular conversation, the client is always the active party; the server merely responds to actions
taken by the client. A MapBasic program can carry on multiple conversations at the same time, limited
only by memory and system resources. A MapBasic application could act as the client in one conversation
(by issuing statements such as DDEInitiate( ), etc.) while acting as the server in another conversation
(by defining a RemoteMsgHandler procedure).
Error Conditions
ERR_CMD_NOT_SUPPORTED (642) error generated if not running on Windows.
ERR_INVALID_CHANNEL (696) error generated if the specified channel number is invalid.
Example
The following example attempts to initiate a DDE conversation with Microsoft Excel, version 4 or later.
The goal is to store a simple text message ("Hello from MapInfo!") in the first cell of a worksheet that
Excel is currently using, but only if that cell is currently empty. If the first cell is not empty, we will not
overwrite its current contents.
Dim chan_num, tab_marker As Integer
Dim topiclist, topicname, cell As String
chan_num = DDEInitiate("EXCEL", "System")
If chan_num = 0 Then
Note "Excel is not responding to DDE conversation."
End Program
250
MapBasic 12.0
Reference
251
DDEPoke statement
See Also:
DDEExecute statement, DDEPoke statement, DDERequest$( ) function, DDETerminate statement,
DDETerminate All statement
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 the DDEInitiate( ) function.
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 (642) error generated if not running on Windows.
ERR_INVALID_CHANNEL (696) 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."
252
MapBasic 12.0
DDERequest$( ) function
Purpose
Returns a data value obtained from a DDE conversation.
Syntax
DDERequest$( channel, itemname )
channel is an integer channel number returned by the DDEInitiate( ) function.
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:
Topic name
"System"
wks (name of a worksheet in A string of the form R1C1 (for Row 1, Column 1) returns the contents
of that cell
use)
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
Reference
253
DDETerminate statement
combinations that can be used when conducting a DDE conversation with MapInfo Professional
as the server
Topic name
"System"
Error Conditions
ERR_CMD_NOT_SUPPORTED (642) error generated if not running on Windows.
ERR_INVALID_CHANNEL (696) error if the specified channel number is invalid.
ERR_CANT_INITIATE_LINK (698) error generated if MapBasic cannot link to the topic.
Example
The following example uses the DDERequest$( ) function to obtain the current contents of the first cell
in an Excel worksheet. Note that this example will only work if Excel is already running.
Dim i_chan_num As Integer
Dim s_cell As String
i_chan_num = DDEInitiate("EXCEL", "Sheet1")
s_cell = DDERequest$(i_chan_num, "R1C1")
The following example assumes that there is another MapBasic application currently in use"Dispatch"and assumes that the Dispatch application has a global variable called Address. The example
below uses DDERequest$( ) to obtain the current value of the Address global variable.
Dim i_chan_num As Integer, s_addr_copy As String
i_chan_num = DDEInitiate("MapInfo","C:\DISPATCH.MBX")
s_addr_copy = DDERequest$(i_chan_num, "Address")
See Also:
DDEInitiate( ) function
DDETerminate statement
Purpose
Closes a DDE conversation.
254
MapBasic 12.0
Error Conditions
ERR_CMD_NOT_SUPPORTED (642) error generated if not running on Windows.
ERR_INVALID_CHANNEL (696) error generated if the specified channel number is invalid.
Example
DDETerminate i_chan_num
See Also:
DDEInitiate( ) function, DDETerminate All statement
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.
Reference
255
256
MapBasic 12.0
Reference
257
258
MapBasic 12.0
Reference
259
260
MapBasic 12.0
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
Reference
261
DeformatNumber$( ) function
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 keyword 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 Dim statement.
Examples
Your application may need to reference the mathematical 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. You can call this function from the MapBasic
window in MapInfo Professional.
Syntax
DeformatNumber$ ( numeric_string )
numeric_string is a string that represents a numeric value, such as "12,345,678".
Return Value
String
262
MapBasic 12.0
Delete statement
Purpose
Deletes one or more graphic objects, or one or more entire rows, from a table. You can issue this
statement from the MapBasic window in MapInfo Professional.
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.
Reference
263
Dialog 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 emptyas if the user had just created it by choosing File > New.
Open Table "clients"
Delete From clients
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
Table clients
See Also:
Drop Map statement, Insert statement
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 box.
h specifies the height of the dialog box, in dialog box units (8 dialog box 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 box'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 box appears centered.
handler is the name of a procedure to call before the user is allowed to use the dialog box; this procedure
is typically used to issue Alter Control statements.
264
MapBasic 12.0
Button
OKButton
CancelButton
EditText
StaticText
PopupMenu
CheckBox
MultiListBox
GroupBox
RadioGroup
PenPickerm
BrushPicker
FontPicker
SymbolPicker
ListBox
See the separate discussions of those control types for more details (for example, for details on CheckBox
controls, see Control CheckBox clause; for details on Picker controls, see Control PenPicker/BrushPicker/SymbolPicker/FontPicker clause; etc.).
Each control_clause can specify one of the following control types:
Description
The Dialog statement creates a dialog box, displays it on the screen, and lets the user interact with it.
The dialog box is modal; in other words, the user must dismiss the dialog box (for example, by clicking
OK or Cancel) before doing anything else in MapInfo Professional. For an introduction to custom dialog
boxes, see the MapBasic User Guide.
Anything that can appear on a dialog box is known as a control. Each dialog box must contain at least
one control (for example, an OKButton control). Individual control clauses are discussed in separate
entries (for example, see Control CheckBox clause for a discussion of check-box controls). As a general rule, every dialog box should include an OKButton control and/or a CancelButton control, so that
the user has a way of dismissing the dialog box.
The Dialog statement lets you create a custom dialog box. If you want to display a standard dialog box
(for example, a File > Open dialog box), use one of the following statements or functions: Ask( ) function,
Reference
265
Dialog statement
Note statement, ProgressBar statement, FileOpenDlg( ) function, FileSaveAsDlg( ) function, or
GetSeamlessSheet( ) function).
For an introduction to the concepts behind MapBasic dialog boxes, see the MapBasic User Guide.
Sizes and Positions of Dialog Boxes and Dialog Box Controls
Within the Dialog statement, sizes and positions are stated in terms of dialog box units. A width of four
dialog box units equals the width of one character, and a height of eight dialog box units equals the
height of one character. Thus, if a dialog box 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 box. To place a control at the upper-left corner of a dialog box, 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 box, with subsequent control clauses appearing further
down in the dialog box.
Terminating a Dialog Box
After a MapBasic program issues a Dialog statement, the user will continue interacting with the dialog
box until one of four things happens:
The user clicks the OKButton control (if the dialog box has one);
The user clicks the CancelButton control (if the dialog box has one);
The user clicks a control with a handler that issues a Dialog Remove statement; or
The user otherwise dismisses the dialog box (for example, by pressing Esc on a dialog box that has
a CancelButton).
To force a dialog box 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 the CommandInfo( ) function to determine whether the user clicked OK
or Cancel to dismiss the dialog box. 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, MapInfo Professional stores
the control's final value in a program variable.
Note: MapInfo Professional only updates the variable if the user clicks OK. Also, MapInfo Professional
only updates the variable after the dialog box terminates.
To read a control's value from within a handler procedure, call the ReadControlValue( ) function.
266
MapBasic 12.0
Reference
267
Dialog statement
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"
268
MapBasic 12.0
Reference
269
See Also:
Alter Control statement, Ask( ) function, Dialog Preserve statement, Dialog Remove statement,
FileOpenDlg( ) function, FileSaveAsDlg( ) function, Note statement, ReadControlValue( ) function
270
MapBasic 12.0
Reference
271
Dim statement
Example
The following procedure is part of the sample program NVIEWS.MB. It handles the ListBox control in the
Named Views dialog box. When the user single-clicks a list item, this handler procedure enables various
buttons on the dialog box. When the user double-clicks a list item, this handler uses a Dialog Remove
statement to dismiss the dialog box.
Note: MapInfo Professional calls this handler procedure for click events and for double-click events.
Sub listbox_handler
Dim i As SmallInt
Alter Control 2 Enable
Alter Control 3 Enable
If CommandInfo(CMD_INFO_DLG_DBL) = TRUE Then
'
' ... then the user double-clicked.
'
i = ReadControlValue(1)
Dialog Remove
Call go_to_view(i)
End If
End Sub
See Also:
Alter Control statement, Dialog statement, Dialog Preserve statement, ReadControlValue( )
function
Dim statement
Purpose
Defines one or more variables. You can issue this statement from the MapBasic window in MapInfo
Professional.
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.
272
MapBasic 12.0
Description
SmallInt
Integer
Float
String
String * length
Logical
Date
Date, stored in four bytes: two bytes for the year, one byte for the
month, one byte for the day.
DateTime
DateTime is stored in nine bytes: 4 bytes for date, 5 bytes for time.
Five bytes for time include: 2 for millisec, 1 for sec, 1 for min, 1 for
hour.
Time
Time is stored in five bytes: 2 for millisec, 1 for sec, 1 for min, 1 for
hour.
Object
Alias
Column name.
Pen
Brush
Font
Symbol
The Dim statement which defines a variable must precede any other statements which use that variable.
Dim statements usually appear at the top of a procedure or function.
If a Dim statement appears within a Sub...End Sub statement or within a Function...End Function
statement, the statement defines variables that are local in scope. Local variables may only be accessed
from within the procedure or function that contained the Dim statement.
If a Dim statement appears outside of any procedure or function definition, the statement defines variables
that are module-level in scope. Module-level variables can be accessed by any procedure or function
within a program module (for example, within the .MB program file).
To declare global variables (variables that can be accessed by any procedure or function in any of the
modules that make up a project), use the Global statement.
Reference
273
Dim statement
Declaring Multiple Variables and Variable Types
A single Dim statement can declare two or more variables that are separated by commas. You also can
define variables of different types within one Dim statement by grouping like variables together, and
separating the different groups with a comma after the variable type:
Dim jointer, i_min, i_max As Integer, s_name As String
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
274
MapBasic 12.0
Alter
Close
Browse
Call
Create
DDE
DDEExecute
DDEPoke
DDETerminate
DDETerminateAll
Declare
Delete
Dialog
Dim
Do
Drop
Else
ElseIf
End
Error
Event
Exit
Export
Fetch
Find
For
Function
Get
Global
Goto
Graph
If
Import
Insert
Layout
Map
Menu
Note
Objects
OnError
Open
Pack
PrintWin
ProgressBar
Put
ReDim
Register
Reload
Remove
Rename
Resume
Rollback
Run
Save
Seek
Select
Set
Shade
StatusBar
Stop
Sub
Type
Update
While
In some BASIC languages, you can dictate a variable's type by ending the variable with one of the
punctuation marks listed above. For example, some BASIC languages assume that any variable named
with a dollar sign (for example, LastName$) is a string variable. In MapBasic, however, you must declare
every variable's type explicitly, through the Dim statement.
Reference
275
Distance( ) function
Initial Values of Variables
MapBasic initializes numeric variables to a value of zero when they are defined. Variable-length string
variables are initialized to an empty string, and fixed-length string variables are initialized to all spaces.
Object and style variables are not automatically initialized. You must initialize Object and style variables
before making references to those variables.
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
' The next Dim statement creates a Person variable
Dim customer As Person
' This Dim creates an array of Person variables:
Dim users(10) As Person
' this Dim statement defines an integer variable
' "counter", and an integer array "counters" :
Dim counter, counters(10) As Integer
' the next statement assigns the "Name" element
' of the first member of the "users" array
users(1).Name = "Chris"
See Also:
Global statement, ReDim statement, Type statement, UBound( ) function
Distance( ) function
Purpose
Returns the distance between two locations. You can call this function from the MapBasic window in
MapInfo Professional.
Syntax
Distance ( x1, y1, x2, y2, unit_name )
x1 and x2 are x-coordinates (for example, longitude).
y1 and y2 are y-coordinates (for example, latitude).
unit_name is a string representing the name of a distance unit (for example, "km").
Return Value
Float
276
MapBasic 12.0
Reference
277
278
MapBasic 12.0
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 statement or Exit Do statement, will be needed
to halt or exit the loop. The Exit Do statement halts any Do...Loop immediately (regardless of whether
Reference
279
280
MapBasic 12.0
Reference
281
282
MapBasic 12.0
Reference
283
EndHandler procedure
menu item added in this fashion calls a sub procedure from a MapBasic program. Once a MapBasic
application has connected a procedure to the menu in this fashion, the application is said to be "sleeping."
If any procedure in a MapBasic application issues an End Program statement, that entire application
is haltedeven if "sleeping" procedures have been attached to custom menu items. When an application
halts, MapInfo Professional automatically removes any menu items created by that application.
If an application defines a procedure named EndHandler, MapBasic automatically calls that procedure
when the application halts, for whatever reason the application halts.
See Also:
End MapInfo statement, EndHandler procedure
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 MapInfo Professional
terminates, MapBasic automatically calls all sleeping EndHandler procedures, one after another.
See Also:
RemoteMsgHandler procedure, SelChangedHandler procedure, ToolHandler procedure, WinChangedHandler procedure, WinClosedHandler procedure
EOF( ) function
Purpose
Returns TRUE if MapBasic tried to read past the end of a file, FALSE otherwise.
Syntax
EOF( filenum )
284
MapBasic 12.0
EOT( ) function
Purpose
Returns TRUE if MapBasic has reached the end of the specified table, FALSE otherwise. You can call
this function from the MapBasic window in MapInfo Professional.
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 (405) error generated if the specified table is not available
Reference
285
EPSGToCoordSysString$( ) function
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:
EOF( ) function, Fetch statement, Open File statement, Open Table statement
EPSGToCoordSysString$( ) function
Purpose
Converts a string containing a Spatial Reference System into a CoordSys clause that can be used with
any MapBasic function or statement. You can call this function from the MapBasic window in MapInfo
Professional.
Syntax
EPSGToCoordSysString$( srs_string )
srs_string is a String describing a Spatial Reference System (SRS) for any supported coordinate systems.
SRS strings are also referred to as EPSG (European Petroleum Survey Group) strings (for example,
epsg:2600). For a complete list of EPSG codes used with MapInfo Professional see the MAPINFOW.PRJ
file in your MapInfo Professional installation. The EPSG codes are identified by a "\p" followed by a
number.
Description
The EPSGToCoordSysString$( ) is used to convert a SRS String into a CoordSys clause that can be
used in any MapBasic function or statement that takes a CoordSys clause as an input.
Example
The following example sets the coordinate system of a map to Earth Projection 1, 104.
run command("Set Map " +
EPSGToCoordSysString$("EPSG:4326"))
See Also:
CoordSys clause
286
MapBasic 12.0
Erase( ) function
Purpose
Returns an object created by erasing part of another object. You can call this function from the MapBasic
window in MapInfo Professional.
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 statement, Objects Intersect statement
Err( ) function
Purpose
Returns a numeric code, representing the current error. You can call this function from the MapBasic
window in MapInfo Professional.
Reference
287
Err( ) function
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 (696) 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( ) function and ObjectInfo( ) function,
take an Object expression as a parameter. Any such function will generate the
ERR_FCN_OBJ_FETCH_FAILED (650) 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 (650)
error. Since the ERR_FCN_OBJ_FETCH_FAILED (650) 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 (911) and
ERR_FP_MATH_LIB_RANGE (912)-which can occur as a result of an invalid numeric parameter. These
errors might be generated by calls to any of the following functions: Acos( ) function, Asin( ) function,
Atn( ) function, Cos( ) function, Exp( ) function, Log( ) function, Sin( ) function, Sqr( ) function, or
Tan( ) function.
The complete list of potential MapBasic error codes is included in the file ERRORS.DOC.
See Also:
Error statement, Error$( ) function, OnError statement
288
MapBasic 12.0
Error statement
Purpose
Simulates the occurrence of an error condition. You can issue this statement from the MapBasic window
in MapInfo Professional.
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( ) function, Error$( ) function, OnError statement
Error$( ) function
Purpose
Returns a message describing the current error. You can call this function from the MapBasic window
in MapInfo Professional.
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 Err( ) function
for more information.
See Also:
Err( ) function, Error statement, OnError statement
Reference
289
Exit Do statement
Exit Do statement
Purpose
Exits a Do...Loop statement 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 statement, Exit For statement, Exit Sub statement
290
MapBasic 12.0
Reference
291
Exp( ) function
Purpose
Returns the number e raised to a specified exponent. You can call this function from the MapBasic
window in MapInfo Professional.
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 (^).
292
MapBasic 12.0
Export statement
Purpose
Exports a table to another file format. You can issue this statement from the MapBasic window in MapInfo
Professional.
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 ] |
"CSV" [ Charset char_set ] [ 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 file name 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 "WindowsLatin1"; see CharSet clause 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.
Reference
293
Export statement
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.
Specifying the File Format
The optional Type clause specifies the format of the file you want to create.
Type clause
Type "MIF"
Type "DXF"
Type "DBF"
Type "ASCII"
Type "CSV"
If you omit the Type clause, MapInfo Professional assumes that the file extension indicates the desired
file format. For example, if you specify the file name "PARCELS.DXF" MapInfo Professional creates a
DXF file.
If you include the optional Overwrite keyword, MapInfo Professional creates the export file, regardless
of whether a file by that name already exists. If you omit the Overwrite keyword, and the file already
exists, MapInfo Professional does not overwrite the file.
Exporting ASCII Text Files
When you export a table to an ASCII or CSV text file, the text file will contain delimiters. A delimiter is a
special character that separates the fields within each row of data. CSV text files automatically use a
comma (,) as the delimiter. No other delimiter can be specified for CSV export.
294
MapBasic 12.0
Reference
295
ExtractNodes( ) function
ExtractNodes( ) function
Purpose
Returns a polyline or region created from a subset of the nodes in an existing object. You can call this
function from the MapBasic window in MapInfo Professional.
Syntax
ExtractNodes( object, polygon_index, begin_node, end_node, b_region )
object is a polyline or region object.
polygon_index is an integer value, 1 or larger: for region objects. This indicates which polygon (for regions)
or section (for polylines) to query.
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 begin_node is equal to or greater than end_node, the nodes are returned in the following order:
begin_node through the next-to-last node in the polygon;
First node in polygon through end_node.
If object is a region object, and if begin_node and end_node are both equal to 1, MapBasic returns the
entire set of nodes for that polygon. This provides a simple mechanism for extracting a single polygon
from a multiple-polygon region. To determine the number of polygons in a region, call the ObjectInfo(
) function.
Error Conditions
ERR_FCN_ARG_RANGE (644) error generated if b_region is FALSE and the range of nodes contains
fewer than two nodes, or if b_region is TRUE and the range of nodes contains fewer than three nodes.
See Also:
ObjectNodeX( ) function, ObjectNodeY( ) function
296
MapBasic 12.0
Farthest statement
Purpose
Find the object in a table that is farthest from a particular object. The result is a two-point Polyline object
representing the farthest distance. You can issue this statement from the MapBasic window in MapInfo
Professional.
Syntax
Farthest [ N | All ]
From { Table fromtable | Variable fromvar }
To totable Into intotable
[ Type { Spherical | Cartesian } ]
[ Ignore [ Contains ] [ Min min_value ]
[ Max max_value ] Units unitname ]
[ Data clause ]
N is an optional parameter for the number of "farthest" objects to find. The default is 1. If All is used,
then a distance object is created for every combination.
fromtable is a table of objects from which you want to find farthest distances.
fromvar is a MapBasic variable representing an object that you want to find the farthest distances from.
totable is a table of objects that you want to find farthest distances to.
intotable is a table to place the results into.
min_value is the minimum distance to include in the results.
max_value is the maximum distance to include in the results.
unitname is string representing the name of a distance unit (for example, "km") used for min_value and/or
max_value.
Description
The Farthest statement finds all the objects in the fromtable that is furthest from a particular object.
Every object in the fromtable is considered. For each object in the fromtable, the furthest object in the
totable is found. If N is defined, then the N farthest objects in the totable are found. A two-point Polyline
object representing the farthest points between the fromtable object and the chosen totable object is
placed in the intotable. If All is specified, then an object is placed in the intotable representing the distance
between the fromtable object and each totable object.
If there are multiple objects in the totable that are the same distance from a given fromtable object, then
only one of them may be returned. If multiple objects are requested (for example, if N is greater than 1),
then objects of the same distance will fill subsequent slots. If a tie exists at the second farthest object,
and three objects are requested, then one of the second farthest objects will become the third farthest
object.
The types of the objects in the fromtable and totable can be anything except Text objects. For example,
if both tables contain Region objects, then the minimum distance between Region objects is found, and
the two-point Polyline object produced represents the points on each object used to calculate that distance.
Reference
297
Farthest statement
If the Region objects intersect, then the minimum distance is zero, and the two-point Polyline returned
will be degenerate, where both points are identical and represent a point of intersection.
The distances calculated do not take into account any road route distance. It is strictly a "as the bird
flies" distance.
The Ignore clause can be used to limit the distances to be searched, and can effect how many totable
objects are found for each fromtable object. One use of the Min distance could be to eliminate distances
of zero. This may be useful in the case of two point tables to eliminate comparisons of the same point.
For example, if there are two point tables representing Cities, and we want to find the closest cities, we
may want to exclude cases of the same city.
The Max distance can be used to limit the objects to consider in the totable. This may be most useful in
conjunction with N or All. For example, we may want to search for the five airports that are closest to a
set of cities (where the fromtable is the set of cities and the totable is a set of airports), but we don't care
about airports that are farther away than 100 miles. This may result in less than five airports being returned
for a given city. This could also be used in conjunction with the All parameter, where we would find all
airports within 100 miles of a city.
Supplying a Max parameter can improve the performance of the Farthest statement, since it effectively
limits the number of totable objects that are searched.
The effective distances found are strictly greater than the min_value and less than or equal to the
max_value:
min_value < distance <= max_value
This can allow ranges or distances to be returned in multiple passes using the Farthest statement. For
example, the first pass may return all objects between 0 and 100 miles, and the second pass may return
all objects between 100 and 200 miles, and the results should not contain duplicates (for example, a
distance of 100 should only occur in the first pass and never in the second pass).
Type is the method used to calculate the distances between objects. It can either be Spherical or
Cartesian. The type of distance calculation must be correct for the coordinate system of the intotable or
an error will occur. If the Coordsys of the intotable is NonEarth and the distance method is Spherical,
then an error will occur. If the Coordsys of the intotable is Latitude/Longitude, and the distance method
is Cartesian, then an error will occur.
The Ignore clause limits the distances returned. Any distances found which are less than or equal to
min_value or greater than max_value are ignored. min_value and max_value are in the distance unit
signified by unitname. If unitname is not a valid distance unit, an error will occur. See Set Distance Units
statement for the list of available unit names. The entire Ignore clause is optional, as are the Min and
Max sub clauses within it.
Normally, if one object is contained within another object, the distance between the objects is zero. For
example, if fromtable is WorldCaps and totable is World, then the distance between London and the
United Kingdom would be zero. If the Contains keyword is used within the Ignore clause, then the distance will not be automatically be zero. Instead, the distance from London to the boundary of the United
Kingdom will be returned. In effect, this will treat all closed objects, such as regions, as polylines for the
purpose of this operation.
The Data clause can be used to mark which fromtable object and which totable object the result came
from.
298
MapBasic 12.0
Fetch statement
Purpose
Sets a table's cursor position (for example, which row is the current row). You can issue this statement
from the MapBasic window in MapInfo Professional.
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:
Reference
299
Fetch statement
Syntax
Example
table.column
World.Country
table.col#
World.col1
table.col( number )
World.col( 1 )
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 (for example, 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, the EOT( ) function 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
Print "Number of undeleted records: " + i
300
MapBasic 12.0
FileAttr( ) function
Purpose
Returns information about an open file. You can call this function from the MapBasic window in MapInfo
Professional.
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:
attribute parameter
ID
Return Value
FILE_ATTR_MODE
FILE_ATTR_FILESIZE
Reference
MODE_INPUT (0)
MODE_OUTPUT (1)
MODE_APPEND (2)
MODE_RANDOM (3)
MODE_BINARY (4)
301
FileExists( ) function
Error Conditions
ERR_FILEMGR_NOTOPEN (366) error is generated if the specified file is not open.
See Also:
EOF( ) function, Get statement, Open File statement, Put statement
FileExists( ) function
Purpose
Returns a logical value indicating whether or not a file exists. You can call this function from the MapBasic
window in MapInfo Professional.
Syntax
FileExists( filespec )
filespec is a string that specifies the file path and name.
Return Value
Logical: TRUE if the file already exists, otherwise FALSE.
Example
If FileExists("C:\MapInfo\TODO.TXT") Then
Open File "C:\MapInfo\TODO.TXT" For INPUT As #1
End If
See Also:
TempFileName$( ) function
FileOpenDlg( ) function
Purpose
Displays a File Open dialog box, and returns the name of the file the user selected. You can call this
function from the MapBasic window in MapInfo Professional.
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.
filetype is a string value, three or four characters long, indicating a file type (for example, "TAB" to specify
tables).
prompt is a string title that appears on the bar at the top of the dialog box.
302
MapBasic 12.0
"TAB"
MapInfo tables
"WOR"
MapInfo workspaces
"MIF"
MapInfo Interchange Format files, used for importing / exporting maps from
/ to ASCII text files.
"DBF"
"WKS", "WK1"
"XLS", "XLSX"
"DXF"
"MMI", "MBI"
Reference
303
FileSaveAsDlg( ) function
filetype parameter
"MB"
"MBX"
"TXT"
Text files
"BMP"
"WMF"
Windows metafiles
Each of the three-character file types listed above corresponds to an actual file extension; in other words,
specifying a filetype parameter of "WOR" tells MapBasic to display a list of files having the ".WOR" file
extension, because that is the extension used by MapInfo Professional workspaces.
To help you write portable applications, MapBasic lets you use the same three-character filetype settings
on all platforms. On Windows, a control in the lower left corner of the dialog box lets the user choose
whether to see a list of files with the .TAB extension, or a list of all files in the current directory. If the
FileOpenDlg( ) function specifies a filetype parameter which is not listed in the table of file extensions
above, the dialog box appears without that control.
Example
Dim s_filename As String
s_filename = FileOpenDlg("","","TAB","Open Table")
See Also:
FileSaveAsDlg( ) function, Open File statement, Open Table statement
FileSaveAsDlg( ) function
Purpose
Displays a Save As dialog box, and returns the name of the file the user entered. You can call this
function from the MapBasic window in MapInfo Professional.
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 box lets the user choose.
prompt is a string title that appears at the top of the dialog box.
Return Value
String value, representing the name of the file the user entered (or an empty string if the user cancelled).
304
MapBasic 12.0
Find statement
Purpose
Finds a location in a mappable table. You can issue this statement from the MapBasic window in MapInfo
Professional.
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 box displays a list of "near matches."
Reference
305
Find statement
The Find statement can only search a mappable table (for example, 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 MapInfo Professional'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 (for example, "Albany") by searching
a table of cities; or you could refine the search by specifying both a city name and a region name (for
example, "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 (1). If the Find statement results in an approximate match, the function call returns a
value greater than one (1). If the Find statement fails to match the address, the function call returns a
negative value.
306
MapBasic 12.0
Meaning
xx1
Exact match.
xx2
xx3 ( - )
xx4 ( - )
xx5 ( + )
x1x
x2x ( + / - )
x3x ( + / - )
x4x ( + / - )
x5x ( - )
x6x ( - )
x7x ( + )
The user chose an address number from the Interactive dialog box.
1xx ( + / - )
2xx ( - )
Name found in more than one region other than the specified region.
3xx ( + / - )
4xx ( - )
5xx ( + )
6xx ( + )
The user chose a region name from the Interactive dialog box.
Reference
307
Find statement
The Mod operator is useful when examining individual digits from the Find result. For example, to determine the last digit of a number, use the expression number Mod 10. To determine the last two digits of
a number, use the expression number Mod 100; etc.
The distinction between exact and approximate matches is best illustrated by example. If a table of cities
contains one entry for "Albany", and the Find Using statement attempts to locate a city name without a
refining region name, and the Find statement specifies an address parameter value of "Albany", the
search results in an exact match. Following such a Find statement, the function call CommandInfo(CMD_INFO_FIND_RC) would return a value of 1 (one), indicating that an exact match was found.
Now suppose that the Find operation has been set up to refine the search with an optional region name;
in other words, the Find statement expects a city name followed by a state name (for example, "Albany",
"NY"). If a MapBasic program then issues a Find statement with "Albany" as the address and a null
string as the state name, that is technically not an exact match, because MapBasic expects the city
name to be followed by a state name. Nevertheless, if there is only one "Albany" record in the table,
MapBasic will be able to locate that record. Following such a Find operation, the function call CommandInfo(CMD_INFO_FIND_RC) would return a 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 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 Professional 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 box, and the user enters text in the dialog box in
order to complete the find, then the return code will have a 1 (one) in the millions place.
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:
308
MapBasic 12.0
Reference
309
Fix( ) function
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.
If Percent is specified, it represents the percentage of the length of the line where the address is to be
placed. For Percent, valid values for inset_value are from 0 to 50. If Distance Units are specified, inset_value represents the distance from the ends of the line where the address is to be placed. For distance, valid values for inset_value are from 0 to 32,767. The inset takes the addresses that would normally
fall at the end of the street and moves them away from the end going in the direction towards the center.
The Offset value sets the addresses back from the street instead of right on the street. value is a positive
integer value representing how far to offset the placement of an address location back from the street.
Valid values are from 0 to 32,767.
Example
Find Using city_1k(city)
Refine Using states(state)
Find "Albany", "NY"
See Also:
Create Index statement, Find statement
Fix( ) function
Purpose
Returns an integer value, obtained by removing the fractional part of a decimal value. You can call this
function from the MapBasic window in MapInfo Professional.
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)
310
MapBasic 12.0
Font clause
Purpose
Specifies a text style. You can use this clause in the MapBasic window in MapInfo Professional.
Syntax
Font font_expr
font_expr is a Font expression, for example:
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 the Create Text statement, 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 (for example, CurrentFont( ) function or MakeFont( ) function) which returns a
Font value:
Font MakeFont("Helvetica", 1, 12, BLACK, WHITE)
With some MapBasic statements (for example, the Set Legend statement), 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:
Reference
311
Font clause
Component
Description
font name
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
foreground color
Integer RGB color value, representing the color of the text. See Rnd( )
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.
Style Value
Plain
Bold
Italic
Underline
Strikethrough
32
Shadow
256
Halo
512
All Caps
1024
Expanded
To specify two or more style attributes, add the values from the left column. For example, to specify both
the Bold and All Caps attributes, use a style value of 513.
Example
Include "MAPBASIC.DEF"
Dim o_title As Object
Create Text
Into Variable o_title
"Your message could go HERE"
(73.5, 42.6) (73.67, 42.9)
Font MakeFont("Helvetica",1,12,BLACK,WHITE)
312
MapBasic 12.0
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...Next statement provides loop control. This statement requires a numeric variable (identified
by the var_name parameter). A For...Next 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...Next 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...Next 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.
Reference
313
ForegroundTaskSwitchHandler procedure
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
' the next loop will execute a Note statement 5 times
For i = 1 to 5
Note "Hello world!"
Next
' the next loop will execute the Note statement 3 times
For i = 1 to 5 Step 2
Note "Hello world!"
Next
' the next loop will execute the Note statement 3 times
For i = 5 to 1 Step -2
Note "Hello world!"
Next
' MapBasic will skip the following For statement
' completely, because the initial start value is
' already larger than the initial end value
For i = 100 to 50 Step 5
Note "This note will never be executed"
Next
See Also:
Do...Loop statement, Exit For statement
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.
314
MapBasic 12.0
Format$( ) function
Purpose
Returns a string representing a custom-formatted number. You can call this function from the MapBasic
window in MapInfo Professional.
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
Reference
315
Format$( ) function
character (,), the period (.), or the semi-colon (;); these characters control how the results will look.
The table below summarizes the format characters.
pattern character
The result will include one or more digits from the value.
If the pattern string contains one or more # characters to the left of the
decimal place, and if the value is between zero and one, the formatted result
string will not include a zero before the decimal place.
316
. (period)
The pattern string must include a period if you want the result string to include
a "decimal separator." The result string will include the decimal separator
currently in use on the user's computer. To force the decimal separator to be
a period, use the Set Format statement.
, (comma)
The pattern string must include a comma if you want the result string to include
"thousand separators." The result string will include the thousand separator
currently set up on the user's computer. To force the thousand separator to
be a comma, use the Set Format statement.
The result will represent the value multiplied by one hundred; thus, a value
of 0.75 will produce a result string of "75%". If you wish to include a percent
sign in your result, but you do not want MapBasic to multiply the value by
one hundred, place a \ (back slash) character before the percent sign (see
below).
E+
The result is formatted with scientific notation. For example, the value 1234
produces the result "1.234e+03". If the exponent is positive, a plus sign appears after the "e". If the exponent is negative (which is the case for fractional
numbers), the results include a minus sign after the "e".
E-
This string of control characters functions just as the "E+" string, except that
the result will never show a plus sign following the "e".
; (semi-colon)
By including a semicolon in your pattern string, you can specify one format
for positive numbers and another format for negative numbers. Place the
semicolon after the first set of format characters, and before the second set
of format characters. The second set of format characters applies to negative
numbers. If you want negative numbers to appear with a minus sign, include
"-" in the second set of format characters.
If the back slash character appears in a pattern string, MapBasic does not
perform any special processing for the character which follows the back slash.
This lets you include special characters (for example, %) in the results, without
causing the special formatting actions described above.
MapBasic 12.0
",#")
",#")
"$#")
"$#")
'
'
'
'
returns
returns
returns
returns
"12,345"
"-12,345"
"$12345"
"-$12345"
FormatDate$( ) function
Purpose
Returns a date formatted in the short date style specified by the Control Panel. You can call this function
from the MapBasic window in MapInfo Professional.
Note: The FormatDate$( ) function is not configurable whereas the FormatTime$( ) function provides
full control of the output.
Syntax
FormatDate$( value )
value is a number or string representing the date in a YYYYMMDD format.
Return Value
String
Reference
317
FormatNumber$( ) function
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 (for example, 96), MapInfo Professional uses the current
century or the century as determined by the Set Date Window( ) statement.
Year can 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:
FormatTime$( ) function, DateWindow( ) function, Set Date Window( ) statement
FormatNumber$( ) function
Purpose
Returns a string representing a number, including thousands separators and decimal-place separators
that match the user's system configuration. You can call this function from the MapBasic window in
MapInfo Professional.
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.
318
MapBasic 12.0
Result returned
FormatNumber$("12345.67")
FormatNumber$("12,345.67")
If the user's computer is set up to use period as the thousands separator and comma as the decimal
separator, the following table demonstrates the results:
Function Call
Result returned
FormatNumber$("12345.67")
FormatNumber$("12,345.67")
See Also:
DeformatNumber$( ) function
FormatTime$( ) function
Purpose
Returns a string representing a time using the format specified in the second argument. You can call
this function from the MapBasic window in MapInfo Professional.
Note: The FormatDate$( ) function is not configurable whereas the FormatTime$( ) function provides
full control of the output.
The format string should follow the same Microsoft standards as for setting the locale time format:
Hours
Meaning
hh
HH
Minutes
Meaning
Reference
319
FormatTime$( ) function
Hours
Meaning
mm
Seconds
Meaning
ss
Time marker
Meaning
tt
Source: http://msdn2.microsoft.com/en-us/library/ms776320.aspx
Note: In the preceding formats, the letters m, s, and t must be lowercase, and the letter h must be
lowercase to denote the 12-hour clock or uppercase to denote the 24-hour clock.
Our code follows the rules for specifying the system local time format. In addition, we also allow the user
to specify f, ff, or fff for tenths of a second, hundredths of a second, or milliseconds.
Syntax
FormatTime$( Time, String )
Return Value
String
Example
Copy this example into the MapBasic window for a demonstration of this function.
dim Z as time
Z = CurTime()
Print FormatTime$(Z, "hh:mm:ss.fff tt")
See Also:
FormatDate$( ) function, GetTime() function, NumberToDateTime( ) function
320
MapBasic 12.0
FrontWindow( ) function
Purpose
Returns the integer identifier of the active window. You can call this function from the MapBasic window
in MapInfo Professional.
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 (for example,
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( ) function, WindowID( ) function, WindowInfo( ) function
Reference
321
322
MapBasic 12.0
Reference
323
Geocode statement
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
Function CubeRoot(ByVal x As Float) As Float
CubeRoot = x ^ 0.33333333333
End Function
See Also:
Declare Function statement, Declare Sub statement, Sub...End Sub statement
Geocode statement
Purpose
Geocodes a table or individual value using a remote geocode service through a connection created using
the Open Connection statement and set up using the Set Connection Geocode statement. You can
issue this statement from the MapBasic window in MapInfo Professional.
Syntax
Geocode connection_number
Input
[ Table input_tablename ]
[ Country = Country_expr
[ Street = Street_expr,
[ IntersectingStreet = IntersectingStreet_expr ],
Municipality = Municipality_expr,
CountrySubdivision = CountrySubdiv_expr,
PostalCode = PostalCode_expr,
CountrySecondarySubdivision = CountrySecondarySubdiv_expr,
SecondaryPostalCode = SecondaryPostalCode_expr,
Placename = Placename_expr,
Street2 = Street2_expr,
MunicipalitySubdivision = MunicipalitySubdiv_expr ] ]
Output
[ Into
[ Table out_tablename [ Key out_keycolumn = in_keyexpr ] ] |
[ Variable variable_name ] ]
[ Point [ On | Off ] [ Symbol Symbol_expr ], ]
[ Street_column = Street,
Municipality_column = Municipality,
CountrySubdiv_column = CountrySubdivision,
PostalCode_column = PostalCode,
324
MapBasic 12.0
Reference
325
Geocode statement
Street_column is an alias that represents the name of the column to hold the Street result.
Municipality_column is a string the represents the name of the column to hold the Municipality result.
CountrySubdiv_column is a string the represents the name of the column to hold the Country Subdivision
result.
PostalCode_column is a string the represents the name of the column to hold the Postal Code result.
CountrySecondarySubdiv_column is a string the represents the name of the column to hold the Country
Secondary Subdivision result.
SecondaryPostalCode_column is a string the represents the name of the column to hold the Secondary
Postal Code result.
Placename_column is a string the represents the name of the column to hold the Placename result.
MunicipalitySubdiv_column is a string the represents the name of the column to hold the Municipality
Subdivision result.
Country_column is a string the represents the name of the column to hold the Country result.
ResultCode_column is a string the represents the name of the column to hold the Result Code generated
by the geocoder.
Latitude_column is a string the represents the name of the float or decimal column to hold the Latitude
result.
Longitude_column is a string the represents the name of the float or decimal column to hold the Longitude
result.
colname is a string the represents the name of the column for a geocoder-specific result.
geocoder_keyname is a string representing the name of a country-specific geocoder item. These items
are documented by the specific geocoder.
candidates_expr is an expression that specifies the number of candidates to be returned in an interactive
geocoding session.
Description
Every Geocode statement must include an Input clause and an Output clause. The input_tablename
is optional, however if a table is not specified, the resulting geocode operation would be performed on
a set of string inputs (variables or constants), so that only a single address is geocoded in each request.
The output_tablename is also optional. See Table vs. non-table- based input and output below.
Input clause
The Input clause is required as a geocode request needs some input data.
A Country must be specified either as an explicit argument or as a column in input_tablename. When
a single country is used, it can be a constant string if no data is available. ISO standard three letter
country codes must be used.
The list of fields to include from input_table to be geocoded must include at least one value. The more
expressions that are included, the more accurate your geocoding result will be.
326
MapBasic 12.0
Reference
327
GeocodeInfo( ) function
Interactive is equivalent to Interactive On. When no value is provided for Max the default is three (3)
candidates to be returned.
Interactive On Max Candidates All returns all candidates
Interactive On Max Candidates 4* myMBVariable/6 returns the number of candidates resulting
from the evaluation of the expression.
Interactive Off is equivalent to Interactive Off None.
Interactive Off First returns the first candidate in the list.
The CloseMatchesOnly setting sets the geocode service to only return close matches as defined by
the server. If CloseMatchesOnly is set to Off, all results are returned up to the number defined in Max
Candidates with the ones that are considered to be close marked as such.
Examples
The following example shows a geocode request using the nystreets table and specifying the use of the
city, Streetname, state, and postalcode.
Geocode connectionHandle Input Table nystreets municipality=city,
street=StreetName, countrysubdivision=state, postalcode=zip,
country="usa"
OUTPUT StreetName=street, address=municipality
This example shows a geocode request using the nystreets table and specifying a symbol for displaying
the output.
Geocode connectionHandle Input Table nystreets street=StreetName,
country="usa"
Output Point Symbol MakeFontSymbol(65, 255 ,24,"MapInfo
Cartographic",32,0), StreetName=street
This example sends a request with the Interactive set to On with the return value being placed into the
street column.
Geocode connectionHandle Input Table nystreets street=StreetName,
country="usa"
Output Point Symbol MakeFontSymbol(65, 255 ,24,"MapInfo
Cartographic",32,0),
StreetName=street Interactive on Max Candidates 5
The following example shows a Geocode request without using a table and outputting the results into a
variable:
Geocode connectionHandle Input street="1 Global View", country="usa",
countrysubdivison="NY", municipality="Troy"
Output Variable outvar
See Also:
Open Connection statement
GeocodeInfo( ) function
Purpose
Returns any and all attributes that were set on a connection using the Set Connection Geocode
statement. In addition, GeocodeInfo( ) can also return some status values from the last geocode
command issued using each connection. There is also an attribute to handle the maximum number of
328
MapBasic 12.0
ID
GEOCODE_STREET_NAME
GEOCODE_STREET_NUMBER
GEOCODE_MUNICIPALITY
GEOCODE_MUNICIPALITY2
GEOCODE_COUNTRY_SUBDIVISION
GEOCODE_COUNTRY_SUBDIVISION2
GEOCODE_POSTAL_CODE
GEOCODE_DICTIONARY
GEOCODE_BATCH_SIZE
Reference
10
DICTIONARY_ALL
DICTIONARY_ADDRESS_ONLY
DICTIONARY_USER_ONLY
DICTIONARY_PREFER_ADDRESS
DICTIONARY_PREFER_USER
329
GeocodeInfo( ) function
attribute Value
ID
GEOCODE_FALLBACK_GEOGRAPH- 11
IC
GEOCODE_FALLBACK_POSTAL
12
GEOCODE_OFFSET_CENTER
13
GEOCODE_OFFSET_CENTER_UNITS
14
GEOCODE_OFFSET_END
15
GEOCODE_OFFSET_END_UNITS
16
GEOCODE_MIXED_CASE
17
GEOCODE_RESULT_MARK_MULTIPLE
18
330
GEOCODE_COUNT_GEOCODED
19
Integer value representing the number of records geocoded during the last operation.
GEOCODE_COUNT_NOTGEOCODED
20
GEOCODE_UNABLE_TO_CONVERT_DATA
21
MapBasic 12.0
ID
GEOCODE_MAX_BATCH_SIZE
22
Integer value representing the maximum number of records (for example, addresses) that the server will permit
to be sent to the service at one time.
GEOCODE_PASSTHROUGH
GEOCODE_PASSTHROUGH + n
Example
The following MapBasic snippet will print the Envinsa Location Utility Constraints to the message window
in MapInfo Professional:
Include "MapBasic.Def"
declare sub main
sub main
dim iConnect as integer
Open Connection Service Geocode Envinsa
URL
"http://envinsa_server:8066/LocationUtility/services/LocationUtility"
User "john"
Password "green"
into variable iConnect
Print "Geocode Max Batch Size: " +
GeoCodeInfo(iConnect,GEOCODE_MAX_BATCH_SIZE)
end sub
See Also:
Open Connection statement, Set Connection Geocode statement
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.
Reference
331
GetCurrentPath$( ) function
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:
Variable Type
Storage In File
Logical
SmallInt
Integer
Float
String
Date
Cannot be read.
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 statement, Put statement
GetCurrentPath$( ) function
Purpose
Returns the path location used by a MapInfo Professional File dialog. Each type of table or file has its
own remembered location.
You can call this function from the MapBasic window in MapInfo Professional.
332
MapBasic 12.0
Example
Copy this example into the MapBasic window for a demonstration of this function.
include "mapbasic.def"
declare sub main
sub main
dim sMiPrfFile as string
sMiPrfFile = GetCurrentPath$( PREFERENCE_PATH_WORKSPACE)
Print sMiPrfFile
end sub
See Also:
GetPreferencePath$( ) function
GetDate( ) function
Purpose
Returns the Date component of a DateTime. You can call this function from the MapBasic window in
MapInfo Professional.
Reference
333
GetFolderPath$( ) function
Syntax
GetDate( DateTime )
Return Value
Date, which is an integer value in four bytes: two bytes for the year, one byte for the month, one byte
for the day.
Example
Copy this example into the MapBasic window for a demonstration of this function.
dim dtX as datetime
dim Z as date
dtX = "03/07/2007 12:09:09.000 AM"
Z = GetDate(dtX)
Print FormatDate$(Z)
See Also:
GetTime() function
GetFolderPath$( ) function
Purpose
Returns the path of a special MapInfo Professional or Windows directory. You can call this function from
the MapBasic window in MapInfo Professional.
Syntax
GetFolderPath$( folder_id )
folder_id is one of the following values:
FOLDER_MI_APPDATA (-1)
FOLDER_MI_LOCAL_APPDATA (-2)
FOLDER_MI_PREFERENCE (-3)
FOLDER_MI_COMMON_APPDATA (-4)
FOLDER_APPDATA (26)
FOLDER_LOCAL_APPDATA (28)
FOLDER_COMMON_APPDATA (35)
FOLDER_COMMON_DOCS (46)
FOLDER_MYDOCS (5)
FOLDER_MYPICS (39)
Return Value
String
Description
Given the ID of a special MapInfo or Windows directory, GetFolderPath$( ) function returns the path of
the directory. An example of a special Windows directory is the My Documents directory. An example
of a special MapInfo directory is the preference directory; the default location to which MapInfo Professional writes out the preference file.
334
MapBasic 12.0
GetGridCellValue( ) function
Purpose:
Determines the value of a grid cell if the cell is non-null.
Syntax:
GetGridCellValue( table_id, x_pixel, y_pixel )
table_id is a string representing a table name, a positive integer table number, or 0 (zero). The table
must be a grid table.
x_pixel is the integer number of the X coordinate of the grid cell. Pixel numbers start at 0. The maximum
pixel value is the (pixel_width-1), determined by calling
RasterTableInfo(...RASTER_TAB_INFO_WIDTH).
y_pixel is the integer number of the Y coordinate of the grid cell. Pixel numbers start at 0. The maximum
pixel value is the (pixel_height-1), determined by calling
RasterTableInfo(...RASTER_TAB_INFO_HEIGHT).
Return Value
A Float is returned, representing the value of a specified cell in the table if the cell is non-null. The IsGridCellNull() function should be used before calling this function to determine if the cell is null or if it contains
a value.
See Also:
Create Grid statement, GridTableInfo( ), IsGridCellNull( ) function, RasterTableInfo( ) function
Reference
335
GetMetadata$( ) function
GetMetadata$( ) function
Purpose
Retrieves metadata from a table. You can call this function from the MapBasic window in MapInfo Professional.
Syntax
GetMetadata$( table_name, key_name )
table_name is the name of an open table, specified either as an explicit table name (for example, World)
or as a string representing a table name (for example, "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 Metadata statement, or see the MapBasic User 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 statement
GetPreferencePath$( ) function
Purpose
Returns the path location stored in MapInfo Professional preferences for each type of table or files' dialog.
This path is used to initialize the dialog path the first time that dialog is used in a MapInfo Professional
session or after the path is changed in the Preferences dialog.
You can call this function from the MapBasic window in MapInfo Professional.
Syntax
GetPreferencePath$( preference_path_id )
preference_path_id is one of the following values:
336
MapBasic 12.0
PREFERENCE_PATH_TABLE (0)
PREFERENCE_PATH_WORKSPACE (1)
PREFERENCE_PATH_MBX (2)
PREFERENCE_PATH_IMPORT (3)
PREFERENCE_PATH_SQLQUERY (4)
PREFERENCE_PATH_THEMETHEMPLATE (5)
PREFERENCE_PATH_MIQUERY (6)
PREFERENCE_PATH_NEWGRID (7)
PREFERENCE_PATH_CRYSTAL (8)
PREFERENCE_PATH_GRAPHSUPPORT (9)
PREFERENCE_PATH_REMOTETABLE (11)
PREFERENCE_PATH_WFSTABLE (12)
PREFERENCE_PATH_WMSTABLE (13)
Return Value
String
Description
Given the ID of a special MapInfo Preference directory, the GetPreferencePath$( ) function returns the
path of the directory. An example of a special MapInfo directory is the default location to which MapInfo
Professional writes out new native MapInfo tables.
Example
include "mapbasic.def"
declare sub main
sub main
dim sMiPrfFile as string
sMiPrfFile = GetPreferencePath$( PREFERENCE_PATH_WORKSPACE)
Print sMiPrfFile
end sub
See Also:
GetCurrentPath$( ) function, LocateFile$( ) function
GetSeamlessSheet( ) function
Purpose
Prompts the user to select one sheet from a seamless table, and then returns the name of the chosen
sheet. You can call this function from the MapBasic window in MapInfo Professional.
Syntax
GetSeamlessSheet( table_name )
table_name is the name of a seamless table that is open.
Reference
337
GetTime() function
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
If TableInfo(s_tab_name, TAB_INFO_SEAMLESS) Then
s_sheet = GetSeamlessSheet(s_tab_name)
If s_sheet <> "" Then
Browse * From s_sheet
End If
Else
Browse * from s_tab_name
End If
End Sub
See Also:
Set Table statement, TableInfo( ) function
GetTime() function
Purpose
Returns the Time component of a DateTime. You can call this function from the MapBasic window in
MapInfo Professional.
Syntax
GetTime( DateTime )
Return Value
Time, which is an integer value in five bytes: 2 for millisec, 1 for sec, 1 for min, 1 for hour.
Example
Copy this example into the MapBasic window for a demonstration of this function.
dim dtX as datetime
dim Z as time
dtX = "03/07/2007 12:09:09.000 AM"
Z = GetTime(dtX)
Print FormatTime$(Z,"hh:mm:ss.fff tt")
See also:
338
MapBasic 12.0
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 (for example, 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 statement, ReDim statement, Type statement, UBound( ) function
Reference
339
Goto statement
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
statement and Exit For statement 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
...
endproc: End Program
See Also:
Do Case...End Case statement, Do...Loop statement, For...Next statement, OnError statement,
Resume statement
Graph statement
Purpose
Opens a new Graph window. You can call this function from the MapBasic window in MapInfo Professional.
Syntax
Graph
label_column, expr ["label_text"][ , ... ]
From table
340
MapBasic 12.0
label_column is the name of the column to use for labeling the y-axis.
expr is an expression providing values to be graphed.
label_text is the text that displays for each label column instead of the column name
table is the name of an open table.
paperunits is the name of a paper unit (for example, "in").
x, y specifies the position of the upper left corner of the Grapher, in paper units. For details about paper
units, see Set Paper Units statement.
window_width and window_height specify the size of the Grapher, in paper units. For a list of paper unit
names, see Set Paper Units statement.
template_file is a valid graph template file.
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 Series In Columns is included, then the graph
series are based on the table columns. Otherwise the series are based on the table rows.
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 (for example, the graph rotation, graph type, title, etc.).
MapInfo Professional 's Window > Graph dialog box 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 box 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 MapInfo Professional. 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
Reference
341
GridTableInfo( ) function
Example (pre-5.5 graphs)
Graph Country, Population From Selection
See Also:
Set Graph statement
GridTableInfo( ) function
Purpose
Returns information about a grid table.
Syntax
GridTableInfo( table_id, attribute )
table_id is a string representing a table name, a positive integer table number, or 0 (zero). The table
must be a grid table.
attribute is an integer code indicating which aspect of the grid table to return.
Return Value
String, SmallInt, Integer or Logical, depending on the attribute parameter specified.
The attribute parameter can be any value from the table below. Codes in the left column (for example,
GRID_TAB_INFO_) are defined in MAPBASIC.DEF.
attribute code
ID
GridTableInfo() returns:
GRID_TAB_INFO_MIN_VALUE
GRID_TAB_INFO_MAX_VALUE
GRID_TAB_INFO_HAS_HILLSHADE 3
See Also:
Create Grid statement, GetGridCellValue( ) function, IsGridCellNull( ) function, RasterTableInfo(
) function
GroupLayerInfo function
Purpose
This function returns information about a specific group layer in the map.
342
MapBasic 12.0
ID
Description
GROUPLAYER_INFO_NAME
GROUPLAYER_INFO_LAYERLIST_ID
GROUPLAYER_INFO_DISPLAY
GROUPLAYER_INFO_LAYERS
GROUPLAYER_INFO_ALL_LAYERS 5
GROUPLAYER_INFO_TOPLEVEL_LAYERS
GROUPLAYER_INFO_PARENT_GROUP_ID
Returns the group layer ID of the immediate group containing this group, will return zero (0) if group layer is in the
top level list.
Group layer ID's are from zero (0) to n, where n is the number of group layers in the list and zero (0)
refers to top level, or "root" of the layer list. All the group layer info attributes will apply to the root of the
list with the exception of GROUPLAYER_INFO_DISPLAY (3). GROUPLAYER_INFO_NAME (1) will
return the map's name (same as its window title). The cosmetic layer will be included in any of the attributes that count graphical layers.
Reference
343
HomeDirectory$( ) function
Specifying a map window ID of zero (0) returns the name of the map window, and returns the name of
the Cosmetic Layer as "cosmetic1", "cosmetic2".
See Also:
LayerInfo( ) function, MapperInfo( ) function
HomeDirectory$( ) function
Purpose
Returns a string indicating the user's home directory path. You can call this function from the MapBasic
window in MapInfo Professional.
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.
Environment
Windows
Example
Dim s_home_dir As String
s_home_dir = HomeDirectory$( )
See Also:
ApplicationDirectory$( ) function, ProgramDirectory$( ) function, SystemInfo( ) function
HotlinkInfo( ) function
Purpose
Returns information about a HotLink definition in a map layer. You can call this function from the MapBasic
window in MapInfo Professional.
Syntax
HotlinkInfo ( map_window_id, layer_number, hotlink_number, attribute )
map_window_id is a Map window identifier.
344
MapBasic 12.0
ID
Description
HOTLINK_INFO_EXPR
HOTLINK_INFO_MODE
HOTLINK_INFO_RELATIVE
HOTLINK_INFO_ENABLED
HOTLINK_INFO_ALIAS
See Also:
Set Map statement, LayerInfo( ) function
Hour( ) function
Purpose
Retrieves the hour component of a Time value as an integer (0-23). You can call this function from the
MapBasic window in MapInfo Professional.
Syntax
Hour ( Time )
Return Value
SmallInt
Example
Copy this example into the MapBasic window for a demonstration of this function.
dim Z as time
dim iHour as integer
Z = CurDateTime()
iHour = Hour(Z)
Print iHour
Reference
345
If...Then statement
See Also:
Minute( ) function, Second( ) function
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 if_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
346
MapBasic 12.0
Import statement
Purpose
Creates a new MapInfo Professional table by importing an exported file, such as a GML or DXF file. You
can issue this statement from the MapBasic window in MapInfo Professional.
See Importing MIF/MID, PICT, or MapInfo for DOS Files, Importing DXF Files, Importing GML Files,
or Importing GML 2.1 Files.
Reference
347
Import statement
[ Into table_name ]
[ Overwrite ]
file_name is a string that specifies the name of the file to import.
file_type is a string that specifies the import file format (MIF, MBI, MMI, IMG, or PICT).
table_name specifies the name of the new table to create.
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 optional Type clause specifies the format of the file you want to import. The Type clause can take
one of the following forms:
Type clause
Type "DXF"
Type "MIF"
Type "MBI"
Type "MMI"
Type "IMG"
Type "GML"
Type "GML21"
If you omit the Type clause, MapInfo Professional assumes that the file's extension indicates the file
format. For example, a file named "PARCELS.DXF" is assumed to be a DXF file. (For more about DXF,
see Importing DXF Files.)
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 file name. For example, on Windows, if you import the text file "WORLD.MIF", the new
table's default name is "WORLD.TAB".
If you include the optional Overwrite keyword, MapInfo Professional creates a new table, regardless of
whether a table by that name already exists; the new table replaces the existing table. If you omit the
Overwrite keyword, and the table already exists, MapInfo Professional does not overwrite the table.
348
MapBasic 12.0
Reference
349
Import statement
Preserve AttributeData - Include this clause if you want MapInfo Professional to preserve the attribute
data from the DXF file.
Preserve Blocks As MultiPolygonRgns - Include this clause if you want MapInfo Professional to store
all of the polygons from a DXF block record into one multiple-polygon region object. If you omit this
clause, each DXF polygon becomes a separate MapInfo Professional region object.
CoordSys - Controls the projection and coordinate system of the table. For details, see CoordSys
clause.
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,
MapInfo Professional stores each object's center elevation in a column called _DXFElevation. (For lines,
MapInfo Professional stores the elevation at the center of the line; for regions, MapInfo Professional
stores the average of the object's elevation values.) If you include VisibleOnly, MapInfo Professional
ignores invisible objects.
Layer clause - 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,
MapInfo Professional 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
350
MapBasic 12.0
Reference
351
Include statement
Overwrite causes the TAB file to be automatically overwritten. If Overwrite is not specified, an error will
result if the TAB file already exists.
The Coordsys clause is optional. If the GML file contains a supported projection and the Coordsys
clause is not specified, the projection from the GML file will be used. If the GML file contains a supported
projection and the Coordsys clause is specified, the projection from the Coordsys clause will be used.
If the GML file does not contain a supported projection, the Coordsys clause must be specified.
Note: If the Coordsys clause does not match the projection of the GML file, your data may not import
correctly. The coordinate system must match the coordinate system of the data in the GML file.
It will not transform the data from one projection to another.
Example
Sample importing using GML21 style:
Import "D:\midata\GML\GML2.1\mi_usa.xml" Type "GML21" layer "USA" Into
"D:\midata\GML\GML2.1\mi_usa_USA.TAB" Overwrite CoordSys Earth Projection
1, 104
See Also:
Export statement
Include statement
Purpose
Incorporates the contents of a separate text file as part of a MapBasic program. Issuing this statement
from the MapBasic window in MapInfo Professional does not work.
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.
352
MapBasic 12.0
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 the Open File statement.
var_name is the name of a variable.
Description
The Input # statement reads data from a file which was opened in a sequential mode (for example, 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 statement.
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 MapInfo Professional was
able to read the data. If the input was successful, the EOF( ) function returns FALSE; if the end-of-file
was reached before the input was completed, the EOF( ) function 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
Object
Reference
353
Insert statement
See Also:
EOF( ) function, Line Input statement, Open File statement, Write # statement
Insert statement
Purpose
Appends new rows to an open table. You can issue this statement from the MapBasic window in MapInfo
Professional.
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 Table
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.
Examples
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")
354
MapBasic 12.0
InStr( ) function
Purpose
Returns a character position, indicating where a substring first appears within another string. You can
call this function from the MapBasic window in MapInfo Professional.
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.
Reference
355
Int( ) function
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 (644) 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)
pos = InStr(1, fullname, "YORK")
' pos will now contain a value of 0;
' YORK is uppercase, so InStr will not locate it
' within the string "New York City"
See Also:
Mid$( ) function
Int( ) function
Purpose
Returns an integer value obtained by removing the fractional part of a decimal value. You can call this
function from the MapBasic window in MapInfo Professional.
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( ) function will return the nearest integer value greater than or equal to the original value; so, the
function call Fix(-2.3) will return a value of -2. But when the Int( ) function is passed a negative frac-
356
MapBasic 12.0
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. You can call this function from the MapBasic window in MapInfo
Professional.
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.
IsGridCellNull( ) function
Purpose
Returns a Logical. Returns TRUE if the cell value location (x, y) is valid for the table, and is a null cell (a
cell that does not have an assigned value). Returns FALSE if the cell contains a value that is non-null.
The GetCellValue() function can be used to retrieve the value.
Reference
357
IsogramInfo( ) function
Syntax
IsGridCellNull( table_id, x_pixel, y_pixel )
table_id is a string representing a table name, a positive integer table number, or 0 (zero). The table
must be a grid table.
x_pixel is the integer pixel number of the X coordinate of the grid cell. Pixel numbers start at 0. The
maximum pixel value is the (pixel_width-1), determined by calling
RasterTableInfo(...RASTER_TAB_INFO_WIDTH)
y_pixel is the integer pixel number of the Y coordinate of the grid cell. Pixel numbers start at 0. The
maximum pixel value is the (pixel_height-1), determined by calling
RasterTableInfo(...RASTER_TAB_INFO_HEIGHT).
Return Value
A Logical is returned, representing whether the specified cell in the table is null, or non-null. If the grid
cell is non-null (IsGridCellNull() returns FALSE), then the GetGridCellValue() function can be called to
retrieve the value for that grid pixel.
See Also:
Create Grid statement, GetGridCellValue( ) function, GridTableInfo( ), RasterTableInfo( ) function
IsogramInfo( ) function
Purpose
Returns any and all attributes that were set on a connection using the Set Connection Isogram statement. Includes attributes to handle the maximum number of records for server, time, and distance values.
You can call this function from the MapBasic window in MapInfo Professional.
Syntax
IsogramInfo( connection_handle, attribute )
connection_handle is an integer signifying the number of the connection returned from the Open Connection statement.
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
This function returns the properties defaulted by the connection or the properties that have been changed
using the Set Connection Isogram statement.
There are several attributes that IsogramInfo( ) can return. Codes are defined in MAPBASIC.DEF.
358
MapBasic 12.0
ID
ISOGRAM_BANDING
ISOGRAM_MAJOR_ROADS_ONLY 2
ISOGRAM_RETURN_HOLES
ISOGRAM_MAJOR_POLYGON_ONLY
ISOGRAM_MAX_OFF_ROAD_DISTANCE
ISOGRAM_MAX_OFF_ROAD_DISTANCE_UNITS
ISOGRAM_SIMPLIFICATION_FACTOR
Float value representing the Simplification Factor. (a percent value represented as a value between 0 and 1.
ISOGRAM_DEFAULT_AMBIENT_SPEED
ISOGRAM_DEFAULT_AMBIENT_SPEED_DISTANCE_UNIT
ISOGRAM_DEFAULT_AMBIENT_SPEED_TIME_UNIT
10
ISOGRAM_DEFAULT_PROPAGATION_FACTOR
11
Determines the off-road network percentage of the remaining cost (distance) for which off network travel is allowed
when finding the Distance boundary. Roads not identified
in the network can be driveways or access roads, among
others. The propagation factor is a percentage of the cost
used to calculate the distance between the starting point
and the Distance. The default value for this property is
0.16.
ISOGRAM_BATCH_SIZE
12
Integer value representing the maximum number of records that are sent to the service at one time.
ISOGRAM_POINTS_ONLY
13
Logical representing the whether or not records that contain non-point objects should be skipped.
ISOGRAM_RECORDS_INSERTED
14
ISOGRAM_RECORDS_NOTINSER- 15
TED
ISOGRAM_MAX_BATCH_SIZE
Integer value representing the maximum number of records (for example, points) that the server will permit to
be sent to the service at one time.
Reference
16
359
IsPenWidthPixels( ) function
attribute setting
ID
ISOGRAM_MAX_BANDS
17
ISOGRAM_MAX_DISTANCE
18
ISOGRAM_MAX_DISTANCE_UNITS 19
ISOGRAM_MAX_TIME
20
ISOGRAM_MAX_TIME_UNITS
21
Example
The following MapBasic snippet will print the Envinsa Routing Constraints to the message window in
MapInfo Professional:
Include "MapBasic.Def"
declare sub main
sub main
dim iConnect as integer
Open Connection Service Isogram
URL "http://envinsa_server:8062/Route/services/Route"
User "john"
Password "green"
into variable iConnect
Print "Isogram_Max_Batch_Size: " +
IsogramInfo(iConnect,Isogram_Max_Batch_Size)
Print "Isogram_Max_Bands: " + IsogramInfo(iConnect, Isogram_Max_Bands)
Print "Isogram_Max_Distance: " + IsogramInfo(iConnect,
Isogram_Max_Distance)
Print "Isogram_Max_Distance_Units: " + IsogramInfo(iConnect,
Isogram_Max_Distance_Units)
Print "Isogram_Max_Time: " + IsogramInfo(iConnect,Isogram_Max_Time)
Print "Isogram_Max_Time_Units: " +
IsogramInfo(iConnect,Isogram_Max_Time_Units)
Close Connection iConnect
end sub
See Also:
Create Object statement, Open Connection statement, Set Connection Isogram statement
IsPenWidthPixels( ) function
Purpose
The IsPenWidthPixels function determines if a pen width is in pixels or in points. You can call this function
from the MapBasic window in MapInfo Professional.
360
MapBasic 12.0
Kill statement
Purpose
Deletes a file. You can issue this statement from the MapBasic window in MapInfo Professional.
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"
Reference
361
LabelFindByID( ) function
See Also:
Open File statement
LabelFindByID( ) function
Purpose
Initializes an internal label pointer, so that you can query the label for a specific row in a map layer. You
can call this function from the MapBasic window in MapInfo Professional.
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 (for example, 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 the LabelInfo( )
function.
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
Open Table "World" Interactive As World
Map From World
i_mapid = FrontWindow( )
Set Map Window i_mapid Layer 1 Label Auto On
' Make sure all labels draw before we continue...
Update Window i_mapid
' Now see if row # 1 was auto-labeled
b_morelabels = LabelFindByID(i_mapid, 1, 1, "", TRUE)
If b_morelabels Then
' The object was labeled; now query its label.
obj_mytext = LabelInfo(i_mapid, 1, LABEL_INFO_OBJECT)
362
MapBasic 12.0
LabelFindFirst( ) function
Purpose
Initializes an internal label pointer, so that you can query the first label in a map layer. You can call this
function from the MapBasic window in MapInfo Professional.
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 (for example, 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 the LabelFindFirst( ) function, the LabelFindNext(
) function, or the LabelFindByID( ) function.
2. If the function you called in step 1 did not return FALSE, you can query the current label by calling
the LabelInfo( ) function.
To continue querying additional labels, return to step 1.
Example
For an example, see LabelInfo( ) function.
See Also:
LabelFindByID( ) function, LabelFindNext( ) function, LabelInfo( ) function
Reference
363
LabelFindNext( ) function
LabelFindNext( ) function
Purpose
Advances the internal label pointer, so that you can query the next label in a map layer. You can call
this function from the MapBasic window in MapInfo Professional.
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 (for example, 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 the LabelFindFirst( ) function to begin querying labels, you can call LabelFindNext( ) to
advance to the next label in the same layer.
Example
For an example, see LabelInfo( ) function.
See Also:
LabelFindByID( ) function, LabelFindFirst( ) function, LabelInfo( ) function
LabelInfo( ) function
Purpose
Returns information about a label in a map. LabeIInfo can return a label as text object and the text object
returned can be curved or can be returned as rotated straight text. However, if the label is curved, it will
be returned as rotated flat text. You can call this function from the MapBasic window in MapInfo Professional.
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 (for example, 1 for the top layer).
attribute is a code indicating the type of information to return; see table below.
364
MapBasic 12.0
ID
LABEL_INFO_OBJECT
LABEL_INFO_POSITION
Integer value between 0 and 8, indicating the label's position relative to its anchor location. The return value will
match one of these codes:
LAYER_INFO_LBL_POS_AUTO (-1),
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).
Reference
365
LabelInfo( ) function
attribute code
ID
LABEL_INFO_ANCHORX
LABEL_INFO_ANCHORY
LABEL_INFO_OFFSET
LABEL_INFO_ROWID
LABEL_INFO_TABLE
LABEL_INFO_EDIT
LABEL_INFO_EDIT_VISIBILITY
LABEL_INFO_EDIT_ANCHOR
10
LABEL_INFO_EDIT_OFFSET
11
LABEL_INFO_EDIT_FONT
12
LABEL_INFO_EDIT_PEN
13
LABEL_INFO_EDIT_TEXT
14
LABEL_INFO_EDIT_TEXTARROW
15
LABEL_INFO_EDIT_ANGLE
16
LABEL_INFO_EDIT_POSITION
17
LABEL_INFO_EDIT_TEXTLINE
18
LABEL_INFO_SELECT
19
LABEL_INFO_DRAWN
20
LABEL_INFO_ORIENTATION
21
Returns Smallint value indicating the 'current' label's orientation. The current label is initialized by using one of
the following Label functions: LabelFindFirst, LabelFindByID, or LabelFindNext. The Return value will be one of
these:
LAYER_INFO_LABEL_ORIENT_HORIZONTAL (label
has angle equal to 0)
366
MapBasic 12.0
ID
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( ) function, LabelFindFirst( ) function, LabelFindNext( ) function
LabelOverrideInfo( ) function
Returns information about a specific label override.
Syntax
LabelOverrideInfo (
window_id, layer_number, labeloverride_index, attribute )
window_id is the integer window identifier of a Map window.
layer_number is the number of a layer in the current Map window (for example, 1 for the top layer); to
determine the number of layers in a Map window, call the MapperInfo( ) function.
labeloverride_index is an integer index (1-based) for the override definition within the layer. Each label
override is tied to an zoom range and is ordered so that the smallest zoom range value is on top (index
1).
attribute is a code indicating the type of information to return; see table below.
Return Value
Return value depends on attribute parameter.
Reference
367
LabelOverrideInfo( ) function
Description
The LabelOverrideInfo( ) function returns label information for a specific label override for one layer
in an existing Map window. The layer_number must be a valid 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.
Attribute Code
ID
LBL_OVR_INFO_NAME
LBL_OVR_INFO_VISIBILITY
LBL_OVR_INFO_ZOOM_MIN
Float value, indicating the minimum zoom value (in MapBasic's current distance units) at which the label override
displays.
LBL_OVR_INFO_ZOOM_MAX
LBL_OVR_INFO_EXPR
LBL_OVR_INFO_LT
368
LBL_OVR_INFO_FONT
LBL_OVR_INFO_PARALLEL
MapBasic 12.0
ID
LBL_OVR_INFO_POS
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)
LBL_OVR_INFO_OVERLAP
10
LBL_OVR_INFO_DUPLICATES
11
LBL_OVR_INFO_OFFSET
12
LBL_OVR_INFO_MAX
13
LBL_OVR_INFO_PARTIALSEGS
14
LBL_OVR_INFO_ORIENTATION
15
LBL_OVR_INFO_ALPHA
16
Reference
369
LabelOverrideInfo( ) function
Attribute Code
ID
370
LBL_OVR_INFO_AUTODISPLAY
17
LBL_OVR_INFO_POS_RETRY
18
LBL_OVR_INFO_LINE_PEN
19
LBL_OVR_INFO_PERCENT_OVER 20
LBL_OVR_INFO_AUTO_POSITION 21
LBL_OVR_INFO_AUTO_SIZES
22
LBL_OVR_INFO_SUPPRESS_IF_NO_FIT
23
LBL_OVR_INFO_AUTO_SIZE_STEP 24
LBL_OVR_INFO_CURVED_BEST_PO- 25
SITION
LBL_OVR_INFO_CURVED_FALLBACK
26
LBL_OVR_INFO_USE_ABBREVIATION
27
LBL_OVR_INFO_ABBREVIATION_EXPR
28
MapBasic 12.0
ID
LBL_OVR_INFO_AUTO_CALLOUT
29
Example
LabelOverrideInfo(nMID, nLayer, nOverride, LBL_OVR_INFO_ORIENTATION)
See Also:
StyleOverrideInfo( ) function, LayerStyleInfo( ) function, Set Map statement, LayerInfo( ) function
LayerControlInfo( ) function
Purpose
Returns information about the Layer Control window.
Syntax
LayerControlInfo( attribute )
attribute is a code indicating the type of information to return; see table below.
Description
The attribute parameter is a value from the table below. Codes in the left column are defined in MAPBASIC.DEF.
attribute code
ID
TableInfo( ) returns
LC_INFO_SEL_COUNT
Example
LayerControlInfo(LC_INFO_SEL_COUNT)
See Also:
LayerControlSelectionInfo( ) function
LayerControlSelectionInfo( ) function
Purpose
Returns information about a selected item in the Layer Control window.
Syntax
LayerControlSelectionInfo( selection_index, attribute )
selection_id is the index of a selected item in Layer Control.
Reference
371
LayerInfo( ) function
attribute is a code indicating the type of information to return; see table below.
Description
The attribute parameter can be any value from the table below. Codes in the left column are defined in
MAPBASIC.DEF.
attribute code
ID
TableInfo( ) returns
LC_SEL_INFO_NAME
LC_SEL_INFO_TYPE
LC_SEL_INFO_TYPE_MAP (0)
LC_SEL_INFO_TYPE_LAYER (1)
LC_SEL_INFO_TYPE_GROUPLAYER (2)
LC_SEL_INFO_TYPE_STYLE_OVR (3)
LC_SEL_INFO_TYPE_LABEL_OVR (4)
LC_SEL_INFO_MAPWIN_ID
LC_SEL_INFO_LAYER_ID
LC_SEL_INFO_OVR_ID
Smallint value, indicating the index of the override associated with the selected item. If you query this value when
a map, layer, or grouplayer item is selected, the return
value is -1.
Example
LayerControlSelectionInfo(layer_number, LC_SEL_INFO_NAME)
See Also:
LayerControlInfo( ) function
LayerInfo( ) function
Purpose
Returns information about a layer in a Map window. You can call this function from the MapBasic window
in MapInfo Professional.
Syntax
LayerInfo( window_id, layer_number, attribute )
window_id is the integer window identifier of a Map window.
372
MapBasic 12.0
ID
LAYER_INFO_NAME
LAYER_INFO_EDITABLE
LAYER_INFO_SELECTABLE
LAYER_INFO_ZOOM_LAYERED
LAYER_INFO_ZOOM_MIN
Float value, indicating the minimum zoom value (in MapBasic's current distance units) at which the layer displays.
(To set MapBasic's distance units, use Set Distance Units
statement.)
LAYER_INFO_ZOOM_MAX
LAYER_INFO_COSMETIC
LAYER_INFO_PATH
LAYER_INFO_DISPLAY
SmallInt, indicating how and whether this layer is displayed; return value will be one of these values:
LAYER_INFO_DISPLAY_OFF (0)
Reference
373
LayerInfo( ) function
Attribute Code
ID
LAYER_INFO_OVR_LINE
10
LAYER_INFO_OVR_PEN
11
LAYER_INFO_OVR_BRUSH
12
LAYER_INFO_OVR_SYMBOL
13
LAYER_INFO_OVR_FONT
14
Font style used for displaying text objects. If the base set
of layer properties includes a stacked style, the font returned is the first pass of the stacked style.
LAYER_INFO_LBL_EXPR
15
LAYER_INFO_LBL_LT
16
374
MapBasic 12.0
ID
LAYER_INFO_LBL_CURFONT
17
LAYER_INFO_LBL_FONT
18
LAYER_INFO_LBL_PARALLEL
19
LAYER_INFO_LBL_POS
20
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_CC (0)
LAYER_INFO_LBL_POS_CR (5)
LAYER_INFO_LBL_POS_BL (6)
LAYER_INFO_LBL_POS_BC (7)
LAYER_INFO_LBL_POS_BR (8)
LAYER_INFO_ARROWS
21
LAYER_INFO_NODES
22
LAYER_INFO_CENTROIDS
23
LAYER_INFO_TYPE
24
Reference
375
LayerInfo( ) function
Attribute Code
ID
LAYER_INFO_LBL_VISIBILITY
25
LAYER_INFO_LBL_ZOOM_MIN
26
LAYER_INFO_LBL_ZOOM_MAX
27
LAYER_INFO_LBL_AUTODISPLAY
28
LAYER_INFO_LBL_OVERLAP
29
LAYER_INFO_LBL_DUPLICATES
30
LAYER_INFO_LBL_OFFSET
31
LAYER_INFO_LBL_MAX
32
LAYER_INFO_LBL_PARTIALSEGS
33
LAYER_INFO_HOTLINK_EXPR
34
LAYER_INFO_HOTLINK_MODE
35
376
MapBasic 12.0
ID
LAYER_INFO_HOTLINK_RELATIVE 36
LAYER_INFO_HOTLINK_COUNT
37
LAYER_INFO_LBL_ORIENTATION* 38
LAYER_INFO_LAYER_ALPHA
39
SmallInt value, representing the alpha factor for the specified layer.
0=fully transparent.
255=fully opaque.
To set the translucency or alpha for a layer, use the Set
Map statement.
LAYER_INFO_LAYER_TRANSLUCENCY
40
LAYER_INFO_LABEL_ALPHA
41
Reference
377
LayerInfo( ) function
378
Attribute Code
ID
LAYER_INFO_LAYERLIST_ID
42
LAYER_INFO_PARENT_GROUP_ID 43
Returns the group layer ID of the immediate group containing this layer, returns 0 if layer is in the top level list.
LAYER_INFO_OVR_STYLE_COUNT 44
LAYER_INFO_OVR_LBL_COUNT
45
LAYER_INFO_OVR_STYLE_CURRENT
46
LAYER_INFO_OVR_LBL_CURRENT 47
LAYER_INFO_OVR_LINE_COUNT
48
LAYER_INFO_OVR_PEN_COUNT
49
LAYER_INFO_OVR_BRUSH_COUNT 50
LAYER_INFO_OVR_SYMBOL_COUNT
51
LAYER_INFO_OVR_FONT_COUNT 52
LAYER_INFO_TILE_SERVER_LEVEL
53
LAYER_INFO_LBL_AUTO_POSITION
54
LAYER_INFO_LBL_AUTO_SIZES
55
MapBasic 12.0
ID
LAYER_INFO_LBL_SUPPRESS_IF_NO_FIT
56
LAYER_INFO_LBL_AUTO_SIZE_STEP
57
LAY58
ER_INFO_LBL_CURVED_BEST_POSITION
LAYER_INFO_LBL_CURVED_FALL- 59
BACK
LAYER_INFO_LBL_USE_ABBREVI- 60
ATION
LAYER_INFO_ABBREVIATION_EX- 61
PR
LAYER_INFO_LBL_AUTO_CALLOUT 62
LAYER_INFO_LBL_ORDER
63
Hotlinks
For backwards compatibility, the original set of attributes before version 10.0 still work, and will return
the values for the layer's first hotlink definition. If no hotlinks are defined when the function is called, then
the following values are returned:
LAYER_INFO_HOTLINK_EXPR - empty string ("")
LAYER_INFO_HOTLINK_MODE - returns default value HOTLINK_MODE_LABEL
LAYER_INFO_HOTLINK_RELATIVE - returns default value FALSE
Examples
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_number, LAYER_INFO_TYPE)
Reference
379
LayerListInfo( ) function
If i_lay_type = LAYER_INFO_TYPE_NORMAL Then
'
' ... then this is a "normal" layer
'
End If
The folowing example illustrates layer priority. If the label priority order is set as:
Set Map Window FrontWindow() LabelPriority 5, 1, 2, 4, 3
Then the following returns a value of 1, because the default draw order for labels is the same as the
draw order for map layers (which is bottom up).
LayerInfo(FrontWindow(), 5, LAYER_INFO_LBL_ORDER)
See Also:
GroupLayerInfo function, LayerListInfo( ) function, MapperInfo( ) function, Set Map statement
LayerListInfo( ) function
Purpose
This function helps to enumerate a map's list of layers and can refer to both group and graphical layers.
Syntax
LayerListInfo( map_window_id, numeric_counter, attribute )
map_window_id is a Map window identifier.
numeric_counter is value from zero (0) to MAPPER_INFO_ALL_LAYERS, which is the number of layers
in the Map window excluding the cosmetic layer. For details about MAPPER_INFO_ALL_LAYERS, see
MapperInfo( ) function.
attribute is a code indicating the type of information to return; see table below.
Return Value
Depends on the attribute parameter.
Description
This function can be used to iterate over all the components of the map's layer list where numeric_counter
goes from zero (0) to MAPPER_INFO_ALL_LAYERS.
The attributes are:
Value of window_id, attribute
ID
Description
LAYERLIST_INFO_TYPE
LAYERLIST_INFO_NAME
380
MapBasic 12.0
ID
Description
LAYERLIST_INFO_LAYER_ID
LAYERLIST_INFO_GROUPLAYER_ID
If the type returns a graphical layer, then use LayerInfo to get attributes. If it is a group layer then use
GroupLayerInfo to get attributes. To loop through this flattened view of the layer list, use MAPPER_INFO_ALL_LAYERS as the looping limit.
Specifying a map window ID of zero (0) returns information about the Cosmetic Layer.
See Also:
GroupLayerInfo function, LayerInfo( ) function, MapperInfo( ) function
LayerStyleInfo( ) function
Returns style information for a stacked style (a style composed of one or more style definitions).
Syntax
LayerStyleInfo (
window_id, layer_number, override_index, pass_index, attribute )
window_id is the integer window identifier of a Map window.
layer_number is the number of a layer in the current Map window (for example, 1 for the top layer); to
determine the number of layers in a Map window, call the MapperInfo( ) function.
override_index is an integer index (0-based, where 0 for the layer's base set of properties) and 1 or
higher is for a style override.
pass_index is an integer index (1-based) where the index corresponds to a pass within the stacked style.
The first pass is the part of the style drawn first, the second pass is the part of the style drawn next, and
so on.
attribute is a code indicating the type of information to return; see table below.
Return Value
Return value depends on attribute parameter.
Description
The LayerStyleInfo( ) function returns style information for a stacked style. A stacked style is made up
of one or more style definitions. For example, a line style drawn with two separate styles; a thin light red
line drawn on top of a thicker dark red line would be descried as follows using MapBasic syntax:
Line (7,2,12582912), Line (3,2,16736352)
The thicker dark red line in this example is drawn first.
Reference
381
Layout statement
The layer_number must be a valid 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.
Attribute Code
ID
STYLE_OVR _INFO_LINE
10
Pen style used for displaying the specified pass for linear
objects.
STYLE_OVR _INFO_PEN
11
Pen style used for displaying the specified pass for the
borders of filled objects.
STYLE_OVR_INFO_BRUSH
12
Brush style used for displaying the specified pass for filled
objects.
STYLE_OVR_INFO_SYMBOL
13
STYLE_OVR_INFO_FONT
14
Font style used for displaying the specified pass for text
objects.
Example
LayerStyleInfo(nMID, nLayer, nOverride, nPass, STYLE_OVR_INFO_PEN)
See Also:
StyleOverrideInfo( ) function, LabelOverrideInfo( ) function, Set Map statement, LayerInfo( )
function
Layout statement
Purpose
Opens a new layout window. You can issue this statement from the MapBasic window in MapInfo Professional.
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 (for example, "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. For details about paper units, see Set Paper Units
statement.
window_width and window_height dictate the size of the window, in Paper units.
382
MapBasic 12.0
LCase$( ) function
Purpose
Returns a lower-case equivalent of a string. You can call this function from the MapBasic window in
MapInfo Professional.
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.
Reference
383
Left$( ) function
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$( ) function, UCase$( ) function
Left$( ) function
Purpose
Returns part or all of a string, beginning at the left end of the string. You can call this function from the
MapBasic window in MapInfo Professional.
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)
' at this point, partial contains the string: "Afghan"
384
MapBasic 12.0
LegendFrameInfo( ) function
Purpose
Returns information about a frame within a legend. You can call this function from the MapBasic window
in MapInfo Professional.
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
ID
FRAME_INFO_TYPE
FRAME_INFO_MAP_LAYER_ID
FRAME_INFO_REFRESHABLE
FRAME_INFO_POS_X
FRAME_INFO_POS_Y
FRAME_INFO_WIDTH
Returns the width of the frame (in paper units). For details
about paper units, see Set Paper Units statement.
FRAME_INFO_HEIGHT
FRAME_INFO_TITLE
FRAME_INFO_TITLE_FONT
Reference
385
LegendInfo( ) function
Attribute codes
ID
FRAME_INFO_SUBTITLE
10
FRAME_INFO_SUBTITLE_FONT
11
FRAME_INFO_BORDER_PEN
12
FRAME_INFO_NUM_STYLES
13
FRAME_INFO_VISIBLE
14
FRAME_INFO_COLUMN
15
FRAME_INFO_LABEL
16
FRAME_INFO_COLUMNS
17
FRAME_INFO_NUM_VISIBLE_ROWS
18
FRAME_INFO_LINE_SAMPLE_WIDTH 19
Returns line sample width in MapBasic paper units. Returns -1 for Cartographic Legend window.
FRAME_INFO_REGION_SAMPLE_WIDTH
20
FRAME_INFO_REGION_SAMPLE_HEIGHT
21
See Also:
LegendInfo( ) function, LegendTextFrameInfo( ) function, LegendStyleInfo( ) function
LegendInfo( ) function
Purpose
Returns information about a legend. You can call this function from the MapBasic window in MapInfo
Professional.
386
MapBasic 12.0
ID
LEGEND_INFO_MAP_ID
LEGEND_INFO_ORIENTATION
LEGEND_INFO_NUM_FRAMES
LE4
GEND_INFO_STYLE_SAMPLE_SIZE
LE5
GEND_INFO_LINE_SAMPLE_WIDTH
Returns line sample width in MapBasic paper units. Returns -1 for Cartographic Legend window. For details about
paper units, see Set Paper Units statement.
LEGEND_INFO_REGION_SAMPLE_WIDTH
LEGEND_INFO_REGION_SAMPLE_HEIGHT
LEGEND_INFO_NUM_TEXTFRAMES 8
Example
dim wndLegend, wndMap as integer
for i = 1 to NumWindows()
If WindowInfo(WindowID(i), WIN_INFO_TYPE) = WIN_MAPPER then
wndMap = WindowInfo(WindowID(i), WIN_INFO_WINDOWID)
end if
if WindowInfo(WindowID(i), WIN_INFO_TYPE) = WIN_LEGEND_DESIGNER then
wndLegend = WindowInfo(WindowID(i), WIN_INFO_WINDOWID)
end if
next
Reference
387
LegendStyleInfo( ) function
This example illustrates how to see which map window ID was used for creating the Legend Designer
Window.
If LegendInfo(wndLegend, LEGEND_INFO_MAP_ID) = wndMap then
Print "Map ID: " + str$(MapID) + " was correct"
End if
See Also:
LegendFrameInfo( ) function, LegendTextFrameInfo( ) function, LegendStyleInfo( ) function
LegendStyleInfo( ) function
Purpose
Returns information about a style item within a legend frame. You can call this function from the MapBasic
window in MapInfo Professional.
Syntax
LegendStyleInfo( 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
Attribute Code
ID
LEGEND_STYLE_INFO_TEXT
LEGEND_STYLE_INFO_FONT
LEGEND_STYLE_INFO_OBJ
LEGEND_STYLE_INFO_ROW_VIS- 4
IBLE
388
MapBasic 12.0
objStyle as object
tBrush as Brush
tPen as Pen
tSymbol as Symbol
tFont as Font
strSampleText as string
Use the StyleAttr() function to return specific properties of the Font Style, such as:
StyleAttr(tFont, FONT_NAME)
and print text of the first thematic range value (such as 5,700,000 to 23,700,000).
Print strSampleText
See Also:
StyleAttr() function
Reference
389
LegendTextFrameInfo( ) function
LegendTextFrameInfo( ) function
Purpose
Returns information about a text frame within a a Legend Designer window. You can call this function
from the MapBasic window in MapInfo Professional.
Syntax
LegendTextFrameInfo( 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
ID
FRAME_INFO_POS_X
FRAME_INFO_POS_Y
FRAME_INFO_WIDTH
Returns the width of the frame (in paper units). For details
about paper units, see Set Paper Units statement.
FRAME_INFO_HEIGHT
Returns the height of the frame (in paper units). For details
about paper units, see Set Paper Units statement.
FRAME_INFO_TEXT
FRAME_INFO_TEXT_FONT
See Also:
LegendInfo( ) function, LegendFrameInfo( ) function, LegendStyleInfo( ) function
Len( ) function
Purpose
Returns the number of characters in a string or the number of bytes in a variable. You can call this
function from the MapBasic window in MapInfo Professional.
390
MapBasic 12.0
LibraryServiceInfo( ) function
Purpose
Returns information about the Library Services, such as the current mode of operation, version, or default
URL for the Library Service. It also gives the list of CSW URL's exposed by the MapInfo Manager server.
Syntax
LibraryServiceInfo( attribute )
attribute is a code indicating the type of information to return; see table below.
Description
The LibraryServiceInfo( ) function returns one piece of information about the Library Services.
The attribute parameter is a value from the table below. Codes in the left column are defined in MAPBASIC.DEF.
Reference
391
Like( ) function
attribute code
ID
LibraryServiceInfo( ) returns
LIBSRVC_INFO_LIBSRVCMODE
LIBSRVC_INFO_LIBVERSION
LIBSRVC_INFO_DEFURLPATH
LIBSRVC_INFO_LISTCSWURL
Example
The following example shows how to use this function:
include "mapbasic.def"
declare sub main
sub main
dim liburlpath as string
dim libversion as string
liburlpath = LibraryServiceInfo(LIBSRVC_INFO_DEFURLPATH)if
StringCompare(liburlpath, "") == 0 then
Set LibraryServiceInfo URL
"http://localhost:8080/LibraryService/LibraryService"
endif
libversion = LibraryServiceInfo(LIBSRVC_INFO_LIBVERSION)
end sub
See Also:
Set LibraryServiceInfo statement
Like( ) function
Purpose
Returns TRUE or FALSE to indicate whether a string satisfies pattern-matching criteria. You can call
this function from the MapBasic window in MapInfo Professional.
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 (for example,
"\") 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 ("").
392
MapBasic 12.0
% (percent)
To search for instances of the underscore or percent characters, specify an escape_char parameter, as
shown in the table below.
To determine if a string...
See Also:
Len( ) function, StringCompare( ) function
Reference
393
LocateFile$( ) function
The Line Input statement treats each line of the file as one long string. If each line of a file contains a
comma-separated list of expressions, and you want to read each expression into a separate variable,
use the Input # statement instead of Line Input.
Example
The following program opens an existing text file, reads the contents of the text file one line at a time,
and copies the contents of the file to a separate text file.
Dim str As String
Open File "original.txt" For Input As #1
Open File "copy.txt" For Output As #2
Do While Not EOF(1)
Line Input #1, str
If Not EOF(1) Then
Print #2, str
End If
Loop
Close File #1
Close File #2
See Also:
Input # statement, Open File statement, Print # statement
LocateFile$( ) function
Purpose
Return the path to one of the MapInfo application data files. You can call this function from the MapBasic
window in MapInfo Professional.
Syntax
LocateFile$( file_id )
file_id is one of the following values
394
Value
ID
Description
LOCATE_PREF_FILE
LOCATE_DEF_WOR
LOCATE_CLR_FILE
LOCATE_PEN_FILE
LOCATE_FNT_FILE
LOCATE_ABB_FILE
LOCATE_PRJ_FILE
LOCATE_MNU_FILE
LOCATE_CUSTSYMB_DIR
MapBasic 12.0
ID
Description
LOCATE_THMTMPLT_DIR
LOCATE_GRAPH_DIR
10
LOCATE_WMS_SERVERLIST
11
LOCATE_WFS_SERVERLIST
12
LOCATE_GEOCODE_SERVERLIST 13
LOCATE_ROUTING_SERVERLIST
14
LOCATE_LAYOUT_TEMPLATE_DIR 15
Return Value
String
Description
Given the ID of a MapInfo Professional application data file, this function returns the location where
MapInfo Professional found that file. MapInfo Professional 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$( ) function
LOF( ) function
Purpose
Returns the length of an open file.
Syntax
LOF( filenum )
filenum is the number of an open file.
Reference
395
Log( ) function
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 (366) 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 statement
Log( ) function
Purpose
Returns the natural logarithm of a number. You can call this function from the MapBasic window in
MapInfo Professional.
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.
396
MapBasic 12.0
LTrim$( ) function
Purpose
Trims space characters from the beginning of a string and returns the results. You can call this function
from the MapBasic window in MapInfo Professional.
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)
' name now contains the string "Mary Smith"
See Also:
RTrim$( ) function
Reference
397
Main procedure
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
(for example, 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
398
MapBasic 12.0
MakeBrush( ) function
Purpose
Returns a Brush value. You can call this function from the MapBasic window in MapInfo Professional.
Syntax
MakeBrush( pattern, forecolor, backcolor)
pattern is an integer value from 1 to 8 or from 12 to 186, 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 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 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:
Reference
399
MakeCustomSymbol( ) function
Brush clause, CurrentBrush( ) function, RGB( ) function, StyleAttr( ) function
MakeCustomSymbol( ) function
Purpose
Returns a Symbol value based on a bitmap file. You can call this function from the MapBasic window
in MapInfo Professional.
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 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 Symbol clause
for information about other symbol types.
The following table describes how the customstyle argument controls the symbol's style:
400
customstyle value
Symbol Style
The Show Background, the Apply Color, and the Display at Actual Size settings are off; the symbol appears in its default state at the point size specified
by the size parameter. White pixels in the bitmap are displayed as transparent,
allowing whatever is behind the symbol to show through.
The Show Background setting is on; white pixels in the bitmap are opaque.
The Apply Color setting is on; non-white pixels in the bitmap are replaced
with the symbol's color setting.
The Display at Actual Size setting is on; the bitmap image is rendered at its
native width and height in pixels.
The Show Background and Display at Actual Size settings are on.
The Show Background, the Apply Color, and the Display at Actual Size settings are on.
MapBasic 12.0
MakeDateTime( ) function
Purpose
Returns a DateTime made from the specified Date and Time. You can call this function from the MapBasic
window in MapInfo Professional.
Syntax
MakeDateTime( Date, Time )
Return Value
DateTime, which is an integer value DateTime in nine bytes: 4 bytes for date, 5 bytes for time. Five bytes
for time include: 2 for millisec, 1 for sec, 1 for min, 1 for hour.
Example
Copy this example into the MapBasic window for a demonstration of this function.
dim tX as time
dim dX as date
dim dtX as datetime
tX = 105604123
dX = 20070908
dtX = MakeDateTime(dX,tX)
Print FormatDate$(GetDate(dtX))
Print FormatTime$(GetTime(dtX), "hh:mm:ss.fff tt")
See Also:
DateWindow( ) function, Set Date Window( ) statement
MakeFont( ) function
Purpose
Returns a Font value. You can call this function from the MapBasic window in MapInfo Professional.
Syntax
MakeFont( fontname, style, size, forecolor, backcolor )
fontname is a text string specifying a font (for example, "Arial"). This argument is case sensitive.
style is a positive integer expression; 0 = plain text, 1 = bold text, etc. See Font clause for details.
Reference
401
MakeFontSymbol( ) function
size is an integer point size, one or greater.
forecolor is the RGB color value for the text. See 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 statement or Set Style statement).
See Font clause for more information about Font settings.
Example
Include "mapbasic.def"
Dim big_title As Font
big_title = MakeFont("Arial", 1, 20,BLACK,WHITE)
See Also:
CurrentFont( ) function, Font clause, StyleAttr( ) function
MakeFontSymbol( ) function
Purpose
Returns a Symbol value, using a character from a TrueType font as the symbol. You can call this function
from the MapBasic window in MapInfo Professional.
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 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 (for example, "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
402
MapBasic 12.0
Symbol Style
Plain
Bold
16
32
Drop Shadow
256
To specify two or more style attributes, add the values from the left column. For example, to specify both
the Bold and the Drop Shadow attributes, use a fontstyle value of 33. Border and Halo are mutually exclusive.
Example
Include "mapbasic.def"
Dim sym_marker As Symbol
sym_marker = MakeFontSymbol(65,RED,24,"WingDings",32,0)
See Also:
CurrentSymbol( ) function, MakeCustomSymbol( ) function, MakeSymbol( ) function, StyleAttr(
) function, Symbol clause
MakePen( ) function
Purpose
Returns a Pen value. You can call this function from the MapBasic window in MapInfo Professional.
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 RGB( ) function for details.
Return Value
Pen
Reference
403
MakeSymbol( ) function
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 statement, Create Pline statement, Set Style statement, or Set Map
statement).
See 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( ) function, Pen clause, StyleAttr( ) function, RGB( ) function
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. You can call this function from the MapBasic window
in 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 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 clause as a parameter
(such as Create Point statement, Set Map statement, Set Style statement, or Shade statement).
To create a symbol from a character in a TrueType font, call the MakeFontSymbol( ) function.
To create a symbol from a bitmap file, call the MakeCustomSymbol( ) function.
See Symbol clause for more information about Symbol settings.
404
MapBasic 12.0
Map statement
Purpose
Opens a new Map window. You can issue this statement from the MapBasic window in MapInfo Professional.
Syntax
Map From item [ , item ... ]
[ Position ( x, y ) [ Units paperunits ] ]
[ Width window_width [ Units paperunits ] ]
[ Height window_height [ Units paperunits ] ]
[ { Min | Max } ]
where item = table | [GroupLayer ("friendly_name" [ , item ...])
item is either the name of an open table, or a group layer
friendly_name for each group layer is required but does not have to be unique, group layers may contain
other group layers and/or tables, or be empty (no tables).
paperunits is the name of a paper unit (for example, "in").
x, y specifies the position of the upper left corner of the Map window, in paper units. For details about
paper units, see Set Paper Units statement.
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 statement.
A GroupLayer keyword has been added to create nested group layers. Group layers are a special type
of layer that allow users to organize other map layers into groups, similar to the way that folders and
subfolders allow users to organize files. Group layers will make it easier to manage maps that have many
layers. There are two main benefits to using groups:
1. Organizational benefits - layer lists are more manageable if they are organized into meaningful
groups.
2. Efficiency benefits - once layers are organized into groups, subsequent operations such as "turn off
all the street layers" can be performed in fewer clicks / fewer steps.
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 ac-
Reference
405
Map statement
tually 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, regardless of whether it is part of a group layer or
not, 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 Professional application, not relative to the upper left corner
of the screen.
If the Map statement includes the optional Max keyword, the new Map window is maximized, taking up
all of the screen space available to MapInfo Professional. Conversely, if the Map statement includes the
Min keyword, the window is minimized immediately.
Each Map window can have its own projection. MapInfo Professional 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.
Examples
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 Professional 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
The following example opens a Map window that has group layers, some of which are nested (assume
all tables have been opened first).
Map From
GroupLayer (
"Grid",
GroupLayer ("Tropics", Tropic_Of_Capricorn, Tropic_Of_Cancer),
Wgrid15
),
GroupLayer (
"World Places", WorldPlaces, WorldPlacesMajor, WorldPlaces_Capitals
),
Airports,
GroupLayer ("World Boundaries", world_Border),
GroupLayer (
"Roads", Roads, US_Primary_Roads, US_Secondary_Roads, US_Major_Roads
),
GroupLayer ("Countries" Countries_small, Countries_large),
Ocean
406
MapBasic 12.0
Layer ID
GroupLayer "Grid"
group 1
GroupLayer "Tropics"
group 2
Tropic_Of_Capricorn
layer 1
Tropic_Of_Cancer
layer 2
Wgrid15
layer 3
group 3
WorldPlaces
layer 4
WorldPlacesMajor
layer 5
WorldPlaces_Capitals
layer 6
Airports
layer 7
group 4
world_Border
layer 8
GroupLayer "Roads"
group 5
Roads
layer 19
US_Primary_Roads
layer 10
US_Secondary_Roads
layer 11
US_Major_Roads
layer 12
GroupLayer "Countries"
group 6
Countries_small
layer 13
Countries_large
layer 14
Ocean
layer 15
See Also:
Add Map statement, Remove Map statement, Set Map statement, Set Shade statement, Shade
statement
Reference
407
Map3DInfo( ) function
Map3DInfo( ) function
Purpose
Returns properties of a 3DMap window. You can call this function from the MapBasic window in MapInfo
Professional.
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.
Return Value
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.
408
Attribute
ID
Return Value
MAP3D_INFO_SCALE
MAP3D_INFO_RESOLUTION_X
MAP3D_INFO_RESOLUTION_Y
MAP3D_INFO_BACKGROUND
MAP3D_INFO_UNITS
MAP3D_INFO_LIGHT_X
MAP3D_INFO_LIGHT_Y
MapBasic 12.0
ID
Return Value
MAP3D_INFO_LIGHT_Z
MAP3D_INFO_LIGHT_COLOR
MAP3D_INFO_CAMERA_X
10
MAP3D_INFO_CAMERA_Y
11
MAP3D_INFO_CAMERA_Z
12
MAP3D_INFO_CAMERA_FOCAL_X 13
MAP3D_INFO_CAMERA_FOCAL_Y 14
MAP3D_INFO_CAMERA_FOCAL_Z 15
MAP3D_INFO_CAMERA_VU_1
16
MAP3D_INFO_CAMERA_VU_2
17
MAP3D_INFO_CAMERA_VU_3
18
MAP3D_INFO_CAMERA_VPN_1
19
MAP3D_INFO_CAMERA_VPN_2
20
Float result representing the second value of the ViewPlane Unit Normal Vector.
MAP3D_INFO_CAMERA_VPN_3
21
MAP3D_INFO_CAMERA_CLIP_NEAR
22
MAP3D_INFO_CAMERA_CLIP_FAR 23
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( ),
Reference
409
MapperInfo( ) function
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. You can call this function from the
MapBasic window in MapInfo Professional.
Syntax
MapperInfo( window_id, attribute )
window_id is an integer window identifier.
410
MapBasic 12.0
ID
MAPPER_INFO_ZOOM
MAPPER_INFO_SCALE
MAPPER_INFO_CENTERX
MAPPER_INFO_CENTERY
MAPPER_INFO_MINX
MAPPER_INFO_MINY
MAPPER_INFO_MAXX
MAPPER_INFO_MAXY
MAPPER_INFO_LAYERS
MAPPER_INFO_EDIT_LAYER
10
MAPPER_INFO_XYUNITS
11
MAPPER_INFO_DISTUNITS
12
Reference
411
MapperInfo( ) function
attribute setting
ID
MAPPER_INFO_AREAUNITS
13
MAPPER_INFO_SCROLLBARS
14
MAPPER_INFO_DISPLAY
15
Small integer, indicating what aspect of the map is displayed on the status bar. Corresponds to Set Map Display. Return value will be one of these:
MAPPER_INFO_DISPLAY_SCALE (0)
MAPPER_INFO_DISPLAY_ZOOM (1)
MAPPER_INFO_DISPLAY_POSITION (2)
MAPPER_INFO_DISPLAY_CARTOGRAPHIC_SCALE
(3)
MAPPER_INFO_NUM_THEMATIC
16
MAPPER_INFO_COORDSYS_CLAUSE
17
MAPPER_INFO_COORDSYS_NAME 18
String result, representing the name of the map's CoordSys as listed in MAPINFOW.PRJ (but without the optional
"\p..." suffix that appears in MAPINFOW.PRJ). Returns
empty string if CoordSys is not found in MAPINFOW.PRJ.
MAPPER_INFO_MOVE_DUPLICATE_NODES
19
MAPPER_INFO_DIST_CALC_TYPE 20
Small integer, indicating type of calculation to use for distance, length, perimeter, and area calculations for mapper.
Corresponds to Set Map Distance Type. Return values
include:
MAPPER_INFO_DIST_SPHERICAL (0)
MAPPER_INFO_DIST CARTESIAN (1)
MAPPER_INFO_DISPLAY_DMS
21
Small integer, indicating whether the map displays coordinates in decimal degrees, DMS (degrees, minutes,
seconds), or Military Grid Reference System or USNG
(US National Grid) format. Return value is one of the following:
MAPPER_INFO_DISPLAY_DECIMAL (0)
412
MapBasic 12.0
ID
MAPPER_INFO_COORDSYS_CLAUSE_WITH_BOUNDS
22
MAPPER_INFO_CLIP_TYPE
23
MAPPER_INFO_CLIP_REGION
24
MAPPER_INFO_REPROJECTION
25
MAPPER_INFO_RESAMPLING
26
MAPPER_INFO_MERGE_MAP
27
MAPPER_INFO_ALL_LAYERS
28
This will return the count of layers and group layers (includes all nested layers and group layers)
MAPPER_INFO_GROUPLAYERS
29
Reference
413
MapperInfo( ) function
attribute setting
ID
MAPPER_INFO_LABELS_SELECT- 30
ABLE
MAPPER_INFO_NUM_ADORNMENTS
200 This will return an integer representing the number of adornments associated with a mapper. Use some value
suitably outside the normal range for MapperInfo, such
as 100.
MAPPER_INFO_ADORNMENT+n
200 This will return the WindowID of a given adornment associated with the Mapper.
When you call MapperInfo( ) to obtain coordinate values (for example, by specifying MAPPER_INFO_CENTERX as the attribute), the value returned represents a coordinate in MapBasic's current
coordinate system, which may be different from the coordinate system of the Map window. Use the Set
CoordSys statement to specify a different coordinate system.
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 its 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 statement.
Coordinate Value Returns
MapperInfo( ) does not return coordinates (for example 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 MapInfo Professional 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).
Clip Region Information
Beginning with MapInfo Professional 6.0, there are three methods that are used for Clip Region functionality. The MAPPER_INFO_CLIP_OVERLAY (2) method is the method that has been the only option
until MapInfo Professional 6.0. Using this method, the Overlap( ) function (Object > Erase Outside)
is used internally. Since the Overlap( ) function cannot produce result with Text objects, text objects
are never clipped. For Point objects, a simple point in region test is performed to either include or exclude
the Point. Label objects are treated similar to Point objects and are either completely displayed (is the
label point is inside the clip region object) or ignored. Since the clipping is done at the spatial object level,
styles (wide lines, symbols, text) are never clipped.
414
MapBasic 12.0
Maximum( ) function
Purpose
Returns the larger of two numbers. You can call this function from the MapBasic window in MapInfo
Professional.
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 =
x, y, z As Float
42
27
Maximum(x, y)
Reference
415
MBR( ) function
Minimum( ) function
MBR( ) function
Purpose
Returns a rectangle object, representing the minimum bounding rectangle (MBR) of another object. You
can call this function from the MapBasic window in MapInfo Professional.
Syntax
MBR( obj_expr )
obj_expr is an object expression.
Return Value
Object (a rectangle)
Description
The MBR( ) function calculates the minimum bounding rectangle (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( ) function, CentroidX( ) function, CentroidY( ) function
416
MapBasic 12.0
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, MapInfo Professional 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 (for example, using the optional ID clause in the Create
Menu statement), and call MenuItemInfoByID( ) function instead of calling MenuitemInfoByHandler(
).
The attribute parameter is a numeric code (defined in MAPBASIC.DEF) from the following table:
attribute setting
ID
Return value
MENUITEM_INFO_ENABLED
MENUITEM_INFO_CHECKED
Reference
417
MenuItemInfoByID( ) function
attribute setting
ID
Return value
MENUITEM_INFO_CHECKABLE
MENUITEM_INFO_SHOWHIDEABLE 4
MENUITEM_INFO_ACCELERATOR 5
MENUITEM_INFO_TEXT
MENUITEM_INFO_HELPMSG
MENUITEM_INFO_HANDLER
MENUITEM_INFO_ID
See Also:
MenuItemInfoByID( ) function
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).
418
MapBasic 12.0
Metadata statement
Purpose
Manages a table's metadata. You can issue this statement from the MapBasic window in MapInfo Professional.
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; MapInfo Professional 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 In 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; MapInfo Professional stores the fetched key's name in
this variable.
Reference
419
Metadata statement
key_value_var is the name of a string variable; MapInfo Professional stores the fetched key's value in
this variable.
Description
The Metadata statement manages the metadata stored in MapInfo tables. 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 Pitney Bowes Software Inc. Corporation." For more
information about Metadata, see the MapBasic User Guide.
Modifying a Table's Metadata
To create, modify, or delete metadata, use Syntax 1. The following clauses apply:
SetKey
Assigns a value to a metadata key. If the key already exists, MapInfo Professional assigns it a new value.
If the key does not exist, MapInfo Professional creates a new key. When you create a new key, the
changes take effect immediately; you do not need to perform a Save operation.
MetaData Table Parcels SetKey "\Info\Date" To Str$(CurDate( ))
Note: MapInfo Professional 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 MapInfo Professional.
DropKey
Deletes the specified key from the table. If you include the Hierarchical keyword, MapInfo Professional
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
Reading a Table's Metadata
To read a table's metadata values, use the SetTraverse clause to initialize a traversal, and then use the
Next clause to fetch key values. After you are finished fetching key values, use the Destroy clause to
free the memory used by the traversal. The following clauses apply:
SetTraverse
Prepares to traverse the table's keys, starting with the specified key. To start at the beginning of the list
of keys, specify "\" as the starting key name. If you include the Hierarchical keyword, the traversal can
hierarchically fetch every key. If you omit the Hierarchical keyword, the traversal is flat, meaning that
MapInfo Professional will only fetch keys at the root level (for example, the traversal will fetch the "\Info"
key, but not the "\Info\Date" key).
Next Into Key... Into Value...
Attempts to read the next key. If there is a key to read, MapInfo Professional stores the key's name in
the key_name_var variable, and stores the key's value in the key_value_var variable. If there are no
more keys to read, MapInfo Professional stores empty strings in both variables.
420
MapBasic 12.0
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
' Initialize the traversal:
Metadata Table table_name
SetTraverse "\" Hierarchical Into ID i_traversal
' Attempt to fetch the first key:
Metadata Traverse i_traversal
Next Into Key s_keyname Into Value s_keyvalue
' Now loop for as long as there are key values;
' with each iteration of the loop, retrieve
' one key, and print it to the Message window.
Do While s_keyname <> ""
Print " "
Print "Key name: " & s_keyname
Print "Key value: " & s_keyvalue
Metadata Traverse i_traversal
Next Into Key s_keyname Into Value s_keyvalue
Loop
' Release this traversal to free memory:
MetaData Traverse i_traversal Destroy
End Sub
See Also:
GetMetadata$( ) function, TableInfo( ) function
MGRSToPoint( ) function
Purpose
Converts a string representing an MGRS (Military Grid Reference System) coordinate into a point object
in the current MapBasic coordinate system. You can call this function from the MapBasic window in
MapInfo Professional.
Reference
421
MGRSToPoint( ) function
Syntax
MGRSToPoint( string )
string is a string expression representing an MGRS coordinate.
The default Longitude/Latitude coordinate system is used as the initial selection.
Return Value
Object
Description
The returned point will be in the current MapBasic coordinate system, which by default is Long/Lat (no
datum). For the most accurate results when saving the resulting points to a table, set the MapBasic coordinate system to match the destination table's coordinate system before calling MGRSToPoint( ). This
will prevent MapInfo Professional from doing an intermediate conversion to the datumless Long/Lat coordinate system, which can cause a significant loss of precision.
Example
Example 1:
dim obj1 as Object
dim s_mgrs As String
dim obj2 as Object
obj1 = CreatePoint(-74.669, 43.263)
s_mgrs = PointToMGRS$(obj1)
obj2 = MGRSToPoint(s_mgrs)
Example 2:
Open Table "C:\Temp\MyTable.TAB" as MGRSfile
' When using the PointToMGRS$( ) or MGRSToPoint( ) functions,
' it is very important to make sure that the current MapBasic
' coordsys matches the coordsys of the table where the
' point object is being stored.
'Set the MapBasic coordsys to that of the table used
Set CoordSys Table MGRSfile
'Update a Character column (for example COL2) with MGRS strings from
'a table of points
Update MGRSfile
Set Col2 = PointToMGRS$(obj)
'Update two float columns (Col3 & Col4) with
'CentroidX & CentroidY information
'from a character column (Col2) that contains MGRS strings.
Update MGRSfile
Set Col3 = CentroidX(MGRSToPoint(Col2))
Update mgrstestfile ' MGRSfile
Set Col4 = CentroidY(MGRSToPoint(Col2))
Commit Table MGRSfile
Close Table MGRSfile
See Also:
PointToMGRS$( ) function
422
MapBasic 12.0
Mid$( ) function
Purpose
Returns a string extracted from the middle of another string. You can call this function from the MapBasic
window in MapInfo Professional.
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)
' substr_var now contains the string "City"
See Also:
InStr( ) function, Left$( ) function, Right$( ) function
MidByte$( ) function
Purpose
Accesses individual bytes of a string on a system with a double-byte character system. You can call this
function from the MapBasic window in MapInfo Professional.
Reference
423
Minimum( ) function
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( ) function, Left$( ) function, Right$( ) function
Minimum( ) function
Purpose
Returns the smaller of two numbers. You can call this function from the MapBasic window in MapInfo
Professional.
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 =
424
x, y, z As Float
42
-100
Minimum(x, y)
MapBasic 12.0
Minute( ) function
Purpose
Retrieves the minute part of a Time value as an integer (0-59). You can call this function from the MapBasic window in MapInfo Professional.
Syntax
Minute( Time )
Return Value
SmallInt
Example
Copy this example into the MapBasic window for a demonstration of this function.
dim X as time
dim iMin as integer
X = CurDateTime()
iMin = Minute(X)
Print iMin
See Also:
Hour( ) function, Second( ) function
Month( ) function
Purpose
Returns the month component (1 - 12) of a date value. You can call this function from the MapBasic
window in MapInfo Professional.
Syntax
Month( date_expr )
date_expr is a date expression.
Return Value
SmallInt value from 1 to 12, inclusive.
Reference
425
Nearest statement
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 MapInfo Professional 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( ) function, Day( ) function, Minute( ) function, Month( ) function, Second( ) function,
Weekday( ) function, Year( ) function
Nearest statement
Purpose
Find the object in a table that is closest to a particular object. The result is a 2-point Polyline object representing the closest distance. You can issue this statement from the MapBasic window in MapInfo
Professional.
Syntax
Nearest [ N | All ]
From { Table fromtable | Variable fromvar }
To totable Into intotable
[ Type { Spherical | Cartesian }]
[ Ignore [ Contains ] [ Min min_value ] [ Max max_value ]
Units unitname ] [ Data clause ]
N is an optional parameter representing the number of "nearest" objects to find. The default is 1. If All
is used, then a distance object is created for every combination.
fromtable represents a table of objects that you want to find closest distances from.
fromvar represents a MapBasic variable representing an object that you want to find the closest distances
from.
totable represents a table of objects that you want to find closest distances to.
426
MapBasic 12.0
Reference
427
Nearest statement
airports within 100 miles of a city. Supplying a Max parameter can improve the performance of the
Nearest statement, since it effectively limits the number of totable objects that are searched.
The effective distances found are strictly greater than the min_value and less than or equal to the
max_value:
min_value < distance <= max_value
This can allow ranges or distances to be returned in multiple passes using the Nearest statement. For
example, the first pass may return all objects between 0 and 100 miles, and the second pass may return
all objects between 100 and 200 miles, and the results should not contain duplicates (for example, a
distance of 100 should only occur in the first pass and never in the second pass).
Normally, if one object is contained within another object, the distance between the objects is zero. For
example, if the fromtable is WorldCaps and the totable is World, then the distance between London and
the United Kingdom would be zero. If the Contains flag is set within the Ignore clause, then the distance
will not be automatically be zero. Instead, the distance from London to the boundary of the United
Kingdom will be returned. In effect, this will treat all closed objects, such as regions, as polylines for the
purpose of this operation.
Data Clause
The Data clause can be used to mark which fromtable object and which totable object the result came
from.
Data IntoColumn1=column1, IntoColumn2=column2
The IntoColumn on the left hand side of the equals must be a valid column in intotable. The column
name on the right hand side of the equals sign must be a valid column name from either totable or
fromtable. If the same column name exists in both totable and fromtable, then the column in totable will
be used (e.g., totable is searched first for column names on the right hand side of the equals sign). To
avoid any conflicts such as this, the column names can be qualified using the table alias:
Data name1=states.state_name, name2=county.state_name
To fill a column in the intotable with the distance, we can either use the Table > Update Column functionality from the menu or use the Update statement.
Examples
Assume that we have a point table representing locations of ATM machines and that there are at least
two columns in this table: Business, which represents the name of the business which contains the ATM;
and Address, which represents the street address of that business. Assume that the current selection
represents our current location. Then the following will find the closest ATM to where we currently are:
Nearest From Table selection To atm Into result Data
where=Business,address=Address
If we wanted to find the closest five ATM machines to our current location:
Nearest 5 From Table selection To atm Into result Data
where=Business,address=Address
If we want to find all ATM machines within a 5 mile radius:
Nearest All From Table selection To atm Into result Ignore Max 5 Units
"mi" Data where=buisness,address=address
428
MapBasic 12.0
Note statement
Purpose
Displays a simple message in a dialog box. You can issue this statement from the MapBasic window
in MapInfo Professional.
Syntax
Note message
message is an expression to be displayed in a dialog box.
Description
The Note statement creates a dialog box to display a message. The dialog box contains an OK button;
the message dialog box 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 (for example, "Region") for display in the Note
dialog box. 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( ) function, Dialog statement, Print statement
Reference
429
NumAllWindows( ) function
NumAllWindows( ) function
Purpose
Returns the number of windows owned by MapInfo Professional, including special windows such as
ButtonPads and the Info window. You can call this function from the MapBasic window in MapInfo Professional.
Syntax
NumAllWindows( )
Return Value
SmallInt
Description
The NumAllWindows( ) function returns the number of windows owned by MapInfo Professional.
To determine the number of document windows opened by MapInfo Professional (Map, Browse, Graph,
and Layout windows), call NumWindows( ).
See Also:
NumWindows( ) function, WindowID( ) function
NumberToDate( ) function
Purpose
Returns a Date value, given an integer. You can call this function from the MapBasic window in MapInfo
Professional.
Syntax
NumberToDate( numeric_date )
numeric_date is an eight-digit integer in the form YYYYMMDD (for example, 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, 2006:
NumberToDate(20061231)
430
MapBasic 12.0
NumberToDateTime( ) function
Purpose
Returns a DateTime value. You can call this function from the MapBasic window in MapInfo Professional.
Syntax
NumberToDateTime( numeric_datetime )
numeric_datetime is an seventeen-digit integer in the form YYYYMMDDHHMMSSFFF. For example,
20070301214237582 represents March 1, 2007 9:42:37.582 PM.
Return Value
DateTime
Example
Copy this example into the MapBasic window for a demonstration of this function.
dim fNum as float
dim Y as datetime
fNum = 20070301214237582
Y = NumbertoDateTime (fNum)
Print FormatDate$(GetDate(Y))
Print FormatTime$(GetDate(Y),"hh:mm:ss.fff tt")
See also:
FormatTime$( ) function, GetTime() function, NumberToDate( ) function, NumberToTime( ) function
NumberToTime( ) function
Purpose
Returns a Time value. You can call this function from the MapBasic window in MapInfo Professional.
Reference
431
NumCols( ) function
Syntax
NumberToTime( numeric_time )
numeric_time is an nine-digit integer in the form HHMMSSFFF. For example, 214237582 represents
9:42:37.582 P.M.
Return Value
Time
Example
Copy this example into the MapBasic window for a demonstration of this function.
dim fNum as integer
dim Y as time
fNum = 214237582
Y = NumberToTime(fNum)
Print FormatTime$(Y,"hh:mm:ss.fff tt")
See also:
FormatTime$( ) function, GetTime() function, NumberToDate( ) function, NumberToDateTime( )
function
NumCols( ) function
Purpose
Returns the number of columns in a specified table. You can call this function from the MapBasic window
in MapInfo Professional.
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 (for example, because of an Add Column statement), the
number returned by NumCols( ) includes the temporary column(s).
432
MapBasic 12.0
NumTables( ) function
Purpose
Returns the number of tables currently open. You can call this function from the MapBasic window in
MapInfo Professional.
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, MapInfo Professional treats the DCWASHS table as a
single table; for example, the Layer Control window 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 statement, TableInfo( ) function, ColumnInfo( ) function
Reference
433
NumWindows( ) function
NumWindows( ) function
Purpose
Returns the number of open document windows (Map, Browse, Graph, Layout). You can call this function
from the MapBasic window in MapInfo Professional.
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( ) function, WindowID( ) function
ObjectDistance( ) function
Purpose
Returns the distance between two objects. You can call this function from the MapBasic window in
MapInfo Professional.
Syntax
ObjectDistance( object1, object2, unit_name )
object1 and object2 are object expressions.
unit_name is a string representing the name of a distance unit.
Return Value
Float
434
MapBasic 12.0
ObjectGeography( ) function
Purpose
Returns coordinate or angle information describing a graphical object. You can call this function from
the MapBasic window in MapInfo Professional.
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 (for example,
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. If
an object does not support z- or m-values, or a z- or m-value for this node is not defined, then an error
is thrown.
attribute setting
ID
OBJ_GEO_MINX
OBJ_GEO_MINY
OBJ_GEO_MAXX
OBJ_GEO_MAXY
Reference
435
ObjectGeography( ) function
attribute setting
ID
OBJ_GEO_ARCBEGANGLE
OBJ_GEO_ARCENDANGLE
OBJ_GEO_LINEBEGX
OBJ_GEO_LINEBEGY
OBJ_GEO_LINEENDX
OBJ_GEO_LINEENDY
OBJ_GEO_POINTX
OBJ_GEO_POINTY
OBJ_GEO_POINTZ
OBJ_GEO_POINTM
OBJ_GEO_ROUNDRADIUS
OBJ_GEO_CENTROID
OBJ_GEO_TEXTLINEX
OBJ_GEO_TEXTLINEY
OBJ_GEO_TEXTANGLE
The ObjectGeography( ) function has been extended to support Multipoints and Collections. Both types
support attributes 1 - 4 (coordinates of object's minimum bounding rectangle (MBR).
OBJ_GEO_MINX
OBJ_GEO_MINY
OBJ_GEO_MAXX
OBJ GEO_MAXY
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
436
MapBasic 12.0
ObjectInfo( ) function
Purpose
Returns Pen, Brush, or other values describing a graphical object. You can call this function from the
MapBasic window in MapInfo Professional.
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.
OBJ_INFO_NPOLYGONS (21) is an integer that indicates the number of polygons (in the case of a region)
or sections (in the case of a polyline) which make up an object.
OBJ_INFO_NPOLYGONS+N (21) is an integer that indicates the number of nodes in the Nth polygon
of a region or the Nth section of a polyline.
Note: With region objects, MapInfo Professional counts the starting node twice (once as the start node
and once as the end node). For example, ObjectInfo( ) returns a value of 4 for a triangle-shaped
region.
Description
The ObjectInfo( ) function returns general information about one aspect of a graphical object. The first
parameter should be an object value (for example, 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
Reference
437
ObjectInfo( ) function
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.
attribute Setting
ID
Return Value
OBJ_INFO_TYPE
OBJ_INFO_PEN
Pen style is returned; this query is only valid for the following object types: Arc, Ellipse, Line, Polyline, Frame, Regions, Rectangle, and Rounded Rectangle.
OBJ_INFO_BRUSH
Brush style is returned; this query is only valid for the following object types: Ellipse, Frame, Region, Rectangle,
and Rounded Rectangle.
OBJ_INFO_TEXTFONT
Font style is returned; this query is only valid for Text objects.
Note: If the Text object is contained in a mappable table
(as opposed to a Layout window), the Font specifies a point size of zero, and the text height is
controlled by the Map window's zoom distance.
OBJ_INFO_SYMBOL
OBJ_INFO_NPNTS
20
OBJ_INFO_SMOOTH
OBJ_INFO_FRAMEWIN
OBJ_INFO_FRAMETITLE
OBJ_INFO_NPOLYGONS
21
OBJ_INFO_NPOLYGONS+N
21
438
MapBasic 12.0
ID
Return Value
OBJ_INFO_TEXTSTRING
OBJ_INFO_TEXTSPACING
OBJ_INFO_TEXTJUSTIFY
OBJ_INFO_TEXTARROW
OBJ_INFO_FILLFRAME
OBJ_INFO_NONEMPTY
11
OBJ_INFO_REGION
OBJ_INFO_PLINE
Object value representing polyline part of a collection object. If the collection object does not have a polyline, it
returns an empty polyline object. This query is valid only
for collection objects.
OBJ_INFO_MPOINT
10
OBJ_INFO_Z_UNIT_SET
12
OBJ_INFO_Z_UNIT
13
OBJ_INFO_HAS_Z
14
OBJ_INFO_HAS_M
15
The codes in the left column (for example, OBJ_INFO_TYPE) are defined through the MapBasic definitions
file, MAPBASIC.DEF. Your program should Include "MAPBASIC.DEF" if you intend to call the ObjectInfo(
) function.
Each graphic attribute only applies to some types of graphic objects. For example, point objects are the
only objects with Symbol attributes, and text objects are the only objects with Font attributes. Therefore,
the ObjectInfo( ) function cannot return every type of attribute setting for every type of object.
Reference
439
ObjectInfo( ) function
If you specify OBJ_INFO_TYPE as the attribute setting, the ObjectInfo( ) function returns one of the
object types listed in the table below.
Table 5: OBJ_INFO_TYPE values
OBJ_INFO_TYPE values
ID
OBJ_TYPE_ARC
Arc object
OBJ_TYPE_ELLIPSE
OBJ_TYPE_LINE
Line object
OBJ_TYPE_PLINE
Polyline object
OBJ_TYPE_POINT
Point object
OBJ_TYPE_FRAME
OBJ_TYPE_REGION
Region object
OBJ_TYPE_RECT
Rectangle object
OBJ_TYPE_ROUNDRECT
OBJ_TYPE_TEXT
10
Text object
OBJ_TYPE_MULTIPOINT
11
OBJ_TYPE_COLLECTION
12
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:
440
MapBasic 12.0
ObjectLen( ) function
Purpose
Returns the geographic length of a line or polyline object. You can call this function from the MapBasic
window in MapInfo Professional.
Syntax
ObjectLen( expr, unit_name )
expr is an object expression.
unit_name is a string representing the name of a distance unit (for example, "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 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( ) function, Perimeter( ) function, Set Distance Units statement
Reference
441
ObjectNodeHasM( ) function
ObjectNodeHasM( ) function
Purpose
Returns TRUE if a specific node in a region, polyline or multipoint object has an m-value. You can call
this function from the MapBasic window in MapInfo Professional.
Syntax
ObjectNodeHasM( 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
Logical
Description
The ObjectNodeHasM( ) function returns TRUE if the specific node from a region, polyline, or multipoint
object has an m-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 ObjectNodeHasM( ) function supports
Multipoint objects and returns TRUE if a specific node in a Multipoint object has an m-value.
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.
If the object does not support m-values or an m-value for this node is not defined, it returns FALSE.
Example
The following example queries the first graphic object in the table Routes. If the first object is a polyline,
the program queries if the first node in the object has z-coordinates or m-values and queries z-coordinates
and m-values of the first node in the polyline.
Dim i_obj_type As SmallInt,
z, m As Float
hasZ, hasM as Logical
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
442
MapBasic 12.0
ObjectNodeHasZ( ) function
Purpose
Returns TRUE if a specific node in a region, polyline, or multipoint object has a z-coordinate. You can
call this function from the MapBasic window in MapInfo Professional.
Syntax
ObjectNodeHasZ( 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
Logical
Description
The ObjectNodeHasZ( ) function returns TRUE if a specific node from a region, polyline, or multipoint
object has a z-coordinate. 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 ObjectNodeHasZ( ) function supports Multipoint objects and returns TRUE if a specific node in a Multipoint object
has a z-coordinate.
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.
If object does not support z-coordinates or a z-coordinate for this node is not defined, it returns FALSE.
Reference
443
ObjectNodeM( ) function
Example
The following example queries the first graphic object in the table Routes. If the first object is a polyline,
the program queries if the first node in the object has z-coordinates or m-values and queries z-coordinates
and m-values of the first node in the polyline.
Dim i_obj_type As SmallInt,
z, m As Float
hasZ, hasM as Logical
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...
If (ObjectNodeHasZ(routes.obj, 1, 1)) Then
z = ObjectNodeZ(routes.obj, 1, 1) ' read z-coordinate
End If
If (ObjectNodeHasM(routes.obj, 1, 1)) Then
m = ObjectNodeM(routes.obj, 1, 1) ' read m-value
End If
End If
See Also:
Querying Map Objects, ObjectInfo( ) function
ObjectNodeM( ) function
Purpose
Returns the m-value of a specific node in a region, polyline, or multipoint object. You can call this function
from the MapBasic window in MapInfo Professional.
Syntax
ObjectNodeM( 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 ObjectNodeM( ) function returns the m-value of a specific node from a region, polyline, or multipoint
object.
444
MapBasic 12.0
ObjectNodeX( ) function
Purpose
Returns the x-coordinate of a specific node in a region or polyline object. You can call this function from
the MapBasic window in MapInfo Professional.
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. 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
Reference
445
ObjectNodeY( ) function
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 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 returns the value in the coordinate system currently in use by
MapBasic; by default, MapBasic uses a Longitude/Latitude coordinate system. See 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 statement, ObjectGeography( ) function, ObjectInfo( ) function, ObjectNodeY( )
function, Set CoordSys statement
ObjectNodeY( ) function
Purpose
Returns the y-coordinate of a specific node in a region or polyline object. You can call this function from
the MapBasic window in MapInfo Professional.
Syntax
ObjectNodeY( object, polygon_num, node_num )
object is an Object expression.
446
MapBasic 12.0
ObjectNodeZ( ) function
Purpose
Returns the z-value of a specific node in a region, polyline, or multipoint object.
Syntax
ObjectNodeZ( 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 ObjectNodeZ( ) function returns the z-value of a specific node from a region, polyline, or multipoint
object.
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 ObjectNodeZ( ) function supports Multipoint objects and returns the z-coordinate of a specific node in a Multipoint object.
Reference
447
448
MapBasic 12.0
Reference
449
450
MapBasic 12.0
Reference
451
Description
col_name = col_name
col_name = value
Used only for numeric columns. MapInfo Professional performs weighted averaging, averaging all
of the col_name column values, and weighting the
average calculation based on the contents of the
wt_colname 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 MapInfo Professional 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 MapInfo Professional assigns blank values to all of the columns
of the new row.
See Also:
Combine( ) function, Set Target statement
452
MapBasic 12.0
Reference
453
Effect
col_name = col_name
col_name = value
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:
Create Object statement
454
MapBasic 12.0
Reference
455
Effect
col_name = col_name
col_name = value
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 object, storing zero
values in numeric columns and blank values in character columns.
Example
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
456
MapBasic 12.0
Effect
col_name = col_name
col_name = value
Reference
457
Effect
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 the Objects Erase statement erases the parts of the target object. 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 Objects Erase statement.
Example
Objects Intersect Into Target
Data
Field2=Proportion(Field2)
See Also:
Create Object statement, Overlap( ) function, Objects Erase statement
458
MapBasic 12.0
Reference
459
460
MapBasic 12.0
Reference
461
Effect
col_name = col_name
col_name = value
The Data clause can contain an assignment for every column in the table. If the Data clause specifies
assignments for only 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
In the following partial example, the selected polyline is split at the specified node (node index of 12).
The unchanged values from each record of the selected polyline are inserted into the new records for
the split polyline.
Objects Pline Split At Node 12 Into Table WORLD Data
Country=Country,Capital=Capital,Continent=Continent,Numeric_code=Numeric_
code,FIPS=FIPS,ISO_2=ISO_2,ISO_3=ISO_3,Pop_1994=Pop_1994,Pop_Grw_Rt=Pop_G
rw_Rt,Pop_Male=Pop_Male,Pop_Fem=Pop_Fem...
See Also:
ObjectLen( ) function, ObjectNodeX( ) function, ObjectNodeY( ) function, Objects Disaggregate
statement
462
MapBasic 12.0
Reference
463
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 statement, Overlap( ) function
464
MapBasic 12.0
Effect
col_name = col_name
col_name = value
Used only for numeric columns; MapInfo Professional 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.
Example
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
Reference
465
Offset( ) function
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 "subdivision" 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 statement
Offset( ) function
Purpose
Returns a copy of the input object offset by the specified distance and angle. You can call this function
from the MapBasic window in MapInfo Professional.
Syntax
Offset( object, angle, distance, units )
object is the object being offset.
angle is the angle to offset the object.
distance is a number representing the distance to offset the object.
units is a string representing the unit in which to measure distance.
Return Value
Object
Description
Offset( ) produces a new object that is a copy of the input object offset by distance along angle (in degrees
with horizontal in the positive X-axis being 0 and positive being counterclockwise). The units string,
similar to that used for the ObjectLen( ) function or Perimeter( ) function, is the unit for the distance
value. The distance type used is Spherical unless the Coordinate System is NonEarth. For NonEarth,
Cartesian distance type is automatically used. The coordinate system used is the coordinate system of
the input object.
There are some considerations for Spherical measurements that do not hold for Cartesian measurements.
If you move an object that is in Lat/Long, the shape of the object remains the same, but the area of the
object will change. This is because you are picking one offset delta in degrees, and the actual measured
distance for a degree is different at different locations.
466
MapBasic 12.0
OffsetXY( ) function
Purpose
Returns a copy of the input object offset by the specified X and Y offset values. You can call this function
from the MapBasic window in MapInfo Professional.
Syntax
OffsetXY( object, xoffset, yoffset, units )
object is the object being offset.
xoffset and yoffset are numbers representing the distance along the x and y axes to offset the object.
units is a string representing the unit in which to measure distance.
Return Value
Object
Description
OffsetXY( ) produces a new object that is a copy of the input object offset by xoffset along the X-axis
and yoffset along the Y-axis. The units string, similar to that used for the ObjectLen( ) function or
Perimeter( ) function, is the unit for the distance values. The distance type used is Spherical unless
the coordinate system is NonEarth. For NonEarth, the Cartesian distance type is automatically used.
The coordinate system used is the coordinate system of the input object.
There are some considerations for Spherical measurements that do not hold for Cartesian measurements.
If you move an object that is in Lat/Long, the shape of the object remains the same, but the area of the
object will change. This is because you are picking one offset delta in degrees, and the actual measured
distance for a degree is different at different locations.
For the Offset functions, the actual offset delta is calculated at some fixed point on the object (for example,
the center of the bounding box), and then that value is converted from the input units into the coordinate
system's units. If the coordinate system is Lat/Long, the conversion to degrees uses the fixed point. The
actual converted distance measurement could vary at different locations on the object. The distance
Reference
467
OnError statement
from the input object and the new offset object is only guaranteed to be exact at the single fixed point
used.
Example
OffsetXY(Rect, 92, -22, "mi")
See Also:
Offset( ) function
OnError statement
Purpose
Enables an error-handling routine.
Syntax
OnError Goto{ label | 0 }
label is a string representing 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 errorhandler. (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 jumps 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 (for example, Exit Sub statement or End Program statement) 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
the 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 displays an error dialog box, then halts 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:
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 statement. This is because each label
468
MapBasic 12.0
Example
OnError GoTo no_states
Open Table "states"
OnError GoTo no_cities
Open Table "cities"
Map From cities, states
after_mapfrom:
OnError GoTo 0
'
' ...
'
End Program
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( ) function, Error statement, Error$( ) function, Resume statement
Reference
469
470
MapBasic 12.0
Reference
471
472
MapBasic 12.0
Reference
473
474
MapBasic 12.0
Reference
475
Overlap( ) function
The following table lists the available window_name values:
window_name value
Window Description
Help
Info
LayerControl
Legend
MapBasic
The MapBasic window. You also can refer to this window by its define code
from MAPBASIC.DEF (WIN_MAPBASIC).
Message
MoveMapTo
Ruler
Statistics
TableList
Note: The window IDs for Table List, Layer Control, and Move Map To are ignored by the Set Window
statement, WindowInfo( ) function, and WindowID( ) function.
You cannot open a document window (Map, Graph, Browse, Layout) through the Open Window statement. There is a separate statement for opening each type of document window (see the Map statement,
Graph statement, Browse statement, Layout statement, and Create Redistricter statement).
See Also:
Close Window statement, Print statement, Set Window statement
Overlap( ) function
Purpose
Returns an object representing the geographic intersection of two objects; produces results similar to
MapInfo Professional's Objects > Erase Outside command. You can call this function from the MapBasic
window in MapInfo Professional.
Syntax
Overlap( object1, object2 )
object1 is an object; it cannot be a point or text object.
object2 is an object; it cannot be a point or text object.
Return Value
An object that is the geographic intersection of object1 and object2.
476
MapBasic 12.0
OverlayNodes( ) function
Purpose
Returns an object based on an existing object, with new nodes added at points where the object intersects
a second object. You can call this function from the MapBasic window in MapInfo Professional.
Syntax
OverlayNodes( input_object, overlay_object )
input_object is an object whose nodes will be included in the output object; it may not be a point or text
object.
overlay_object is an object that will be intersected with input_object; it 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 the input_object intersects with the overlay_object.
If the input_object is a closed object (region, rectangle, rounded rectangle, or ellipse), OverlayNodes(
) returns a region object. If input_object is 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 does not add any nodes if input_object already has nodes at the points
of intersection.
See Also:
Objects Overlay statement
Reference
477
478
MapBasic 12.0
PathToDirectory$( ) function
Purpose
Returns only the specified file's directory. You can call this function from the MapBasic window in
MapInfo Professional.
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. The file specification C:\MAPINFO\DATA\WORLD.TAB includes the directory "C:\MAPINFO\DATA\".
Example
Dim s_filespec, s_filedir As String
s_filespec = "C:\MAPINFO\DATA\STATES.TAB"
s_filedir = PathToDirectory$(s_filespec)
' s_filedir now contains the string "C:\MAPINFO\DATA\"
See Also:
PathToFileName$( ) function, PathToTableName$( ) function
PathToFileName$( ) function
Purpose
Returns just the file name from a specified file. You can call this function from the MapBasic window in
MapInfo Professional.
Syntax
PathToFileName$( filespec )
filespec is a string expression representing a full file specification.
Return Value
String
Reference
479
PathToTableName$( ) function
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. The PathToFileName$( ) function returns
the file's name, including the file extension if there is one.
The file specification C:\MAPINFO\DATA\WORLD.TAB includes a directory ("C:\MAPINFO\DATA\") and
a filename ("WORLD.TAB").
Example
Dim s_filespec, s_filename As String
s_filespec = "C:\MAPINFO\DATA\STATES.TAB"
s_filename = PathToFileName$(s_filespec)
' filename now contains the string "STATES.TAB"
See Also:
PathToDirectory$( ) function, PathToTableName$( ) function
PathToTableName$( ) function
Purpose
Returns a string representing a table alias (such as "_2013_Data") from a complete file specification
(such as "C:\MapInfo\Data\2013 Data.tab"). You can call this function from the MapBasic window in
MapInfo Professional.
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
(for example, on the title bar of a Browser window).
To convert a file name to a table alias, MapInfo Professional removes the directory path from the beginning
of the string and removes ".TAB" from the end of the string. Any special characters (for example, spaces
or punctuation marks) are replaced with the underscore character (_). If the table name starts with a
number, MapInfo Professional inserts an underscore at the beginning of the alias (this increases the
number of characters by 1, so if the table name is 30 characters adding an underscore makes it 31
characters in length). If the resulting string is longer than 31 characters, MapInfo Professional trims
characters from the end; aliases cannot be longer than 31 characters.
480
MapBasic 12.0
Pen clause
Purpose
Specifies a line style for graphic objects. You can use this clause in the MapBasic window in MapInfo
Professional.
Syntax
Pen pen_expr
pen_expr is a Pen expression, for example, MakePen( width, pattern, color )
Description
The Pen clause specifies a line stylein 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 the
Create Line statement, 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 (for example, the CurrentPen( ) function or the MakePen( ) function) which returns
a Pen value:
Pen MakePen(1, 2, BLUE)
You can create an interleaved line style by adding 128 to the pattern value. The following example draws
a two (2) pixel cyan colored line using pattern 101 in an interleaved style (101+128=229):
Pen MakePen(2, 229, CYAN)
Reference
481
Pen clause
With some MapBasic statements (for example, the Set Map statement), 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 (for example, 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).
To specify a width using points, calculate the pen width from a point size
using the PointsToPenWidth( ) function. This calculation multiplies the
point size by 10 and then adds 10 to the result, so the pen width is always
larger than 10.
pattern
color
482
MapBasic 12.0
Examples
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)
Apply line styles to a layer in a map as a layer style override: Pen width = 5 points; Line style B17 in line
style picker; penpattern = 66.
Set Map Window <windowid>
Layer 1 Display Global
Global Line (60,194,16711680)
' Interleave: 194 = 66 + 128
Set Map Window 234499920
Layer 1 Display Global
Global Line MakePen(PointsToPenWidth(5),66,16711680)
' 5 point line, non-interleaved
See Also:
Alter Object statement, CreateLine( ) function, Create Pline statement, CurrentPen( ) function,
IsPenWidthPixels( ) function, MakePen( ) function, PointsToPenWidth( ) function, PenWidthToPoints( ) function, RGB( ) function, Set Style statement
Reference
483
PenWidthToPoints( ) function
PenWidthToPoints( ) function
Purpose
Returns the point size for a given pen width. You can call this function from the MapBasic window in
MapInfo Professional.
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( ) only returns 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( ) function, IsPenWidthPixels( ) function, MakePen( ) function, Pen clause, PointsToPenWidth( ) function, StyleAttr( ) function
Perimeter( ) function
Purpose
Returns the perimeter of a graphical object. You can call this function from the MapBasic window in
MapInfo Professional.
Syntax
Perimeter( obj_expr, unit_name )
484
MapBasic 12.0
Reference
485
PointsToPenWidth( ) function
PointsToPenWidth( ) function
Purpose
Returns a pen width for a given point size. You can call this function from the MapBasic window in
MapInfo Professional.
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( ) function, IsPenWidthPixels( ) function, MakePen( ) function, Pen clause, PenWidthToPoints( ) function, StyleAttr( ) function
PointToMGRS$( ) function
Purpose
Converts an object value representing a point into a string representing an MGRS (Military Grid Reference
System) coordinate. Only point objects are supported. You can call this function from the MapBasic
window in MapInfo Professional.
Syntax
PointToMGRS$( inputobject )
inputobject is an object expression representing a point.
Description
MapInfo Professional automatically converts the input point from the current MapBasic coordinate system
to a Long/Lat (WGS84) datum before performing the conversion to an MGRS string. However, by default,
the MapBasic coordinate system is Long/Lat (no datum); using this as an intermediate coordinate system
486
MapBasic 12.0
Reference
487
PointToUSNG$( ) function
PointToUSNG$( ) function
Purpose
Converts an object value representing a point into a string representing an USNG (United States National
Grid) coordinate. Only point objects are supported. You can call this function from the MapBasic window
in MapInfo Professional.
Syntax
PointToUSNG$(obj, datumid)
obj is an object expression representing the point to be converted. It must evaluate to a point object.
datumid is a numeric expression representing the datum id. It must evaluate to one of the following values.
DATUMID_NAD27 (62)
DATUMID_NAD83 (74)
DATUMID_WGS84 (104)
Note: DATUMID_* are defines in MapBasic.def. WGS84 and NAD83 are treated as equivalent.
Description
MapInfo Professional automatically converts the input point from the current MapBasic coordinate system
to a Long/Lat (WGS84 and NAD27) datum before performing the conversion to an USNG string. However,
by default, the MapBasic coordinate system is Long/Lat (no datum); using this as an intermediate coordinate system can cause a significant loss of precision in the final output, since datumless conversions
are much less accurate. As a rule, the MapBasic coordinate system should be set to either Long/Lat
(WGS84 and NAD27) or to the coordinate system of the source data table, so that no unnecessary intermediate conversions are performed.
Return Value
String
Example 1
The following example illustrates the use of USNGToPoint( ) and PointToUSNG$( ) functions.
dim obj1 as Object
dim s_USNG As String
dim obj2 as Object
obj1 = CreatePoint(-74.669, 43.263)
s_USNG = PointToUSNG$(obj1)
obj2 = USNGToPoint(s_USNG)
Example 2
Open Table "C:\Temp\MyTable.TAB" as USNGfile
' When using the PointToUSNG$( ) or USNGToPoint( ) functions,
' it is very important to make sure that the current MapBasic
488
MapBasic 12.0
Print statement
Purpose
Prints a prompt or a status message in the Message window. You can issue this statement from the
MapBasic window in MapInfo Professional.
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
Reference
489
Print # statement
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 next example displays the Message window, sets the window's size (three inches wide by one inch
high), sets the window's font (Arial, 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 ("Arial", 1, 10, BLUE) ' Arial 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( ) function, Close Window statement, Note statement, Open Window statement, Set Window
statement
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 and 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 the Write # statement instead of Print #.
490
MapBasic 12.0
PrintWin statement
Purpose
Prints an existing window. You can issue this statement from the MapBasic window in MapInfo Professional.
Syntax
PrintWin [ Window window_id ][ Interactive ][ File output_filename ]
[ Overwrite ]
window_id is a window identifier.
output_filename is a string representing the name of an output file. If the output file already exists, an
error will occur, unless the Overwrite keyword is specified.
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( ) function and the
WindowInfo( ) function for more information about obtaining window identifiers.
If you include the Interactive keyword, MapInfo Professional displays the Print dialog box. If you omit
the Interactive keyword, MapInfo Professional prints the window automatically, without displaying the
dialog box.
Examples
Example 1
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
Example 2
PrintWin Window FrontWindow( ) File "c:\output\file.plt"
See Also:
FrontWindow( ) function, Run Menu Command statement, WindowInfo( ) function
Reference
491
PrismMapInfo( ) function
PrismMapInfo( ) function
Purpose
Returns properties of a Prism Map window. You can call this function from the MapBasic window in
MapInfo Professional.
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.
Return Value
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.
492
Attribute
ID
Return Value
PRISMMAP_INFO_SCALE
PRISMMAP_INFO_BACKGROUND
PRISMMAP_INFO_LIGHT_X
PRISMMAP_INFO_LIGHT_Y
PRISMMAP_INFO_LIGHT_Z
PRISMMAP_INFO_LIGHT_COLOR
PRISMMAP_INFO_CAMERA_X
10
MapBasic 12.0
ID
Return Value
PRISMMAP_INFO_CAMERA_Y
11
PRISMMAP_INFO_CAMERA_Z
12
PRISMMAP_INFO_CAMERA_FOCAL_X
13
PRISMMAP_INFO_CAMERA_FOCAL_Y
14
PRISMMAP_INFO_CAMERA_FOCAL_Z
15
PRISMMAP_INFO_CAMERA_VU_1 16
PRISMMAP_INFO_CAMERA_VU_2 17
PRISMMAP_INFO_CAMERA_VU_3 18
PRISMMAP_INFO_CAMERA_VPN_1 19
PRISMMAP_INFO_CAMERA_VPN_2 20
Float result representing the second value of the ViewPlane Unit Normal Vector.
PRISMMAP_INFO_CAMERA_VPN_3 21
PRISMMAP_INFO_CAMERA_CLIP_NEAR
22
PRISMMAP_INFO_CAMERA_CLIP_FAR
23
PRISMMAP_INFO_INFOTIP_EXPR
24
Example
This example prints out all the state variables specific to the PrismMap window:
include "Mapbasic.def"
Print "PRISMMAP_INFO_SCALE: " + PrismMapInfo(FrontWindow( ),
PRISMMAP_INFO_SCALE)
Print "PRISMMAP_INFO_BACKGROUND: " + PrismMapInfo(FrontWindow( ),
PRISMMAP_INFO_BACKGROUND)
Print "PRISMMAP_INFO_UNITS: " + PrismMapInfo(FrontWindow( ),
PRISMMAP_INFO_UNITS)
Print "PRISMMAP_INFO_LIGHT_X : " + PrismMapInfo(FrontWindow( ),
PRISMMAP_INFO_LIGHT_X )
Reference
493
ProgramDirectory$( ) function
Print "PRISMMAP_INFO_LIGHT_Y : " + PrismMapInfo(FrontWindow( ),
PRISMMAP_INFO_LIGHT_Y )
Print "PRISMMAP_INFO_LIGHT_Z: " + PrismMapInfo(FrontWindow( ),
PRISMMAP_INFO_LIGHT_Z)
Print "PRISMMAP_INFO_LIGHT_COLOR: " + PrismMapInfo(FrontWindow( ),
PRISMMAP_INFO_LIGHT_COLOR)
Print "PRISMMAP_INFO_CAMERA_X: " + PrismMapInfo(FrontWindow( ),
PRISMMAP_INFO_CAMERA_X)
Print "PRISMMAP_INFO_CAMERA_Y : " + PrismMapInfo(FrontWindow( ),
PRISMMAP_INFO_CAMERA_Y )
Print "PRISMMAP_INFO_CAMERA_Z : " + PrismMapInfo(FrontWindow( ),
PRISMMAP_INFO_CAMERA_Z )
Print "PRISMMAP_INFO_CAMERA_FOCAL_X: " + PrismMapInfo(FrontWindow( ),
PRISMMAP_INFO_CAMERA_FOCAL_X)
Print "PRISMMAP_INFO_CAMERA_FOCAL_Y: " + PrismMapInfo(FrontWindow( ),
PRISMMAP_INFO_CAMERA_FOCAL_Y)
Print "PRISMMAP_INFO_CAMERA_FOCAL_Z: " + PrismMapInfo(FrontWindow( ),
PRISMMAP_INFO_CAMERA_FOCAL_Z)
Print "PRISMMAP_INFO_CAMERA_VU_1: " + PrismMapInfo(FrontWindow( ),
PRISMMAP_INFO_CAMERA_VU_1)
Print "PRISMMAP_INFO_CAMERA_VU_2: " + PrismMapInfo(FrontWindow( ),
PRISMMAP_INFO_CAMERA_VU_2)
Print "PRISMMAP_INFO_CAMERA_VU_3: " + PrismMapInfo(FrontWindow( ),
PRISMMAP_INFO_CAMERA_VU_3)
Print "PRISMMAP_INFO_CAMERA_VPN_1: " + PrismMapInfo(FrontWindow( ),
PRISMMAP_INFO_CAMERA_VPN_1)
Print "PRISMMAP_INFO_CAMERA_VPN_2: " + PrismMapInfo(FrontWindow( ),
PRISMMAP_INFO_CAMERA_VPN_2)
Print "PRISMMAP_INFO_CAMERA_VPN_3: " + PrismMapInfo(FrontWindow( ),
PRISMMAP_INFO_CAMERA_VPN_3)
Print "PRISMMAP_INFO_CAMERA_CLIP_NEAR: " + PrismMapInfo(FrontWindow( ),
PRISMMAP_INFO_CAMERA_CLIP_NEAR)
Print "PRISMMAP_INFO_CAMERA_CLIP_FAR: " + PrismMapInfo(FrontWindow( ),
PRISMMAP_INFO_CAMERA_CLIP_FAR)
See Also:
Create PrismMap statement, Set PrismMap statement
ProgramDirectory$( ) function
Purpose
Returns the directory path to where the MapInfo Professional software is installed. You can call this
function from the MapBasic window in MapInfo Professional.
Syntax
ProgramDirectory$( )
Return Value
String
494
MapBasic 12.0
ProgressBar statement
Purpose
Displays a dialog box 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 box.
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 box 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). Where CMD_INFO_DLG_OK (1).
The status_message parameter is a string value, such as "Processing data...", which is displayed in the
dialog box.
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.
Reference
495
ProgressBar statement
When a program issues a ProgressBar statement, MapBasic calls the specified handler sub procedure.
The sub procedure should perform a small amount of processing, specifically 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 box, 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.
If the handler assigns a value of negative one to the ProgressBar variable (ProgressBar = -1) then
MapBasic detects that the operation is finished, and accordingly halts the ProgressBar loop and removes
the dialog box. Alternately, if the handler procedure assigns a value other than negative one to the ProgressBar variable (ProgressBar = 50) then MapBasic re-displays the dialog box's "percent complete"
horizontal bar, to reflect the latest figure of percent completion. MapBasic calculates the current percent
of completion by dividing the current value of the ProgressBar variable by the Range setting, n. For example, if the ProgressBar statement specified the Range clause Range 400 and if the current value
of the ProgressBar variable is 100, then the current percent of completion is 25%, and MapBasic will
display the horizontal bar as being 25% filled.
The statements following the ProgressBar statement often must determine whether the ProgressBar
loop halted because the operation was finished, or because the user clicked the Cancel button. Immediately following the ProgressBar statement, the function call CommandInfo(CMD_INFO_DLG_OK)
returns TRUE if the operation was complete, or FALSE if the operation halted because the user clicked
cancel. Where CMD_INFO_DLG_OK (1).
Example
The following example demonstrates how a procedure can be written to work in conjunction with the
ProgressBar statement. In this example, we have an operation involving 600 iterations; perhaps we
have a table with 600 rows, and each row must be processed in some fashion. The main procedure issues
the ProgressBar statement, which then automatically calls the sub procedure, write_out. The write_out
procedure processes records until two seconds have elapsed, and then returns (so that MapBasic can
check to see if the user pressed Cancel). If the user does not press Cancel, MapBasic will repeatedly
call the write_out procedure until the entire task is done.
Include "mapbasic.def"
Declare Sub Main
Declare Sub write_out
Global next_row As Integer
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
496
MapBasic 12.0
Proper$( ) function
Purpose
Returns a mixed-case string, where only the first letter of each word is capitalized. You can call this
function from the MapBasic window in MapInfo Professional.
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
Reference
497
ProportionOverlap( ) function
name = "ed bergen"
propername = Proper$(name)
' propername now contains the string "Ed Bergen"
name = "ABC 123"
propername = Proper$(name)
' propername now contains the string "Abc 123"
name = "a b c d"
propername = Proper$(name)
' propername now contains the string "A B C D"
See Also:
LCase$( ) function, UCase$( ) function
ProportionOverlap( ) function
Purpose
Returns a number that indicates what percentage of one object is covered by another object. You can
call this function from the MapBasic window in MapInfo Professional.
Syntax
ProportionOverlap( object1, object2 )
object1 is the bottom object, and it is a closed object.
object2 is the top object, and it is a closed object.
Return Value
A float value equal to AreaOverlap( object1, object2 ) / Area( object1 ).
Restrictions
ProporationOverlap( ) only works on closed objects. If both objects are not closed (such as points and
lines), then you may see an error message. Closed objects are objects that can produce an area, such
as regions (polygons).
See Also:
AreaOverlap( ) function
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.
498
MapBasic 12.0
Storage In File
Logical
SmallInt
Integer
Float
String
Date
Cannot be written.
The Position parameter sets the file pointer to a specific offset in the file. When the file is opened, the
position is initialized to 1 (the start of the file). As a Put is done, the position is incremented by the
number of bytes written. If the Position clause is not used, the Put simply writes to the current file position.
If the file was opened in Binary mode, the Put statement cannot specify a variable-length string variable;
any string variable used in a Put statement must be fixed-length. If the file was opened in Random mode,
the Put statement cannot specify a fixed-length string variable which is longer than the record length of
the file.
See Also:
EOF( ) function, Get statement, Open File statement, Print # statement, Write # statement
Randomize statement
Purpose
Initializes MapBasic's random number function. You can issue this statement from the MapBasic window
in MapInfo Professional.
Reference
499
RasterTableInfo( ) 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 the Rnd( ) function, 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 the Rnd( ) function 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( ) function
RasterTableInfo( ) function
Purpose:
Returns information about a Raster or Grid Table. (WMS, Tile Server, and Seamless Raster tables not
supported).
Syntax:
RasterTableInfo( table_id, attribute )
table_id is a string representing a table name, a positive integer table number, or 0 (zero). The table
must be a raster or grid table.
attribute is an integer code indicating which aspect of the raster table to return.
Return Value
String, SmallInt, Integer or Logical, depending on the attribute parameter specified.
The attribute parameter can be any value from the table below. Codes in the left column (for example,
RASTER_TAB_INFO_IMAGE_NAME) are defined in MAPBASIC.DEF.
500
MapBasic 12.0
ID
RasterTableInfo() returns
RASTER_TAB_INFO_IMAGE_NAME 1
RASTER_TAB_INFO_WIDTH
RASTER_TAB_INFO_HEIGHT
RASTER_TAB_INFO_IMAGE_TYPE 4
RAS5
TER_TAB_INFO_BITS_PER_PIXEL
RASTER_TAB_INFO_IMAGE_CLASS 6
RASTER_TAB_INFO_NUM_CONTROL_POINTS
RASTER_TAB_INFO_BRIGHTNESS 8
RASTER_TAB_INFO_CONTRAST
RASTER_TAB_INFO_GREYSCALE 10
RASTER_TAB_INFO_DISPLAY_TRANSPARENT
Reference
11
501
RegionInfo( ) function
attribute code
ID
RasterTableInfo() returns
RASTER_TAB_INFO_TRANSPARENT_COLOR
12
RASTER_TAB_INFO_ALPHA
13
See Also:
Create Grid statement, GetGridCellValue( ) function, GridTableInfo( ), IsGridCellNull( ) function
RegionInfo( ) function
Purpose:
This function was created to determine the orientation of points in polygonswhether they are ordered
clockwise, or counter-clockwise. The only attribute the function reports on is the 'direction' of the points
in a specified polygon. You can call this function from the MapBasic window in MapInfo Professional.
Syntax:
RegionInfo( object, REGION_INFO_IS_CLOCKWISE, polygon_num )
Where:
REGION_INFO_IS_CLOCKWISE
ReadControlValue( ) function
Purpose
Reads the current status of a control in the active dialog box.
502
MapBasic 12.0
EditText
String, up to 32,767 bytes long, representing the current contents of the text
box; if the EditText is tall enough to accommodate multiple lines of text, the
string may include Chr$(10) values, indicating that the user entered linefeeds (for example, in Windows, by pressing Ctrl+Enter).
CheckBox
DocumentWindow
Integer that represents the HWND for the window control. This HWND should
be passed as the parent window handle in the Set Next Document statement.
RadioGroup
SmallInt value identifying which button is selected (1 for the first button).
PopupMenu
SmallInt value identifying which item is selected (1 for the first item).
ListBox
SmallInt value identifying the selected list item (1 for the first, 0 if none).
BrushPicker
Brush value.
FontPicker
Font value.
PenPicker
Pen value.
Reference
503
ReadControlValue( ) function
Control Type
SymbolPicker
Symbol value.
MultiListBox
Integer identifying one of the selected items. The user can select one or more
of the items in a MultiListBox control. Since ReadControlValue( ) can only
return one piece of information at a time, your program may need to call
ReadControlValue( ) multiple times in order to determine how many items
are selected.
The first call to ReadControlValue( ) returns the number of the first selected
list item (1 if the first list item is selected); the second call will return the
number of the second selected list item, etc. When ReadControlValue( )
returns zero, the list of selected items has been exhausted. Subsequent calls
to ReadControlValue( ) then begin back at the top of the list of selected
items. If ReadControlValue( ) returns zero on the first call, none of the list
items are selected.
Error Conditions
ERR_FCN_ARG_RANGE (644) error is generated if an argument is outside of the valid range.
ERR_INVALID_READ_CONTROL (842) error is generated if the ReadControlValue( ) function is called
when no dialog box is active.
Example
The following example creates a dialog box that asks the user to type a name in a text edit box. If the
user clicks OK, the application calls ReadControlValue( ) to read in the name that was typed.
Declare Sub Main
Declare Sub okhandler
Sub Main
Dialog
Title "Sign in, Please"
Control OKButton
Position 135, 120 Width 50
Title "OK"
Calling okhandler
Control CancelButton
Position 135, 100 Width 50
Title "Cancel"
Control StaticText
Position 5, 10
Title "Please enter your name:"
Control EditText
Position 55, 10 Width 160
Value "(your name here)"
Id 23 'arbitrary ID number
End Sub
Sub okhandler
' this sub is called when/if the user
' clicks the OK control
Note "Welcome aboard, " + ReadControlValue(23) + "!"
End Sub
504
MapBasic 12.0
ReDim statement
Purpose
Re-sizes an array variable.
Syntax
ReDim var_name ( newsize ) [ , ... ]
var_name is a string representing the name of an existing local or global array variable.
newsize is an integer value dictating the new array size. 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 statement
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
Reference
505
506
MapBasic 12.0
Reference
507
508
MapBasic 12.0
Reference
509
Example: DBF
Register Table "c:\mapinfo\data\rpt23.dbf"
Type DBF
Into "Report23"
Open Table "c:\mapinfo\data\Report23"
510
MapBasic 12.0
Reference
511
512
MapBasic 12.0
Reference
513
RemoteMapGenHandler procedure
directory is a string representing a directory path.
Description
This statement is used by the SYMBOL.MBX utility, which allows users to create custom symbols.
Note: MapInfo 3.0 Symbols refers to the symbol set that came with MapInfo Professional for Windows
3.0 and has been maintained in subsequent versions of MapInfo Professional.
See Also:
Alter Object statement
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 Professional, 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 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.
514
MapBasic 12.0
RemoteQueryHandler( ) function
Purpose
A special function, called when a MapBasic program acts as a DDE server, and the DDE client performs
a "peek" request. You can call this function from the MapBasic window in MapInfo Professional.
Reference
515
RemoteQueryHandler( ) function
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 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, MapInfo Professional 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, MapInfo Professional 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 the CommandInfo( ) function 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)
If s_item_name = "code1" Then
RemoteQueryHandler = custom_function_1( )
Else
RemoteQueryHandler = custom_function_2( )
End If
End Function
See Also:
DDEInitiate( ) function, RemoteMsgHandler procedure
516
MapBasic 12.0
Reference
517
518
MapBasic 12.0
Descriptions of Examples
If you include the Interactive keyword, and if the layer removal will cause the loss of labels or themes,
MapInfo Professional displays a dialog box that allows the user to save (a workspace), discard the labels
and themes, or cancel the layer removal. If you omit the Interactive keyword, the user is not prompted.
A Remove Map statement does not close any tables; it only affects the number of layers displayed in
the Map window. If a Remove Map statement removes the last non-cosmetic layer in a Map window,
MapInfo Professional automatically closes the window.
See Also:
Create Map statement, Map statement, Set Map statement
Reference
519
520
MapBasic 12.0
Reproject statement
Purpose
Allows you to specify which columns should appear the next time a table is browsed. This statement
has been deprecated.
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.
Reference
521
RGB( ) function
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( ) function, Error statement, Error$( ) function, OnError statement
RGB( ) function
Purpose
Returns an RGB color value calculated from Red, Green, Blue components. You can call this function
from the MapBasic window in MapInfo Professional.
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 (for example,
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 blueeach
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:
( red * 65536) + ( green * 256) + blue
522
MapBasic 12.0
Right$( ) function
Purpose
Returns part or all of a string, beginning at the right end of the string. You can call this function from the
MapBasic window in MapInfo Professional.
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)
' at this point, partial contains the string: "stan"
Reference
523
Rnd( ) function
See Also:
Left$( ) function, Mid$( ) function
Rnd( ) function
Purpose
Returns a random number. You can call this function from the MapBasic window in MapInfo Professional.
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 statement
Rollback statement
Purpose
Discards a table's unsaved edits. You can issue this statement from the MapBasic window in MapInfo
Professional.
Syntax
Rollback Table tablename
tablename is the name of an open table.
524
MapBasic 12.0
Rotate( ) function
Purpose
Allows an object (not a text object) to be rotated about the rotation anchor point. You can call this function
from the MapBasic window in MapInfo Professional.
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
The Rotate( ) function 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.
Reference
525
RotateAtPoint( ) function
If an arc, ellipse, rectangle, or rounded rectangle is rotated, the resultant object is 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:
RotateAtPoint( ) function
RotateAtPoint( ) function
Purpose
Allows an object (not a text object) to be rotated about a specified anchor point. You can call this function
from the MapBasic window in MapInfo Professional.
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
The RotateAtPoint( ) function 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 is 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"
526
MapBasic 12.0
Round( ) function
Purpose
Returns a number obtained by rounding off another number. You can call this function from the MapBasic
window in MapInfo Professional.
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, MapInfo Professional 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( ) function, Format$( ) function, Int( ) function
Reference
527
RTrim$( ) function
RTrim$( ) function
Purpose
Trims space characters from the end of a string, and returns the results. You can call this function from
the MapBasic window in MapInfo Professional.
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 ")
' s_name now contains the string "Mary Smith"
' (no spaces at the end)
See Also:
LTrim$( ) function
528
MapBasic 12.0
Reference
529
"
+ "world"
From "
+ "world"
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 commaseparated 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
Open Table "states"
Open Table "cities"
Open Table "counties"
cmd_text = "states" ' always include STATES layer
If counties_wanted Then
cmd_text = "counties, " + cmd_text
End If
If cities_wanted Then
cmd_text = "cities, " + cmd_text
End If
Run Command "Map From " + cmd_text
The following example shows how to duplicate a Map window, given the window ID of an existing map.
The WindowInfo( ) function returns a string containing MapBasic statements; the Run Command
statement executes the string.
Dim i_map_id As Integer
' First, get the ID of an existing Map window
' (assuming the Map window is the active window):
i_map_id = FrontWindow( )
' Now clone the active map window:
Run Command WindowInfo(i_map_id, WIN_INFO_CLONEWINDOW)
See Also:
530
MapBasic 12.0
Reference
531
532
MapBasic 12.0
Reference
533
534
MapBasic 12.0
Reference
535
Any non-map windows (browsers, charts, redistricters, 3D map windows, Prism maps);
Distance, area, or XY and military grid units;
Snap mode, autoscroll, and smart pan settings;
Printer setup information;
Any table that is based on a query that is not referenced by a window;
Any theme that is based upon computed columns, or based on an expression that cannot be translated
from MapBasic syntax to MI SQL syntax;
Labels based on expressions that cannot be translated from MapBasic syntax to MI SQL syntax;
Queries with "sub-select" statements;
Layers based on queries that includes "sub-select" statements;
Note: A "sub-select" statement is any Select statement nested inside another Select statement.
Export options;
Hot links for labels and objects;
Group layers;
Whether object nodes, centroids or line direction is displayed.
See Also:
Save Workspace statement
536
MapBasic 12.0
Reference
537
538
MapBasic 12.0
SearchInfo( ) function
Purpose
Returns information about the search results produced by SearchPoint( ) or SearchRect( ). You can call
this function from the MapBasic window in MapInfo Professional.
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.
Reference
539
SearchInfo( ) function
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:
attribute code
ID
SearchInfo( ) returns:
SEARCH_INFO_TABLE
SEARCH_INFO_ROW
Integer value: this row's rowID number. You can use this
rowID number in a Fetch statement or in a Select
statement's Where clause.
Search results remain in memory until the application halts or until you perform another search. Note
that search results remain in memory even after the user closes the window or the tables associated
with the search; therefore, you should process search results immediately. To manually free the memory
used by search results, perform a search which you know will fail (for example, search at location 0, 0).
MapInfo Professional maintains a separate set of search results for each MapBasic application that is
running, plus another set of search results for MapInfo Professional itself (for commands entered through
the MapBasic window).
Error Conditions
ERR_FCN_ARG_RANGE (644) error is generated if sequence_number is larger than the number of
objects located.
Example
The following program creates two custom tool buttons. If the user uses the point tool, this program calls
the SearchPoint( ) function; if the user uses the rectangle tool, the program calls the SearchRect( )
function. In either case, this program calls SearchInfo( ) to determine which object(s) the user chose.
Include
Include
Declare
Declare
"mapbasic.def"
"icons.def"
Sub Main
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
Print "Searcher program now running."
540
MapBasic 12.0
Reference
541
SearchPoint( ) function
SearchPoint( ) function, SearchRect( ) function
SearchPoint( ) function
Purpose
Searches for map objects at a specific x/y location. You can call this function from the MapBasic window
in MapInfo Professional.
Syntax
SearchPoint( map_window_id, x, y )
map_window_id is a Map window's integer ID number
x is an x-coordinate (for example, longitude)
y is a y-coordinate (for example, 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 the SearchInfo( ) function 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 the CommandInfo( ) function to determine the
x/y coordinates.
Example
For a code example, see the SearchInfo( ) function.
See Also:
SearchInfo( ) function, SearchRect( ) function
542
MapBasic 12.0
SearchRect( ) function
Purpose
Searches for map objects within a rectangular area. You can call this function from the MapBasic window
in MapInfo Professional.
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( )
function 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 statementor
the Alter Button statement to create a custom ToolButton. Use DM_CUSTOM_RECT as the button's
draw mode. Within the button's handler procedure, call CommandInfo( ) function to determine the x/y
coordinates.
Example
For a code example, see the SearchInfo( ) function.
See Also:
SearchInfo( ) function, SearchPoint( ) function
Reference
543
Second( ) function
Second( ) function
Purpose
Retrieves the second part of a Time value as Float (0-59.999). You can call this function from the MapBasic window in MapInfo Professional.
Syntax
Second( Time )
Return Value
Number
Example
Copy this example into the MapBasic window for a demonstration of this function.
dim X as time
dim fSec as Float
X = CurDateTime()
fSec = Second(X)
Print fSec
See Also:
Hour( ) function, Minute( ) function
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 filenum 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
544
MapBasic 12.0
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 statement, Input # statement, Open File statement, Print # statement, Put statement, Seek( )
function, Write # statement
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.
Reference
545
Select statement
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( ) function with one of the following codes:
attribute code
ID
CMD_INFO_SELTYPE
CMD_INFO_ROWID
CMD_INFO_INTERRUPT
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 SelChangedHandler procedure once it is no longer wanted. Be careful not to issue an End Program statement
while the SelChangedHandler procedure is still needed.
Multiple MapBasic applications can be "sleeping" at the same time. When the Selection table changes,
MapBasic automatically calls all sleeping SelChangedHandler procedures, one after another.
A SelChangedHandler procedure should not take actions that affect the GUI "focus" or reset the current
window. In other words, the SelChangedHandler procedure should not issue statements such as a
Note statement, Print statement, or Dialog statement.
See Also:
CommandInfo( ) function, SelectionInfo( ) function
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. You can issue this statement from
the MapBasic window in MapInfo Professional.
Syntax
Select expression_list
From table_name [ , ... ] [ Where expression_group ]
[ Into results_table [ Noselect ] ]
546
MapBasic 12.0
Reference
547
Select statement
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
548
MapBasic 12.0
Reference
549
Select statement
In the example above, the sub-select produces a set of values, and the main Select statement's Where
clause tests for inclusion in that set of values. Alternately, a sub-select might use an aggregate operator
to produce a single result.
The example below uses the Avg( ) aggregate operator to calculate the average value of the pop field
within the table states.
Accordingly, the net result of the following Select statement is that all records having higher-than-average
population are selected.
Select * From states
Where population >
(Select Avg(population) From states)
MapInfo Professional also supports the SQL keyword In. A Select statement can use the keyword In in
place of the operator sequence = Any. In other words, the following Where clause, which uses the Any
keyword:
Where state = Any ("NY", "MA", "PA")
is equivalent to the following Where clause, which uses the In keyword:
Where state In ("NY", "MA", "PA")
In a similar fashion, the keywords Not In may be used in place of the operator sequence: <> All.
Note: A single Select statement may not include multiple, non-nested subqueries. Additionally, MapBasic's Select statement does not support "correlated subqueries." A correlated subquery involves
the inner query referencing a variable from the outer query. Thus, the inner query is reprocessed
for each row in the outer table. Thus, the queries are correlated. An example:
' Note: the following statement, which illustrates
' correlated subqueries, will NOT work in MapBasic
Select * from leads
Where lead.name =
(Select var.name From vars
Where lead.name = customer.name)
This limitation is primarily of interest to users who are already proficient in SQL queries, through the use
of other SQL-compatible database packages.
Into clause
This optional clause lets you name the results table. If no Into clause is specified, the resulting table is
named Selection. Note that when a subsequent operation references the Selection table, MapInfo Professional will take a "snapshot" of the Selection table, and call the snapshot QUERYn (for example,
QUERY1).
If you include the Noselect keyword, the statement performs a query without changing the pre-existing
Selection table. Use the NoSelect keyword if you need to perform a query, but you do not want to deselect whatever rows are already selected.
If you include the Noselect keyword, the query does not trigger the SelChangedHandler procedure.
550
MapBasic 12.0
Description
Avg( column )
Count( * )
integer
Max( column )
float
Reference
Returns
551
Select statement
Function name
Description
Min( column )
Sum( column )
Returns
float
float
Note: No MapBasic function, aggregate or otherwise, returns a decimal value. A decimal field is only
a way of storing the data. The arithmetic is done with floating point numbers.
552
MapBasic 12.0
Reference
553
Select statement
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.
Usage
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 MapInfo Professional will not be able
to take maximum advantage of indexing.
Similarly, MapInfo Professional 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.
554
MapBasic 12.0
SelectionInfo( ) function
Purpose
Returns information about the current selection. You can call this function from the MapBasic window
in MapInfo Professional.
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.
Reference
555
ID
SEL_INFO_TABLENAME
String: The name of the table the selection was based on.
Returns an empty string if no data currently selected.
SEL_INFO_SELNAME
SEL_INFO_NROWS
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 (644) error is 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 statement, TableInfo( ) function
556
MapBasic 12.0
ID
Condition
SRV_NULL_DATA
-1
SRV_TRUNCATED_DATA
-2
Example
' Application to "print" address labels
' Assumes that a relational table ADDR exists with 6 columns...
Dim hdbc, hstmt As Integer
Reference
557
558
MapBasic 12.0
Server_ColumnInfo( ) function
Purpose
Retrieves information about columns in a result set. You can call this function from the MapBasic window
in MapInfo Professional.
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 result set
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.
Attr value
ID
Server_ColumnInfo( ) returns:
SRV_COL_INFO_NAME
SRV_COL_INFO_TYPE
SRV_COL_TYPE_NONE (0)
SRV_COL_TYPE_CHAR (1)
SRV_COL_TYPE_DECIMAL (2)
SRV_COL_TYPE_INTEGER (3)
SRV_COL_TYPE_SMALLINT (4)
SRV_COL_TYPE_DATE (5)
SRV_COL_TYPE_LOGICAL (6)
SRV_COL_TYPE_FLOAT (8)
SRV_COL_TYPE_FIXED_LEN_STRING (16)
SRV_COL_TYPE_BIN_STRING (17)
Reference
559
Server_ColumnInfo( ) function
Attr value
ID
Server_ColumnInfo( ) returns:
SRV_COL_INFO_WIDTH
SRV_COL_INFO_PRECISION
SRV_COL_INFO_SCALE
SRV_COL_INFO_VALUE
Result type varies. Returns the actual data value from the
column of the current row. Long character column values
greater than 32,766 will be truncated. Binary column values are returned as a double length string of hexadecimal
characters.
SRV_COL_INFO_STATUS
SRV_COL_INFO_ALIAS
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 statement, Server Fetch statement, Server_NumCols( ) function
560
MapBasic 12.0
Server_Connect( ) function
Purpose
Establishes communications with a remote data server. You can call this function from the MapBasic
window in MapInfo Professional.
Syntax
Server_Connect( toolkit, connect_string )
toolkit is a string value identifying the remote interface, for example, "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
Reference
561
Server_Connect( ) function
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 the Server_NumDrivers( ) function and the Server_DriverInfo( ) function.
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...]
Note: There are no spaces allowed in the connection string.
Passing the DLG=1 connect option provides a connect dialog box with active help buttons.
Microsoft ACCESS Attributes
The attributes used by ACCESS are:
Attribute
Description
DSN
UID
PWD
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.
562
MapBasic 12.0
Reference
563
Server_Connect( ) function
result sets from stored procedures. When set to 1, the driver returns result sets from stored procedures.
When set to 1 and you execute a stored procedure that does not return result sets, you will incur a small
performance penalty.
SID (SID): The Oracle System Identifier that refers to the instance of Oracle running on the server.
UseCurrrentSchema (UCS): UseCurrentSchema={0 | 1}. Determines whether the driver specifies only
the current user when executing SQLProcedures. When set to 0, the driver does not specify only the
current user. When set to 1 (the initial default), the call for SQLProcedures is optimized, but only procedures owned by the user are returned.
Oracle Spatial Attributes
Oracle Spatial is an implementation of a spatial database from Oracle Corporation. It has some similarities to the previous Oracle SDO implementation, but is significantly different. Oracle Spatial maintains
the Oracle SDO implementation via a relational schema. However, MapInfo Professional does not support
the Oracle SDO relational schema via OCI. MapInfo Professional does support simultaneous connections
to Oracle through OCI and to other databases through ODBC. MapInfo Professional does not support
downloading Oracle Spatial geometry tables via ODBC using the current ODBC driver from Intersolv.
There is no DSN component.
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.
Password (PWD)
ServerName (SRVR)
An example of a connection string to access an Oracle Spatial server using TCP/IP is:
"SRVR=FATBOY;UID=SCOTT;PWD=TIGER"
SQL SERVER 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 in 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 system information. These values are not written to the system information.
The connection string has the form:
DSN=data_source_name[;attribute=value[;attribute=value]...]
An example of a connection string for SQL Server is:
DSN=Accounting;UID=JOHN;PWD=XYZZY
The paragraphs that follow give the long and short names, when applicable, 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.
564
MapBasic 12.0
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.
Reference
565
Server_Connect( ) function
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, datetime,
and time data to character data. The conversion is one way only; the driver does not recognize nonODBC 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.
566
MapBasic 12.0
Keyword
Abbreviation
Description
Nothing
Name of Server
Servername
Nothing
Port
Nothing
User Name
Username
Nothing
Password
Password
Nothing
Debug flag
Debug
B2
Fetch
A7
Socket
A8
ReadOnly
A0
CommLog
B3
Protocol
A1
Optimizer
B4
Ksqo
B5
ConnSettings
A6
UniqueIndex
Nothing
UnknownSizes
A9
Cancel as FreeStmt
CancelAsFreeStmt
C1
UseDeclareFetch
B6
Text as LongVarchar
TextAsLongVarchar
B7
Unknowns as LongVarchar
UnknownsAsLongVarchar
B8
Bools as Char
BoolsAsChar
B9
MaxVarcharSize
B0
MaxLongVarcharSize
B1
FakeOidIndex
A2
ShowOidColumn
A3
Reference
567
Server_ConnectInfo( ) function
Definition
Keyword
Abbreviation
Row Versioning
RowVersioning
A4
Show SystemTables
ShowSystemTables
A5
Parse Statements
Parse
C0
SysTable Prefixes
ExtraSysTablePrefixes
C2
Disallow Premature
DisallowPremature
C3
Updateable Cursors
UpdatableCursors
C4
LFConversion
C5
True is -1
TrueIsMinus1
C6
BI
Nothing
Byte as LongVarBinary
ByteaAsLongVarBinary
C7
UseServerSidePrepare
C8
LowerCaseIdentifier
C9
SSL mode
SSLmode
CA
Extra options
AB
Nothing
CX
Nothing
See Also:
Server Disconnect statement
Server_ConnectInfo( ) function
Purpose
Retrieves information about the active database connections. You can call this function from the MapBasic
window in MapInfo Professional.
Syntax
Server_ConnectInfo( ConnectionNo, Attr )
ConnectionNumber is the integer returned by the Server_Connect( ) function that identifies the database
connection.
Attr is a code indicating which information to return.
Return Value
String
568
MapBasic 12.0
ID
Server_ConnectInfo( ) returns:
SRV_CONNECT_INFO_DRIVER_NAME
SRV_CONNECT_INFO_DB_NAME
SRV_CONNECT_INFO_SQL_USER_ID
SRV_CONNECT_INFO_DS_NAME
SRV_CONNECT_INFO_QUOTE_CHAR
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
See Also:
Server_Connect( ) function
Reference
569
Symbol(...) ]
Linestyle Pen(...) ]
Regionstyle Pen(...) Brush(...) ]
Style Type style_number [ Column column_name ] ]
Text supports the creation of the text object for annotation text. The ALL option does not include this
text object.
connectionNumber is an integer value that identifies the specific connection.
linked_table is the name of an open, linked ODBC table.
columnname is the name of the column containing the coordinates for the specified type.
xcolumnname is the name of the X column containing longitude value of the coordinate
ycolumnname is the name of the Y column containing latitude value of the coordinate
x1, y1, x2, y2 define the coordinate system bounds.
CoordSy clause specifies the coordinate system and projection to be used.
MapBounds clause allows you to specify what to store for the entire/default table view bounds in the
MapCatalog. The default is Data which calculates the bounds of all the data in the layer. (For programs
compiled before 7.5, the default will is Coordsys).
Coordsys stores the coordinate system bounds. This is not recommended as it may cause the entire
layer default view to appear empty if the Coordsys bounds are significantly greater than the bounds of
the actual data. Most users are zoomed out too far to see their data using this option.
Values lets you specify your own bounds values for the MapCatalog.
ObjectType clause specifies the type of object in the table: points, lines, regions, text, or all objects. If
no ObjectType clause is specified, the default is Point. The Text option allows for the placement of
Oracle Spatial annotation text into a text object., and the type for this option is ORA_SP. The ALL option
does not include text.
Symbol is a valid Symbol clause to specify a point style.
Linestyle Pen is a valid Pen clause that specifies the line style to be used for a line object type.
Regionstyle Pen is a valid Pen clause and Brush is a valid Brush clause that specifies the line style
and fill style to be used for a region object type.
StyleType sets per-row symbology. style_number is a value either 0 or 1. The Column keyword and
argument must be present when style_number is set to 1 (one). When the style_number is set to zero
the Column keyword is ignored and the rendition columns in the MapCatalog are cleared.
Description
The Server Create Map statement makes a table linked to a remote database mappable. For a SpatialWare, Oracle Spatial, SQL Server Spatial or PostGIS table, you can make the table mappable for points,
lines, or regions. For all other tables, you can make a table mappable for points only. Any MapInfo Professional table may be displayed in a Browser, but only a mappable table can have graphical objects
attached to it and be displayed in a Map window.
Note: If Oracle9i is the server and the coordinate system is specified as Lat/Long without specifying
the datum, the default datum, World Geodetic System 1984(WGS 84), will be assigned to the
570
MapBasic 12.0
Description
ORA_SP columnname
OracleSpatial
SPATIALWARE
MICODE
XYINDEX
SQLSERVERSPATIAL GEOMETRY
SQLSERVERSPATIAL GEOGRAPHY
POSTGIS
Examples
Sub Main
Dim ConnNum As Integer
ConnNum = Server_Connect("ODBC",
"DSN=SQLServer;DB=QADB;UID=mipro;PWD=mipro")
Server ConnNum Create Map For "Cities"
Type SPATIALWARE
CoordSys Earth Projection 1, 0
ObjectType All
ObjectType Point
Symbol (35,0,12)
Server ConnNum Disconnect
End Sub
The following is an example of the MapBasic statement for the ANNOTEXT_TABLE:
Server 1 Create Map For """MIPRO"".""ANNOTEXT_TABLE"""
Type ORA_SP "TEXTOBJ"
CoordSys Earth Projection 12, 62, "m", 0 Bounds
(-34012036.7393, -8625248.51472) (34012036.7393, 8625248.51472)
mapbounds data
ObjectType Text
See Also:
Server Link Table statement, Unlink statement
Reference
571
572
MapBasic 12.0
Reference
573
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 MapInfo Professional, plus the three columns Key, SpatialObject, and Style columns, for a total of ten columns.
For SQL Server with SpatialWare:
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:
Create Map statement, Server Create Map statement, Server Link Table statement, Unlink statement
574
MapBasic 12.0
Reference
575
Server_DriverInfo( ) function
Server_Connect( ) function
Server_DriverInfo( ) function
Purpose
Retrieves information about the installed toolkits and data sources. You can call this function from the
MapBasic window in MapInfo Professional.
Syntax
Server_DriverInfo( DriverNo, Attr )
DriverNo is an integer value assigned to an interface toolkit by MapInfo Professional when you start
MapInfo Professional.
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.
Attr value
ID
Server_DriverInfo( ) returns:
SRV_DRV_INFO_NAME
String result, the name identifying the toolkit. ODBC indicates an ODBC data source. ORAINET indicates an Oracle
Spatial connection.
SRV_DRV_INFO_NAME_LIST
SRV_DRV_DATA_SOURCE
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 " +
576
MapBasic 12.0
Server_EOT( ) function
Purpose
Determines whether the end of the result table has been reached via a Server Fetch statement. You
can call this function from the MapBasic window in MapInfo Professional.
Syntax
Server_EOT( StatementNumber )
StatementNumber is the number of the Server Fetch statement you are checking.
Return Value
Logical
Description
The Server_EOT( ) function returns TRUE or FALSE indicating whether the previous Server 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 statement
Server_Execute( ) function
Purpose
Sends a SQL string to execute on a remote data server. You can call this function from the MapBasic
window in MapInfo Professional.
Reference
577
Server_Execute( ) function
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 Server Fetch statement and the Server Close statement, to a particular SQL statement.
You should perform a Server Close statement 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 hstmt Close
hstmt = Server_Execute ( hdbc,
"UPDATE NAME_TABLE SET name = 'Tim' ")
Server hstmt Close
Server hdbc Disconnect
See Also:
Server Close statement, Server Fetch statement
578
MapBasic 12.0
Reference
579
Server_GetODBCHConn( ) function
Error Conditions
The command Server n Fetch Into table generates an error condition if any attempts to insert records
into the local MapInfo table fail. The commands Server n Fetch [Next|Prev|recno] generate errors
if the desired record is not available.
Example 1
' An example of Server Fetch downloading into a MapInfo table
Dim hdbc, hstmt As Integer
hdbc = Server_Connect("ODBC", "DLG=1")
hstmt = Server_Execute(hdbc, "Select * from emp")
Server hstmt Fetch Into "MyEmp"
Server hstmt Close
Example 2
' An example of Server Fetch using bound variables
Dim hdbc, hstmt As Integer
dim NameVar, AddrVar as String
dim NameStatus, AddrStatus as Integer
hdbc = Server_Connect("ODBC", "DLG=1")
hstmt = Server_Execute(hdbc, "Select Name, Addr from emp")
Server hstmt Bind Column 1 to NameVar, NameStatus
Server hstmt Bind Column 2 to AddrVar, AddrStatus
Server hstmt Fetch Next
While Not Server_Eot(hstmt)
Print "Name = " + NameVar + "; Address = " + AddrVar
Server hstmt Fetch Next
Wend
See Also:
Server_ColumnInfo( ) function
Server_GetODBCHConn( ) function
Purpose
Returns the ODBC connection handle associated with the remote database connection. You can call
this function from the MapBasic window in MapInfo Professional.
Syntax
Server_GetODBCHConn( ConnectionNumber )
ConnectionNumber is the integer returned by the Server_Connect( ) function 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.
580
MapBasic 12.0
Server_GetODBCHStmt( ) function
Purpose
Return the ODBC statement handle associated with the MapBasic Server... statements. You can issue
this statement from the MapBasic window in MapInfo Professional.
Syntax
Server_GetODBCHStmt( StatementNumber )
StatementNumber is the integer returned by the Server_Execute( ) function that identifies the result
set of the SQL statement executed.
Description
This function returns the ODBC statement handle associated with the MapBasic Server... statements.
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)
Reference
581
582
MapBasic 12.0
Reference
583
Server_NumCols( ) function
This syntax will work for any database that MapInfo Professional supports. MapInfo Professional will
also execute spatial SQL queries that are created using the native SQL syntax for the spatial database.
Valid values for toolkitname can be found in Server_DriverInfo( ) function.
Examples
Declare Sub Main
Sub Main
Open table "C:\mapinfo\data\states.tab"
Server Link Table "Select * from Statecap" Using
"DSN=MS Access;DBQ=C:\MSOFFICE\ACCESS\DB1.mdb"
Into test File "C:\tmp\test"
Map From Test,States
End Sub 'Main
Declare Sub Main
Sub Main
Dim ConnNum As Integer
ConnNum = Server_Connect("ODBC","DSN=SQS;PWD=sysmal;SRVR=seneca")
Server ConnNum Link Table
"Select * from CITY_1"
Into temp
Map From temp
Server ConnNum Disconnect
End Sub
The following example creates a linked table.
Dim hdbc As Integer
hdbc = Server_Connect("ORAINET", "SRVR=ONTARIO;UID=MIPRO;PWD=MIPRO")
Server hdbc link table
"Select * From ""MIPRO"".""SMALLINTEGER"""
Toolkit "ORAINET"
Into SMALLINTEGER
Autokey ON
Map From SMALLINTEGER
See Also:
Close Table statement, Commit Table statement, Drop Table statement, Rollback statement, Save
File statement, Server Refresh statement, Unlink statement
Server_NumCols( ) function
Purpose
Retrieves the number of columns in the result set. You can call this function from the MapBasic window
in MapInfo Professional.
Syntax
Server_NumCols( StatementNumber )
StatementNumber is an integer value that identifies information about an SQL statement.
Return Value
Integer
584
MapBasic 12.0
Server_NumDrivers( ) function
Purpose
Retrieves the number of database connection toolkits currently installed for access from MapInfo. You
can call this function from the MapBasic window in MapInfo Professional.
Syntax
Server_NumDrivers( )
Return Value
Integer
Description
The Server_NumDrivers( ) function returns the number of database connection toolkits installed for
use by MapInfo Professional.
Example
Print "Number of drivers = " + Server_NumDrivers( )
See Also:
Server_DriverInfo( ) function
Reference
585
586
MapBasic 12.0
Reference
587
588
MapBasic 12.0
Reference
589
590
MapBasic 12.0
In the event of a conflict, MapInfo Professional will stop here. (This is also
the default behavior if the statement does not include an Interactive clause
or an Automatic clause.)
RevertToBase
UseCurrent
UseParent
Examples
The following example merges changes to the GWMUSA2 table where MI_PRINX=60 in MIUSER to its
parent workspace.
Server Workspace Merge
Table "GWMUSA2"
Where "MI_PRINX = 60"
Automatic UseCurrent
See Also:
Server Workspace Refresh statement
Reference
591
592
StopOnConflict
In the event of a conflict, MapInfo Professional will stop here. (This is also
the default behavior if the statement does not include an Interactive clause
or an Automatic clause.)
RevertToBase
MapBasic 12.0
UseParent
Examples
The following example refreshes MIUSER by applying changes made to GWMUSA2 where MI_PRINX=60
in its parent workspace.
Server Workspace Refresh
Table "GWMUSA2"
Where "MI_PRINX = 60"
Automatic UseParent
See Also:
Server Workspace Merge statement
SessionInfo( ) function
Purpose
Returns various pieces of information about a running session of MapInfo Professional. You can issue
this statement from the MapBasic window in 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 MapInfo Professional's session status. The attribute
can be any of the codes listed in the table below. The codes are defined in MAPBASIC.DEF.
attribute code
ID
Return Value
SESSION_INFO_COORDSYS_CLAUSE
SESSION_INFO_DISTANCE_UNITS 2
Reference
593
ID
Return Value
SESSION_INFO_AREA_UNITS
SESSION_INFO_PAPER_UNITS
Error Conditions
ERR_FCN_ARG_RANGE (644) error generated if an argument is outside of the valid range.
Example
Include "mapbasic.def"
print SessionInfo(SESSION_INFO_COORDSYS_CLAUSE)
BarType type ]
Ground Units distance_units ]
Display Units paper_units ]
BarLength paper_length ]
BarHeight paper_height ]
BarStyle [ Pen .... ] [ Brush ... ] [ Font ... ] ]
Scale [ { On | Off } ] ]
Auto [ { On | Off } ] ]
594
MapBasic 12.0
(0)
(1)
(2)
(3)
(4)
(5)
(6)
(7)
(8)
(x, y) in the Offset clause is measured from the anchor position. For example, if the win_position is
ADORNMENT_INFO_MAP_POS_TL (top left), then the x is to the right and the y is down. If the
win_position is ADORNMENT_INFO_MAP_POS_BR, then the x position is left and the y position is up.
In the center left (ADORNMENT_INFO_MAP_POS_CL) and center right (ADORNMENT_INFO_MAP_POS_CR), the y offset is ignored. In the center position (ADORNMENT_INFO_MAP_POS_CC), the offset is ignored completely (both x and y). In the top center (ADORNMENT_INFO_MAP_POS_TC) and bottom center (ADORNMENT_INFO_MAP_POS_BC) positions, the
x offset is ignored. For ADORNMENT_INFO_MAP_POS_ defines, see win_position.
win_width and win_height define the size of the adornment. MapInfo Professional ignores these parameters if this is a scale bar adornment, because scale bar adornment size is determined by scale bar
specific items, such as BarLength.
type specify one of the following codes; codes are defined in the MAPBASIC.DEF file.
SCALEBAR_INFO_BARTYPE_CHECKEDBAR
SCALEBAR_INFO_BARTYPE_SOLIDBAR
SCALEBAR_INFO_BARTYPE_LINEBAR
SCALEBAR_INFO_BARTYPE_TICKBAR
(0)
(1)
(2)
(3)
Unit Represented
"ch"
chains
"cm"
centimeters
"ft"
feet (also called International Feet; one International Foot equals exactly
30.48 cm)
"in"
inches
"km"
kilometers
Reference
595
Unit Represented
"li"
links
"m"
meters
"mi"
miles
"mm"
millimeters
"nmi"
"rd"
rods
"survey ft"
U.S. survey feet (used for 1927 State Plane coordinates; one U.S. Survey
Foot equals exactly 12/39.37 meters, or approximately 30.48006 cm)
"yd"
yards
paper_length a value in paper_units to specify how long the scale bar will be displayed. Specify the
length of the scale bar to a maximum of 34 inches or 86.3 cm on the printed map.
paper_height a value in paper_units to specify how tall the scale bar will be displayed. Specify height of
the adornment to a maximum of 44 inches or 111.76cm on the printed map.
Description
The scale bar displays as a paper_length bar in the paper_units.
Position can be Fixed relative to the mapper upper left regardless of the size of the mapper, or relative
to some anchor point on the mapper specified by win_position.
Offset is the amount the adornment will be offset from the mapper when using one of the docked
win_position.
Layout Fixed Position determines how an adornment is positioned in a layout when the adornment is
using Fixed positioning. If this is set to Geographic, then the adornment is placed on the same geographic place on the map frame in the layout as it is in the mapper. If the layout frame changes size,
then the adornment will move relative to the frame to match the geographic position. If this is set to
Frame, then the adornment will remain at a fixed position relative to the frame, as designated in the
Position clause. If the Position clause positions the adornment at (1.0, 1.0) inches, then the adornment
will be placed 1 inch to the left and one inch down from the upper left corner of the frame. Changing the
size of the frame will not change the position of the adornment. The default is Geographic.
The Background clause when used with Brush denotes the fill pattern to be used in the background
while creating or modifying a scale bar. When used with the Pen clause, this denotes the border to be
used in the background while creating or modifying a scale bar.
Brush is a valid Brush clause. Only Solid brushes are allowed. While values other than solid are allowed
as input without error, the type is always forced to solid. This clause is used only to provide the background
color for the adornment.
Pen is a valid Pen clause. Due to window clipping (the adornment is a window within the mapper), Pen
widths other than 1 may not display correctly. Also, Pen styles other than solid may not display correctly.
This clause is designed to turn on (solid) or off (hollow) and set the color of the border of the adornment.
596
MapBasic 12.0
Reference
597
598
Unit Name
Unit Represented
"acre"
acres
"hectare"
hectares
"perch"
perches
"rood"
roods
"sq ch"
square chains
"sq cm"
square centimeters
"sq ft"
square feet
"sq in"
square inches
"sq km"
square kilometers
"sq li"
square links
"sq m"
square meters
"sq mi"
square miles
MapBasic 12.0
Unit Represented
"sq mm"
square millimeters
"sq rd"
square rods
"sq yd"
square yards
Example
Set Area Units "acre"
See Also:
Area( ) function, Set Distance Units statement
Reference
599
600
MapBasic 12.0
Reference
601
602
MapBasic 12.0
Reference
603
604
MapBasic 12.0
Reference
605
606
MapBasic 12.0
Offset Clause
Offset End indicates the distance that a point location is adjusted from a street corner.
Offset Center indicates the distance that a point location is adjusted from a street center line.
Units is a String that describes the units in which Offset Center and Offset End are measured. See
Set Distance Units statement for the list of available unit names.
PassThrough Clause
PassThrough is a set of name/value pairs that are sent to the geocoder. These are pairs are geocode
service specific and are documented by the particular geocode service.
Example
The following example sets a connection to a geocoder with some match options turned on.
set connection MapMarkerHandle1 geocode match streetname, streetnumber,
municipality, municipalitysubdivision, postalcode, countrysubdivision
The following example adds a PassThrough clause to a Set Connection statement. This particular
example turns on CASS certified results in the US.
PassThrough "KEY_CASS_RULES" "true"
See Also:
Geocode statement, Open Connection statement
Reference
607
608
MapBasic 12.0
DefaultPropagationFactor determines the off-road network percentage of the remaining cost (distance)
for which off network travel is allowed when finding the maximum distance boundary. Roads not identified
in the network can be driveways or access roads, among others. The propagation factor is a percentage
of the cost used to calculate the distance between the starting point and the maximum distance. DefaultPropagationFactor is used only for Distances.
The default value for this property is 0.16.
The acceptable range is between 0.01 and 1.
Batch Size sets the number of records to send to the server to be processed at once. This may affect
performance and responsiveness. If a large request is sent it will take longer for the Isogram to be returned
and therefore longer for MapInfo Professional to respond to cancel requests and update the Progress
Bar dialog box. A lower number improves responsiveness of the command and lowers the chance of a
time-out and service failure. The default value is 2.
Example
The following example shows a Set Connection Isogram statement.
Set Connection iConnect Isogram
Banding On MajorRoadsOnly On MaxOffRoadDistance 2 Units "mi"
ReturnHoles On MajorPolygonOnly On SimplificationFactor .05
DefaultAmbientSpeed 50 Units "mi" Per "hr" DefaultPropagationFactor .2
Batch Size 2 Point On
See Also:
Create Object statement, Open Connection statement
Reference
609
610
MapBasic 12.0
Reference
611
612
MapBasic 12.0
Reference
613
614
MapBasic 12.0
Unit Represented
"ch"
chains
"cm"
centimeters
"ft"
feet (also called International Feet; one International Foot equals exactly
30.48 cm)
"in"
inches
"km"
kilometers
"li"
links
"m"
meters
"mi"
miles
"mm"
millimeters
"nmi"
"rd"
rods
"survey ft"
U.S. survey feet (used for 1927 State Plane coordinates; one U.S. Survey
Foot equals exactly 12/39.37 meters, or approximately 30.48006 cm)
"yd"
yards
Reference
615
616
MapBasic 12.0
Reference
617
The Format$( ) function uses the number formatting options set up on the user's computer.
Syntax 1 (Set Format Date) affects the output produced under the following circumstances: Calling the
StringToDate( ) function; passing a date to the Str$( ) function; or performing an operation that causes
MapBasic to perform automatic conversion between dates and strings (for example, issuing a Print
statement to print a date, or assigning a date value to a string variable).
Syntax 2 (Set Format Number) affects the output produced by the Format$( ) function and the
FormatNumber$( ) function. Applications compiled with MapBasic 3.0 or earlier default to U.S.
formatting. Applications compiled with MapBasic 4.0 or later default to "Local" formatting. To determine
618
MapBasic 12.0
Reference
619
620
MapBasic 12.0
Reference
621
622
MapBasic 12.0
Reference
623
624
MapBasic 12.0
Reference
625
626
MapBasic 12.0
range_title is a text string describing one range in a layer that is shaded by value.
Description
The Set Legend statement controls the appearance of the contents in MapInfo Professional's Theme
Legend window. To change the width, height, or position of the Legend window, use the Set Window
statement.
Between sessions, MapInfo Professional preserves theme legend settings by storing a Set Legend
statement in the workspace file. To see an example of the Set Legend statement, you could create a
Map, create a theme legend, save the workspace (for example, LEGEND.WOR), and examine the workspace in a MapBasic text editor window. You could then cut/copy and paste to put the Set Legend
statement in your MapBasic program file.
Reference
627
628
MapBasic 12.0
Reference
629
630
MapBasic 12.0
Reference
631
632
MapBasic 12.0
Reference
633
634
MapBasic 12.0
Reference
635
636
MapBasic 12.0
Reference
637
638
] [ {Left | Right } ] ]
} ]
] [ Percent Over percent ] [
max_vis )
MapBasic 12.0
Reference
639
640
MapBasic 12.0
Reference
641
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
The Object clause allows you to edit labels. For example, if you edit labels in MapInfo Professional 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.
642
MapBasic 12.0
Reference
643
Description
The display style zoom range lets you set up display style overrides that only apply within a limited range
of zoom levels. There can be multiple display style zoom ranges per layer. To have the line styles change
when zooming in on the map, set up multiple display style zoom ranges and assign a different style
override to each of them.
The layer zoom range turns off the layer altogether if you zoom in or out too far. There can only be one
of these per layer.
Arrows turns the display of direction arrows on or off.
Centroids turns the display of centroids on or off.
Nodes turns the display of nodes on or off.
Line 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.
Pen is a valid Pen clause that specifies the style used to display the borders of filled objects.
Symbol is a valid Symbol clause that specifies the style used to display point objects.
Brush is a valid Brush clause that specifies the style used to display filled objects.
Font is a valid Font clause that specifies the font used to display text objects.
Using is for a one-time copy (only the overridden properties get copied) to set the initial property value
of an layer override. The source and target layer do not maintain a connection.
Each vector layer supports more than one style override and more than one label override. Every style
override has its own zoom range that is not allowed to overlap with any other style override for the same
layer. Every label override also has its own zoom range that is not allowed to overlap any other label
override for the same layer. However, style and label overrides can share or have overlapping zoom
ranges between each other.
When an override comes into view (when the map's zoom range is within an override zoom range) then
the map styles or labels are displayed using the override properties rather than the layers base set of
style and label properties.
Style overrides do not display beyond the limits of the layer display zoom range regardless of what
bounds the style override zoom range defines. Likewise, label overrides do not display beyond the limits
644
MapBasic 12.0
Reference
645
Description
Arrows turns the display of direction arrows on or off.
Centroids turns the display of centroids on or off.
Nodes turns the display of nodes on or off.
Line 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.
Pen is a valid Pen clause that specifies the style used to display the borders of filled objects.
646
MapBasic 12.0
Reference
647
648
MapBasic 12.0
Reference
649
650
MapBasic 12.0
Reference
651
652
MapBasic 12.0
Reference
653
654
MapBasic 12.0
Reference
655
Syntax 1 (Group)
Set Map
[ Window window_id ]
[ GroupLayer group_id [ Display { On | Off } ]
[ Title "new_ friendly_name" ] ]
Syntax 2 (Ungroup)
Set Map
[ Window window_id ]
[ GroupLayer group_id
[ Ungroup [ All ] ] ]
656
MapBasic 12.0
Reference
657
Ordering Layers
The following clauses move a layer and group layer to a specific location in the layer list.
Syntax
Set Map
[ Window window_id ]
[ Order layer_id, [ , layer_id ... ] ]
[
[ GroupLayers group_layer_id [ , group_layer_id... ] ]
[ Layers layer_id [ , layer_id ] ] . . .
[ DestGroupLayer group_layer_id [ Position position ] ] ]
window_id is the integer window identifier of a Map window.
layer_id is a number identifying a map layer to modify, 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).
group_layer_id is a number identifying a group layer to modify, according to its original position in the
map.
position is 1-based index within the destination group of where to insert the list of layers being moved.
The default position is the first position in the group (position = 1).
Description
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
Set Map Order resets the order in which map layers are drawn. It moves layers, such as 3, 2, and 1 in
the following example, to the top of the layer list, removing them from whatever group they might have
been in.
Set Map Order Layers 3, 2, 1
However, using the GroupLayers and Layers clauses lets you specify moving layers and/or whole groups.
The optional DestGroupLayer specifies the group to insert the list of one or more layers and groups
into, and at what position. This clause can also be used with the older syntax to specify the exact location
to insert the layers. If missing, it means the groups and/or layers are inserted into the top level list at the
first position (as it was assumed with the old syntax). However you can specify the top level list with a
group ID = 0.
The position is the 1-based index within the destination group of where to insert the list of layers being
moved. If the position is omitted it is assumed to be the first position in the group (position = 1).
If the position given exceeds the number of items in the destination group, the new layers and/or groups
will be inserted at the end of the destination group.
Layer and group IDs may be the numeric ID or name. Group IDs range from 0 to the total number of
groups in the list.
658
MapBasic 12.0
Reference
659
660
MapBasic 12.0
Description
CoordSys clause Assigns the Map window a different coordinate system and projection. For details on
the syntax of a CoordSys clause, see CoordSys clause.
The MapBasic coordinate system must be set explicitly with a Set CoordSys statement and can be
retrieved with the SessionInfo( ) function.
Note: When a Set Map statement includes a CoordSys clause, the MapBasic application's coordinate
system is automatically set to match the map's coordinate system.
This example only alters the map's coordinate system and units; the MapBasic coordinate system is
unaffected:
Set Map XY Units "m" CoordSys Earth Projection 8,
33, "m", -55.5, 0, 0.9999, 304800, 0
Distance Type is either 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 coordinate system of the Map window is NonEarth, then the calculations will be performed
using Cartesian methods regardless of the option chosen, and if the coordinate system of the Map window
is Latitude/Longitude, then calculations will be performed using Spherical methods regardless of the
option chosen.
XY Units specifies the type of coordinate unit used to display x-, y-coordinates (for example, 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
Set
Set
Set
Map
Map
Map
Map
XY
XY
XY
XY
Units
Units
Units
Units
Reference
661
Managing Hotlinks
The hotlink settings are persisted via the Set Map statement Layer Activate clause, which supports
multiple hotlink definitions. This includes the ability to add new items, modify the attribute of existing
items, remove and reorder items. For a discussion of how MapInfo Professional supports legacy syntax,
see Exceptions to Support Backwards Compatibility.
Purpose
The purpose of Activate is to allow you to define new hotlinks. You use a hotlink to launch a file or a URL
from a Map window.
Syntax
Set Map
[ Window window_id ]
[ Layer layer_id
[ Activate LAYER_ACTIVATE_CLAUSES ] ]
Where LAYER_ACTIVATE_CLAUSES is:
Using launch_expr [ On { Labels |
[ Relative Path { On | Off } ]
[ Enable { On | Off }]
662
MapBasic 12.0
Reference
663
664
Action
Number of HotLinks
Result
One or More
Sets the first hotlink's expression to empty string. The definition is effectively disabled until the expression is set to a nonempty value.
MapBasic 12.0
Number of HotLinks
Result
Zero
Activate On Objects
One or More
Note that the same actions will apply when reading in table metadata.
Example
Set Map Layer 1 Activate Using Url1 On Objects Relative Path Off Enable
On, Using Url2 On Objects Relative Path On Enable On
Reference
665
666
MapBasic 12.0
1 Activate
Off
1 Activate
1 Activate
1 Activate
Reference
667
668
MapBasic 12.0
Reference
669
ID
WIN_STYLE_STANDARD
This code resets the style flag to its default value. If you
issue a Set Next Document Style 1 statement, but then
you change your mind and do not want to use the child
window style, issue a Set Next Document Style 0 statement to reset the style.
WIN_STYLE_CHILD
WIN_STYLE_POPUP_FULLCAPTION 2
WIN_STYLE_POPUP
Next window is created as a popup window with a halfheight title bar caption.
The parent and style settings remain in effect until you create a new window. The new window adopts
the parent and style settings you specified; then MapInfo Professional reverts to its default parent and
style settings for any subsequent windows. To re-parent more than one window, issue a separate Set
Next Document statement for each window you will create.
Note: The Create ButtonPad statement resets the parent and style settings, although the new ButtonPad is not re-parented.
This statement re-parents document windows. To re-parent dialog box windows, use the Set Application
Window statement. To re-parent 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)
670
MapBasic 12.0
"cm"
Centimeters
"in"
Inches
"mm"
Millimeters
Reference
671
"pt"
Points
"pica"
Picas
See Also:
Set Area Units statement, Set Distance Units statement
672
MapBasic 12.0
Reference
673
674
MapBasic 12.0
Reference
675
676
MapBasic 12.0
Reference
677
678
MapBasic 12.0
Reference
679
680
MapBasic 12.0
Reference
681
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
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 Layers button (in the
Layer Control window) is disabled for this table.
UserDisplayMap Off
If this table appears in a Map window, the Visible On/Off check box (in the
Layer Control window) is disabled for this table.
Example
The following statement prevents the World table from appearing in the Close Table dialog box.
Set Table World UserClose Off
See Also:
Set Datum Transform Version statement, TableInfo( ) function
682
MapBasic 12.0
Reference
683
window_id is an integer window identifier or a special window name (for example, Help).
x states the desired distance from the left of MapInfo Professional's workspace to the left edge of the
window.
y states the desired distance from the top of MapInfo Professional's workspace to the top edge of the
window.
paper_units is a string representing a paper unit name (for example, "cm" for centimeters).
The Font clause specifies a text style.
win_width is the desired width of the window.
win_height is the desired height of the window.
new_title is a string expression representing a new title for the window.
help_file is the name of a help file (for example, "FILENAME.HLP" on Windows).
context_ID is an integer help file context ID which identifies a specific help topic.
printer_name identifies a printer. The printer can be local or networked to the computer on which MapInfo
Professional is running.
Method determines whether printing will go directly to the device driver or if MapInfo Professional will
generate a Windows Enhanced Metafile first and then send the file to the printer or MapInfo will use an
Offscreen bitmap to create the output first. EMF method enables the printing of maps with raster images
that may not have printed at all in earlier versions, and that use substantially smaller spool files. Offscreen
bitmap is invoked depending upon the type of translucent content in the map and enhanced rendering
state of the window. However setting OSBM from this window means that printing will use Offscreen
bitmaps regardless of the translucency and anti alias settings.
number is the number of copies of a print job that should be sent to the printer.
HWND is an integer window handle. The window specified by HWND will become the parent of the
window specified by window_id; however, only Legend, Statistics, Info, Ruler, and Message windows
may be re-parented in this manner.
table_name is the name of an open table to use with the Info window.
record_number is an integer: specify 1 or larger to display a record in the Info window, or specify 0 to
display a "No Record" message.
Enhanced sets the version of the rendering technology used to display and print graphics.
The On parameter enables the enhanced rendering technology and is set when the user selects the
Enable Enhanced Rendering check box in the MapInfo Professional. The Off option disables the enhanced rendering technology and is set when the user does not select the Enable Enhanced Rendering
check box in MapInfo Professional.
684
MapBasic 12.0
Reference
685
686
MapBasic 12.0
ID
Description
FILTER_VERTICALLY_AND_HORIZONTALLY
FILTER_ALL_DIRECTIONS_1
FILTER_ALL_DIRECTIONS_2
FILTER_DIAGONALLY
FILTER_HORIZONTALLY
FILTER_VERTICALLY
Toolbar shows or hides the toolbar at the top of the window. This applies only to Browser windows.
For example:
Set Window windowId Toolbar Off
Description
The Set Window statement customizes an open window, setting such options as the window's size,
position, status, font, or title.
You can also use this statement to hide the toolbat at the top of the Legend Designer window.
The window_id parameter can be an integer window identifier, which you can obtain by calling the
FrontWindow( ) function and the WindowInfo( ) function. Alternately, when you use the Set Window
statement to affect a special MapInfo Professional window, such as the Statistics window, you can
identify the window by its name (for example, Statistics) or by its code (for example, 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.
Window name
Window description
MapInfo
The frame window of the entire MapInfo Professional application. You can
also refer to this window by its define: WIN_MAPINFO. (The MapInfo application window cannot be renamed).
MapBasic
The MapBasic window. You can also refer to this window by the Define code:
WIN_MAPBASIC.
Reference
687
Window description
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 MapInfo Professional 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
MapInfo Professional'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 MapInfo Professional.
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 statement. The following example disables the Close command of the active window:
Set Window FrontWindow( ) SysMenuClose Off
688
MapBasic 12.0
Reference
689
690
MapBasic 12.0
Reference
691
Sgn( ) function
The Edit DWORD value dialog box displays.
5. Type 1 in the Value data field and click OK to save your entry.
6. Close MapInfo Professional and reopen it.
This corrects the problem by writing the name of the table explicitly in the Layout. This prevents the
name change when the file changes locales.
See Also:
Browse statement, Graph statement, Layout statement, Map statement, Set Paper Units statement
Sgn( ) function
Purpose
Returns -1, 0, or 1, to indicate that a specified number is negative, zero, or positive (respectively). You
can issue this statement from the MapBasic window in MapInfo Professional.
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)
' x now has a value of -1
See Also:
Abs( ) function
Shade statement
Purpose
Creates a thematic map layer and adds it to an existing Map window. You can issue this statement from
the MapBasic window in MapInfo Professional.
692
MapBasic 12.0
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, MapInfo Professional 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 (for example, 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.
Reference
693
Shade statement
value_to_ignore is a value to be ignored; this is usually zero (when using numerical expressions) or a
blank string (when using string expressions); no thematic object will be created for a row if the row's
value matches the value to be ignored.
float_array is an array of float values initialized by a Create Ranges statement.
style_array is an array of Pen, Brush or Symbol values initialized by a Create Styles statement.
minimum is the minimum numeric value for a range.
maximum is the maximum numeric value for a range.
Description
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 (for example, "world").
Each Shade statement must specify an expr expression clause. MapInfo Professional evaluates this
expression for each object in the table being shaded; following the Shade statement, MapInfo Professional 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.
If you specify With Metadata, any theme metadata contained in the open table is used to create the Individual or Ranged Value theme.
The keywords following the expr clause dictate which type of shading MapInfo Professional will perform.
The Ranges keyword results in a shaded map where each object falls into a range of values.
The Pen clause specifies a line style (for example, MakePen(width, pattern, color)) to use for the borders
of filled objects (for example, regions).
The Line clause specifies a line style to use for lines, polylines, and arcs. The syntax of the Line clause
is identical to the Pen clause, except for the keyword Line appearing in place of Pen.
The Brush clause specifies a fill style (for example, MakeBrush(pattern, forecolor, backcolor)).
The Symbol clause specifies a symbol style (for example, MakeSymbol(shape, color, size)).
For the specific syntax of a Ranges map, see Syntax Shading by Ranges of Values.
In a Ranges map, 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 statement and the Create Styles statement. For an example of using arrays in Shade
statements, see Create Ranges statement.
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 MapInfo Professional should use to
display objects belonging to that range. If a record's expr value is greater than or equal to the minimum
694
MapBasic 12.0
Effect
Apply Color
The shading only changes the colors of objects in the map. Point objects
appear in their original shape and size, but the thematic shading controls the
point colors. Line objects appear in their original pattern and thickness, but
the thematic shading controls the line colors. Filled objects appear in their
original fill pattern, but the thematic shading controls the foreground color.
Apply Size
The shading only changes the sizes of point objects and the thickness of
linear objects. Point objects appear in their original shape and color, but the
thematic shading controls the symbol sizes. Line objects appear in their original pattern and color, but the shading controls the line thickness.
Apply All
The shading controls all display attributes: symbol shape, symbol size, line
pattern, line thickness, and color.
Reference
695
Shade statement
In this thematic map, each range appears exactly as its Symbol clause dictates: Points in the low range
appear as 9-point, yellow stars (code 35 is a star shape); points in the medium range appear as 18-point,
green stars; points in the high range appear as 27-point, blue stars.
The following example shows the same statement with the addition of a Use Size clause.
Shade WorldCap With Cap_Pop Ranges
Apply All
Use Size Symbol(34, RED, 24) ' <<<<< Note!
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, MapInfo Professional uses only the size values from the latter Symbol
clauses (9, 18, 27 point); MapInfo Professional ignores the other display attributes (for example, 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, MapInfo Professional 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).
696
MapBasic 12.0
Reference
697
Shade statement
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
Shade 1 With Proper$(Sales_Rep)
Ignore ""
Values
"Alan" ,
"Amanda" ,
"Bob" ,
"Jan"
Dot Density
Syntax
Shade [ Window window_id ]
{ layer_id | layer_name }
With expr
Density dot_value { Circle | Square }
Width dot_size
[ Color color ]
window_id is the integer window identifier of a Map window.
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.
expr is the expression by which the table will be shaded, such as a column name.
dot_value is the numeric value associated with each dot in a dot density map.
dot_size is the size, in pixels, of each dot on a dot density map.
color is the RGB value for the color of the dots in a dot density map.
Description
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 (for example, "world").
Each Shade statement must specify an expr expression clause. MapInfo Professional evaluates this
expression for each object in the table being shaded; following the Shade statement, MapInfo Professional 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 MapInfo Professional will perform.
The Density keyword creates a dot density map.
For the specific syntax of a Dot Density map, see Syntax Dot Density.
698
MapBasic 12.0
Graduated Symbols
Syntax
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" } ]
window_id is the integer window identifier of a Map window.
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.
expr is the expression by which the table will be shaded, such as a column name.
max_value is a number,
min_value is a number,
symbol_size is the point size to use for symbols having the appropriate value.
Reference
699
Shade statement
Description
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 (for example, "world").
Each Shade statement must specify an expr expression clause. MapInfo Professional evaluates this
expression for each object in the table being shaded; following the Shade statement, MapInfo Professional 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 MapInfo Professional will perform.
The Graduated keyword results in a graduated symbols map.
For the specific syntax of a Graduated map, see Syntax Graduated Symbols.
In a Graduated map, the keyword Graduated is followed by a pair of value:symbol_size clauses. The
first of the value:symbol_size clauses specifies what size symbol corresponds to the minimum value,
and the second of the value:symbol_size clauses specifies what size symbol corresponds to the maximum
value. MapInfo Professional uses intermediate symbol sizes for rows having values between the extremes.
A Symbol clause dictates what type of symbol should appear (circle, star, etc.). If you include the optional Inflect clause, which specifies a second Symbol style, MapInfo Professional uses the secondary
symbol style to draw symbols for rows having negative values.
The following example creates a graduated symbols map showing profits and losses. Stores showing a
profit are represented as green triangles, pointing up. The Shade statement also includes an Inflection
clause, so that stores showing a net loss appear as red triangles, pointing down.
Shade stores With Net_Profit
Graduated
0.0:0 15000:24
Symbol(36, GREEN, 24)
Inflect Symbol(37, RED, 24)
Vary Size By "SQRT"
The optional Vary Size By clause controls how differences in numerical values correspond to differences
in symbol sizes. If you omit the Vary Size By clause, MapInfo Professional varies the symbol size using
the "SQRT" (square root) method, which assigns increasingly larger point sizes as the square roots of
the values increase. When you vary by square root, each symbol's area is proportionate to the row's
value; thus, if one row has a value twice as large as another row, the row with the larger value will have
a symbol that occupies twice as much area on the map.
Note: Having twice the area is not the same as having twice the point size. When you double an object's
point size, its area quadruples, because you are increasing both height and width.
700
MapBasic 12.0
Pie Charts
Syntax
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... ] ]
window_id is the integer window identifier of a Map window.
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.
expr is the expression by which the table will be shaded, such as a column name.
angle is the starting angle, in degrees, of the first wedge in a pie chart.
chart_size is a float size, representing the maximum height of each pie or bar chart.
unitname is a paper unit name (for example, "in" for inches, "cm" for centimeters).
max_value is a number, used in the At Value clause to control the heights of Pie and Bar charts. For
each record, if the sum of the column expressions equals the max_value, that record's Pie or Bar chart
will be drawn at the chart_size height; the charts are smaller for rows with smaller sums.
Description
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 (for example, "world").
Each Shade statement must specify an expr expression clause. MapInfo Professional evaluates this
expression for each object in the table being shaded; following the Shade statement, MapInfo Professional 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 MapInfo Professional will perform.
The Pie keyword specify thematically constructed charts.
The Pen clause specifies a line style (for example, MakePen(width, pattern, color)) to use for the borders
of filled objects (for example, regions).
The Brush clause specifies a fill style (for example, MakeBrush(pattern, forecolor, backcolor)).
For the specific syntax of a Pie map, see Syntax Pie Charts.
Reference
701
Shade statement
In a Pie map, MapInfo Professional creates a small pie chart for each map object to be shaded. The
With clause specifies a comma-separated list of two or more expressions to comprise each thematic
pie.
If you place the optional keyword Half before the keyword Pie, MapInfo Professional draws half-pies;
otherwise, MapInfo Professional draws whole pies.
The optional Angle clause specifies the starting angle of the first pie wedge, specified in degrees. The
default start angle is 180.
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 (for example, "in" for
inches). For details about paper units, see Set Paper Units statement. 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 MapInfo Professional 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,
MapInfo Professional 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 Charts
Syntax
Shade [ Window window_id ]
{ layer_id | layer_name | Selection }
With expr [ , expr... ]
702
MapBasic 12.0
Reference
703
Sin( ) function
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 (for example, half an inch tall) regardless
of the numeric values for that map object. If you omit the Fixed keyword, MapInfo Professional 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 statement, Create Styles statement, Map statement, Set Legend statement, Set
Map statement, Set Shade statement
Sin( ) function
Purpose
Returns the sine of a number. You can call this function from the MapBasic window in MapInfo Professional.
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 negative 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.
704
MapBasic 12.0
Space$( ) function
Purpose
Returns a string consisting only of spaces. You can call this function from the MapBasic window in
MapInfo Professional.
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$( ) function
SphericalArea( ) function
Purpose
Returns the area using as calculated in a Latitude/Longitude non-projected coordinate system using
great circle based algorithms. You can call this function from the MapBasic window in MapInfo Professional.
Reference
705
SphericalConnectObjects( ) function
Syntax
SphericalArea( obj_expr, unit_name )
obj_expr is an object expression.
unit_name is a string representing the name of an area unit (for example, "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 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 nonprojected coordinate system using spherical algorithms. A value of -1 will be returned for data that is in
a NonEarth coordinate system since this data cannot 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 Select statement, as shown in the following
example.
Select state, SphericalArea(obj, "sq km")
From states Into results
See Also:
CartesianArea( ) function, SphericalArea( ) function
SphericalConnectObjects( ) function
Purpose
Returns an object representing the shortest or longest distance between two objects. You can call this
function from the MapBasic window in MapInfo Professional.
706
MapBasic 12.0
SphericalDistance( ) function
Purpose
Returns the distance between two locations. You can call this function from the MapBasic window in
MapInfo Professional. You can call this function from the MapBasic window in MapInfo Professional.
Syntax
SphericalDistance( x1, y1, x2, y2, unit_name )
x1 and x2 are x-coordinates (for example, longitude).
y1 and y2 are y-coordinates (for example, latitude).
unit_name is a string representing the name of a distance unit (for example,"km").
Return Value
Float
Description
The SphericalDistance( ) function calculates the distance between two locations.
Reference
707
SphericalObjectDistance( ) function
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 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 Latitude/Longitude 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 nonprojected 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 cannot 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:
CartesianDistance( ) function, Distance( ) function
SphericalObjectDistance( ) function
Purpose
Returns the distance between two objects. You can call this function from the MapBasic window in
MapInfo Professional.
Syntax
SphericalObjectDistance( object1, object2, unit_name )
object1 and object2 are object expressions.
unit_name is a string representing the name of a distance unit.
Return Value
Float
Description
SphericalObjectDistance( ) returns the minimum distance between object1 and object2 using a
spherical calculation method with the return value in unit_name. If the calculation cannot be done using
a spherical distance method (e.g., if the MapBasic coordinate system is NonEarth), then this function
will produce an error.
708
MapBasic 12.0
SphericalObjectLen( ) function
Purpose
Returns the geographic length of a line or polyline object. You can call this function from the MapBasic
window in MapInfo Professional.
Syntax
SphericalObjectLen( obj_expr, unit_name )
obj_expr is an object expression.
unit_name is a string representing the name of a distance unit (for example, "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 nonprojected coordinate system using spherical algorithms. A value of -1 will be returned for data that is in
a NonEarth coordinate system since this data cannot 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 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 Also:
CartesianObjectLen( ) function, SphericalObjectLen( ) function
SphericalOffset( ) function
Purpose
Returns a copy of the input object offset by the specified distance and angle using a spherical DistanceType. You can call this function from the MapBasic window in MapInfo Professional.
Reference
709
SphericalOffsetXY( ) function
Syntax
SphericalOffset( object, angle, distance, units )
object is the object being offset.
angle is the angle to offset the object.
distance is the distance to offset the object.
units is a string representing the unit in which to measure distance.
Return Value
Object
Description
This function produces a new object that is a copy of the input object offset by distance along angle (in
degrees with horizontal in the positive X-axis being 0 and positive being counterclockwise). The unit
string, similar to that used for the ObjectLen( ) function or the Perimeter( ) function, is the unit for the
distance value. The DistanceType used is Spherical. If the coordinate system of the input object is
NonEarth, an error will occur, since Spherical DistanceTypes are not valid for NonEarth. This is signified
by returning a NULL object. The coordinate system used is the coordinate system of the input object.
There are some considerations for Spherical measurements that do not hold for Cartesian measurements.
If you move an object that is in Latitude/Longitude, the shape of the object remains the same, but the
area of the object will change. This is because you are picking one offset delta in degrees, and the actual
measured distance for a degree is different at different locations.
For the Offset functions, the actual offset delta is calculated at some fixed point on the object (for example,
the center of the bounding box), and then that value is converted from the input units into the coordinate
system's units. If the coordinate system is Latitude/Longitude, the conversion to degrees uses the fixed
point. The actual converted distance measurement could vary at different locations on the object. The
distance from the input object and the new offset object is only guaranteed to be exact at the single fixed
point used.
Example
SphericalOffset(Rect, 45, 100, "mi")
See Also:
SphericalOffsetXY( ) function
SphericalOffsetXY( ) function
Purpose
Returns a copy of the input object offset by the specified x- and -offset values using a Spherical DistanceType. You can call this function from the MapBasic window in MapInfo Professional.
Syntax
SphericalOffsetXY( object, xoffset, yoffset, units )
710
MapBasic 12.0
SphericalPerimeter( ) function
Purpose
Returns the perimeter of a graphical object. You can call this function from the MapBasic window in
MapInfo Professional.
Syntax
SphericalPerimeter( obj_expr, unit_name )
obj_expr is an object expression.
unit_name is a string representing the name of a distance unit (for example, "km").
Reference
711
Sqr( ) function
Return Value
Float
Description
The SphericalPerimeter( ) function calculates the perimeter of the obj_expr object. The SphericalPerimeter( ) 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 Set Distance Units statement
for the list of valid unit names.
The SphericalPerimeter( ) function always returns a value as calculated in a Latitude/Longitude nonprojected coordinate system using spherical algorithms. A value of -1 will be returned for data that is in
a NonEarth coordinate system since this data cannot 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 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( ) function, Perimeter( ) function
Sqr( ) function
Purpose
Returns the square root of a number. You can call this function from the MapBasic window in MapInfo
Professional.
712
MapBasic 12.0
StatusBar statement
Purpose
Displays or hides the status bar, or displays a brief message on it. You can issue this statement from
the MapBasic window in MapInfo Professional.
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..."
Reference
713
Stop statement
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
parameter is set to On, 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 On, the user will be able to select the editable layer from the
status bar.
See Also:
Note statement, Print statement
Stop statement
Purpose
Suspends a running MapBasic application, for debugging purposes. You can issue this statement from
the MapBasic window in MapInfo Professional.
Syntax
Stop
Restrictions
You cannot issue a Stop statement from within a user-defined function or within a dialog box's handler
procedure; therefore you cannot issue a Stop statement to debug a Dialog statement while the dialog
box 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, MapInfo Professional displays a list of the global variables in use.
714
MapBasic 12.0
Str$( ) function
Purpose
Returns a string representing an expression (for example, a printout of a number). You can call this
function from the MapBasic window in MapInfo Professional.
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 expression is a negative number, the first character in the returned string is the minus sign (-). If 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 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 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.
Reference
715
String$( ) function
If 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 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$( ) function, FormatNumber$( ) function, Set Format statement, Val( ) function
String$( ) function
Purpose
Returns a string built by repeating a specified character some number of times. You can call this function
from the MapBasic window in MapInfo Professional.
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:
716
MapBasic 12.0
StringCompare( ) function
Purpose
Performs case-sensitive string comparisons. You can call this function from the MapBasic window in
MapInfo Professional.
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.
Return value:
When:
-1
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( ) function, StringCompareIntl( ) function
StringCompareIntl( ) function
Purpose
Performs language-sensitive string comparisons. You can call this function from the MapBasic window
in MapInfo Professional.
Reference
717
StringToDate( ) function
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 (for example, 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.
Return value:
When:
-1
first string precedes the second string, using the current language setting
first string follows the second string, using the current language setting
See Also:
Like( ) function, StringCompare( ) function
StringToDate( ) function
Purpose
Returns a Date value, given a string. You can call this function from the MapBasic window in MapInfo
Professional.
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 (for example, Day/Month/Year) or a different
718
MapBasic 12.0
StringToDateTime( ) function
Purpose
Returns a DateTime value given a string that represents a date and time. MapBasic interprets the
date/time string according to the date and time-formatting options that are set up on the user's computer.
At least one space must be between the date and time. See StringToDate( ) function and StringToTime(
) function for details. You can call this function from the MapBasic window in MapInfo Professional.
Syntax
StringToDateTime( String )
Reference
719
StringToTime( ) function
Return Value
DateTime, which is an integer value DateTime in nine bytes: 4 bytes for date, 5 bytes for time. Five bytes
for time include: 2 for millisec, 1 for sec, 1 for min, 1 for hour.
Example
Copy this example into the MapBasic window for a demonstration of this function. Note that this is using
a United States date example that uses colons to separate year, month, day, hour, minutes, and seconds.
dim strX as string
dim Z as datetime
strX = "1999:09:25:12:32:45"
Z = StringtoDateTime(strX)
Print FormatDate$(Z)
Print FormatTime$(Z,"hh:mm:ss.fff tt")
See Also:
NumberToDateTime( ) function, Set Format statement, Str$( ) function, StringToDate( ) function,
StringToTime( ) function
StringToTime( ) function
Purpose
Returns a Time value given a string that represents a time. MapBasic interprets the time string according
to the time-formatting options that are set up on the user's computer. However, either 12 or 24-hour time
representations are accepted. In addition, the less significant components of a time may be omitted. In
other words, the hour must be specified, but the minutes, seconds, and milliseconds are optional. You
can call this function from the MapBasic window in MapInfo Professional.
Syntax
StringToTime( String )
Return Value
Time
Example
Copy this example into the MapBasic window for a demonstration of this function. Note that this is using
a United States date example that uses colons to separate hour, minutes, and seconds.
dim strY as string
dim X as time
strY = "12:32:45"
X = StringtoTime(strY)
Print FormatTime$ (X,"hh:mm:ss.fff tt")
See Also:
NumberToDateTime( ) function, NumberToTime( ) function, Set Format statement, Str$( ) function,
StringToTime( ) function
720
MapBasic 12.0
StyleAttr( ) function
Purpose
Returns one attribute of a Pen, Brush, Font, or Symbol style. You can call this function from the MapBasic
window in MapInfo Professional.
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 (for example,
PEN_WIDTH) are defined in MAPBASIC.DEF.
Brush settings:
attribute setting
ID
StyleAttr( ) returns:
BRUSH_PATTERN
BRUSH_FORECOLOR
BRUSH_BACKCOLOR
attribute setting
ID
StyleAttr( ) returns:
FONT_NAME
FONT_STYLE
Font settings:
Reference
721
StyleAttr( ) function
attribute setting
ID
StyleAttr( ) returns:
FONT_POINTSIZE
FONT_FORECOLOR
FONT_BACKCOLOR
attribute setting
ID
StyleAttr( ) returns:
PEN_WIDTH
PEN_PATTERN
PEN_COLOR
PEN_INDEX
PEN_INTERLEAVED
attribute setting
ID
StyleAttr( ) returns:
SYMBOL_CODE
SYMBOL_COLOR
SYMBOL_POINTSIZE
SYMBOL_ANGLE
SYMBOL_FONT_NAME
Pen settings:
Symbol settings:
722
MapBasic 12.0
ID
StyleAttr( ) returns:
SYMBOL_FONT_STYLE
Integer, indicating the style attributes of a TrueType symbol (0 = plain, 1 = Bold, etc.). See Symbol clause for a
listing of possible values.
SYMBOL_KIND
SYMBOL_CUSTOM_NAME
SYMBOL_CUSTOM_STYLE
Error Conditions
ERR_FCN_ARG_RANGE (644) error is 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:
Brush clause, Font clause, Pen clause, Symbol clause, MakeBrush( ) function, MakeFont( )
function, MakePen( ) function, MakeSymbol( ) function
StyleOverrideInfo( ) function
Returns information about a specific display style override.
Syntax
StyleOverrideInfo( window_id, layer_number, override_index, attribute )
window_id is the integer window identifier of a Map window.
layer_number is the number of a layer in the current Map window (for example, 1 for the top layer); to
determine the number of layers in a Map window, call the MapperInfo( ) function.
override_index is an integer index (1-based) for the override definition within the layer.
attribute is a code indicating the type of information to return; see table below.
Return Value
Return value depends on attribute parameter.
Reference
723
StyleOverrideInfo( ) function
Description
This function returns information about the specified display style override for one layer in an existing
Map window. The layer_number must be a valid 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.
Attribute Code
ID
STYLE_OVR_INFO_NAME
STYLE_OVR_INFO_VISIBILITY
STYLE_OVR_INFO_ZOOM_MIN
STYLE_OVR_INFO_ZOOM_MAX
STYLE_OVR_INFO_ARROWS
STYLE_OVR_INFO_NODES
STYLE_OVR_INFO_CENTROIDS
STYLE_OVR_INFO_ALPHA
SmallInt value, representing the alpha factor for the specified override.
0=fully transparent.
255=fully opaque.
STYLE_OVR_INFO_TRANSLUCENCY
STYLE_OVR _INFO_LINE
724
10
MapBasic 12.0
ID
STYLE_OVR _INFO_PEN
11
STYLE_OVR_INFO_BRUSH
12
STYLE_OVR_INFO_SYMBOL
13
STYLE_OVR_INFO_FONT
14
STYLE_OVR_INFO_SYMBOL_COUNT
15
STYLE_OVR_INFO_LINE_COUNT
16
STYLE_OVR_INFO_PEN_COUNT
17
STYLE_OVR_INFO_BRUSH_COUNT 18
STYLE_OVR_INFO_FONT_COUNT 19
Example
StyleOverrideInfo(nMID, nLayer, nOverride, STYLE_OVR_INFO_PEN_COUNT)
See Also:
LabelOverrideInfo( ) function, LayerStyleInfo( ) function, Set Map statement, LayerInfo( ) function
Reference
725
726
MapBasic 12.0
Symbol clause
Purpose
Specifies a symbol style for point objects. You can use this clause in the MapBasic window in MapInfo
Professional.
Reference
727
Symbol clause
Example
The following example shows how a Set Map statement can incorporate a Symbol clause. Set Map
statement below specifies that symbol objects in the mapper's first layer should be displayed using
symbol 34 (a filled circle), filled in red, at a size of eighteen points.
Include "mapbasic.def"
Set Map
Layer 1 Display Global
Global Symbol MakeSymbol(34,RED,18)
728
MapBasic 12.0
Symbol Style
Plain
Bold
16
32
Drop Shadow
256
To specify two or more style attributes, add the values from the left column. For example, to specify both
the Bold and the Drop Shadow attributes, use a fontstyle value of 33. Styles 16 and 256 are mutually
exclusive.
Symbol Style
The Show Background, the Apply Color, and the Display at Actual Size settings are off; the symbol appears in its default state at the point size specified
by the size parameter. White pixels in the bitmap are displayed as transparent,
allowing whatever is behind the symbol to show through.
The Show Background setting is on; white pixels in the bitmap are opaque.
The Apply Color setting is on; non-white pixels in the bitmap are replaced
with the symbol's color setting.
Reference
729
SystemInfo( ) function
customstyle value
Symbol Style
The Display at Actual Size setting is on; the bitmap image is rendered at its
native width and height in pixels.
The Show Background and Display at Actual Size settings are on.
The Show Background, the Apply Color, and the Display at Actual Size settings are on.
Symbol Expression
Syntax
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, for example, MakeSymbol(shape, color, size).
See Also:
MakeCustomSymbol( ) function, MakeFontSymbol( ) function, MakeSymbol( ) function, StyleAttr(
) function
SystemInfo( ) function
Purpose
Returns information about the operating system or software version. You can call this function from the
MapBasic window in MapInfo Professional.
Syntax
SystemInfo( attribute )
attribute is an integer code indicating which system attribute to query.
Note: The MAPBASIC.DEF constant for this function is 18.
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
730
MapBasic 12.0
ID
SYS_INFO_PLATFORM
SYS_INFO_APPVERSION
Integer value: the version number with which the application was compiled, multiplied by 100.
SYS_INFO_MIVERSION
Integer value, indicating the version of MapInfo Professional that is currently running, multiplied by 100.
SYS_INFO_RUNTIME
SYS_INFO_CHARSET
SYS_INFO_COPYPROTECTED
Logical value: TRUE means the user is running a copyprotected version of MapInfo Professional.
SYS_INFO_APPLICATIONWND
SYS_INFO_DDESTATUS
SYS_INFO_MAPINFOWND
SYS_INFO_NUMBER_FORMAT
10
SYS_INFO_DATE_FORMAT
11
SYS_INFO_DIG_INSTALLED
12
SYS_INFO_DIG_MODE
13
SYS_INFO_MIPLATFORM
14
SYS_INFO_MDICLIENTWND
15
SYS_INFO_PRODUCTLEVEL
16
Reference
731
TableInfo( ) function
attribute code
ID
SYS_INFO_APPIDISPATCH
(value=17)
17
SYS_INFO_MIBUILD_NUMBER)
18
SYS_INFO_MIFULLVERSION
19
Integer value, representing the full version number, including minor and maintenance versions, of the currently
running MapInfo Professional. This value represents the
version string without decimal points.
SystemInfo(SYS_INFO_MIFULLVERSION) returns 1103
for version 11.0.3. This is more detail than using SystemInfo(SYS_INFO_MIVERSION), which returns 1100
for MapInfo Professional 11.0 and 11.0.3.
Error Conditions
ERR_FCN_ARG_RANGE (644) error is 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
If SystemInfo(SYS_INFO_PLATFORM) = PLATFORM_WIN Then
Call DDE_Setup
End If
TableInfo( ) function
Purpose
Returns information about an open table. Has a define for FME (Universal Data) tables. You can call
this function from the MapBasic window in MapInfo Professional.
732
MapBasic 12.0
ID
TableInfo( ) returns
TAB_INFO_NAME
TAB_INFO_NUM
TAB_INFO_TYPE
Reference
733
TableInfo( ) function
attribute code
ID
TableInfo( ) returns
TAB_TYPE_WFS (7)
if table is from a Web Feature Service
TAB_TYPE_FME (8)
if table is opened through FME
TAB_TYPE_TILESERVER (9)
if table is a raster image from a Tile Server
734
TAB_INFO_NCOLS
TAB_INFO_MAPPABLE
TAB_INFO_READONLY
TAB_INFO_TEMP
TAB_INFO_NROWS
TAB_INFO_EDITED
TAB_INFO_FASTEDIT
10
TAB_INFO_UNDO
11
TAB_INFO_MAPPABLE_TABLE
12
TAB_INFO_USERMAP
13
TAB_INFO_USERBROWSE
14
TAB_INFO_USERCLOSE
15
TAB_INFO_USEREDITABLE
16
TAB_INFO_USERREMOVEMAP
17
MapBasic 12.0
ID
TableInfo( ) returns
TAB_INFO_USERDISPLAYMAP
18
TAB_INFO_TABFILE
19
TAB_INFO_MINX,
20
TAB_INFO_MINY,
21
TAB_INFO_MAXX,
22
TAB_INFO_MAXY
23
TAB_INFO_SEAMLESS
24
TAB_INFO_COORDSYS_MINX,
25
TAB_INFO_COORDSYS_MINY,
26
TAB_INFO_COORDSYS_MAXX,
27
TAB_INFO_COORDSYS_MAXY
28
TAB_INFO_COORDSYS_CLAUSE
29
TAB_INFO_COORDSYS_NAME
30
TAB_INFO_NREFS
31
TAB_INFO_SUPPORT_MZ
32
TAB_INFO_Z_UNIT_SET
33
TAB_INFO_Z_UNIT
34
TAB_INFO_BROWSER_LIST
35
Reference
Float results, indicating the minimum and maximum xand y-coordinates of all objects in the table.
735
TableInfo( ) function
attribute code
ID
TableInfo( ) returns
TAB_INFO_THEME_METADATA
36
TAB_INFO_COORD37
SYS_CLAUSE_WITHOUT_BOUNDS
TAB_INFO_DESCRIPTION
38
TAB_INFO_TABLEID
39
TAB_INFO_PARENTTABLEID
40
String result: returns the table ID from which this TAB file
was copied. If this was not created from another TAB file,
then it returns an empty string.
TAB_INFO_ISMANAGED
41
TAB_INFO_ADSK_TEXTOBJECT
42
TAB_INFO_OVERRIDE_COORDIN- 43
ATE_ORDER
TAB_INFO_PERSIST
44
Error Conditions
ERR_TABLE_NOT_FOUND (405) error is generated if the specified table was not available.
ERR_FCN_ARG_RANGE (644) error is generated if an argument is outside of the valid range.
Examples
Include "mapbasic.def"
Dim i_numcols As SmallInt, L_mappable As Logical
Open Table "world"
736
MapBasic 12.0
TableListInfo( ) function
Purpose
Returns information about the Table List window.
Syntax
TableListInfo( attribute )
attribute is a code indicating the type of information to return; see table below.
Description
The TableListInfo( ) function returns one piece of information about the Table List window.
The attribute parameter is a value from the table below. Codes in the left column are defined in MAPBASIC.DEF.
attribute code
ID
TableInfo( ) returns
TL_INFO_SEL_COUNT
Examples
TableListInfo(TL_INFO_SEL_COUNT)
The following example uses this function in conjunction with a custom item on the Table List shortcut
menu.
include "mapbasic.def"
include "menu.def"
declare sub main
declare sub ShowTABPaths
'================================================================
sub main
' Add new item to Table List context menu
alter menu ID M_SHORTCUT_TLV_TABLES add
"Show TAB path..." calling ShowTABPaths
end sub
'================================================================
sub ShowTABPaths()
' Get the number of selected items
Reference
737
TableListSelectionInfo( ) function
dim selCount as integer
selCount = TableListInfo(TL_INFO_SEL_COUNT)
' Print the table name and TAB file location fo all selected items
dim index as integer
for index = 1 to selCount
' Get the table id
dim tableId as integer
tableId = TableListSelectionInfo(index, TL_SEL_INFO_ID)
' Use the table in call to get the TAB path
dim tablePath as string
tablePath = TableInfo(tableId, TAB_INFO_TABFILE)
' Print the info
print tableName + " - " + tablePath
next
end sub
See Also:
TableListSelectionInfo( ) function
TableListSelectionInfo( ) function
Purpose
Returns information about a selected item in the Table List window.
Syntax
TableListSelectionInfo( selection_index, attribute )
selection_id is the index of a selected item in Table List.
attribute is a code indicating the type of information to return; see table below.
Description
The attribute parameter can be any value from the table below. Codes in the left column are defined in
MAPBASIC.DEF.
attribute code
ID
TableInfo( ) returns
TL_SEL_INFO_NAME
TL_SEL_INFO_ID
Example
TableListSelectionInfo(index, TL_SEL_INFO_ID)
See Also:
TableListInfo( ) function
738
MapBasic 12.0
Tan( ) function
Purpose
Returns the tangent of a number. You can call this function from the MapBasic window in MapInfo
Professional.
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 (0.01745329252). To convert
a radian value into degrees, multiply that value by RAD_2_DEG (57.29577951). (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
y
'
'
= 45 * DEG_2_RAD
= Tan(x)
y will now be equal to 1,
since the tangent of 45 degrees is 1
See Also:
Acos( ) function, Asin( ) function, Atn( ) function, Cos( ) function, Sin( ) function
TempFileName$( ) function
Purpose
Returns a name that can be used when creating a temporary file. You can call this function from the
MapBasic window in MapInfo Professional.
Syntax
TempFileName$( dir )
Reference
739
740
MapBasic 12.0
TextSize( ) function
Purpose
Returns the point size of a text object in a window. You can call this function from the MapBasic window
in MapInfo Professional.
Syntax
TextSize( window_id, text_obj )
window_id is the integer window identifier of a Map or Layout window. Call the FrontWindow( ) function
or the WindowID( ) function 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 clause
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. You can call this function from the MapBasic window in MapInfo Professional.
Note: This function is equivalent to calling FormatTime$(CurTime()). So print Time("hh:mm:ss") is the
same as FormatTime$(CurTime(), "hh:mm:ss").
Reference
741
Timer( ) function
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.
See also:
FormatTime$( ) function, GetTime() function
Timer( ) function
Purpose
Returns the number of elapsed seconds. You can call this function from the MapBasic window in MapInfo
Professional.
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
Dim start, elapsed As Integer
start = Timer( )
Call Ubi
elapsed = Timer( ) - start
'
' elapsed now contains the number of seconds
' that it took to execute the procedure Ubi
'
742
MapBasic 12.0
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 statement and Create ButtonPad statement 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, the CommandInfo( ) function returns the row and column where the user
clicked. If the user clicked in a Map, the CommandInfo( ) function returns the map coordinates of the
location where the user clicked; these coordinates are in MapBasic's current coordinate system (see
Set CoordSys statement).
If the user clicked in a Layout window, the CommandInfo( ) function returns the layout coordinates (for
example, distance from the upper left corner of the page) where the user clicked; these coordinates are
in MapBasic's current paper units (see Set Paper Units statement).
By calling the CommandInfo( ) function, you can also detect whether the user held down the Shift key
and/or the Ctrl 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 namesuch as ToolHandlerthe 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
Reference
743
TriggerControl( ) function
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. That is, a program which executes an End Program statement is no longer
sleeping-it is terminated altogether. So, 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( ) function
TriggerControl( ) function
Purpose
Returns the ID of the last dialog control chosen by the user. You can call this function from the MapBasic
window in MapInfo Professional.
Syntax
TriggerControl( )
Return Value
Integer
744
MapBasic 12.0
TrueFileName$( ) function
Purpose
Returns a full file specification, given a partial specification. You can call this function from the MapBasic
window in MapInfo Professional.
Syntax
TrueFileName$( file_spec )
file_spec is a string representing a partial file specification (for example, "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:
Reference
745
Type statement
ProgramDirectory$( ) function
Type statement
Purpose
Defines a custom variable type which can be used in later Dim statements 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 (for example, 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
Dim sales_mgr, sales_people(10) As Person
sales_mgr.fullname = "Otto Carto"
sales_people(1).fullname = "Melinda Robertson"
See Also:
Dim statement, Global statement, ReDim statement
746
MapBasic 12.0
UBound( ) function
Purpose
Returns the current size of an array. You can call this function from the MapBasic window in MapInfo
Professional.
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 statement 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 statement, Global statement, ReDim statement
UCase$( ) function
Purpose
Returns a string, converted to upper-case. You can call this function from the MapBasic window in
MapInfo Professional.
Syntax
UCase$( string_expr )
Reference
747
UnDim statement
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
regular = "Los Angeles"
upper_case = UCase$(regular)
' upper_case now contains the value "LOS ANGELES"
See Also:
LCase$( ) function, Proper$( ) function
UnDim statement
Purpose
Undefines a variable. You can issue this statement from the MapBasic window in MapInfo Professional.
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
748
MapBasic 12.0
UnitAbbr$( ) function
Purpose
Returns a string representing the abbreviated version of a standard MapInfo Professional unit name.
You can call this function from the MapBasic window in MapInfo Professional.
Syntax
UnitAbbr$( unit_name )
unit_name is a string representing a standard MapInfo Professional unit name (for example, "km").
Return Value
String expression, representing an abbreviated unit name (for example, "km")
Description
The unit_name parameter must be one of MapInfo Professional'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 MapInfo Professional or a
translated version. For example, if a user is running the German-language version of MapInfo Professional, the following function call returns the German translation of "sq km":
UnitAbbr$("sq km")
The UnitAbbr$( ) function can operate on units of distance, area, paper, and time. For a listing of MapInfo
Professional's standard distance unit names (for example, "km"), see Set Distance Units statement.
For a listing of area unit names (for example, "sq km"), see Set Area Units statement. For a listing of
paper unit names (for example, "in" for inches on a page layout), see Set Paper Units statement. Time
unit names include seconds ("sec"), minutes ("min"), and hours ("hr").
The unit_name parameter can also be "degree" (in which case, UnitAbbr$( ) returns "deg").
See Also:
Set Area Units statement, Set Distance Units statement, Set Paper Units statement, UnitName$(
) function
Reference
749
UnitName$( ) function
UnitName$( ) function
Purpose
Returns a string representing the full version of a standard MapInfo Professional unit name. You can
call this function from the MapBasic window in MapInfo Professional.
Syntax
UnitName$( unit_name )
unit_name is a string representing a standard MapInfo Professional unit name (for example, "km")
Return Value
String expression, representing a full unit name (for example, "kilometers")
Description
The unit_name parameter must be one of MapInfo Professional'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 MapInfo Professional or a translated version. For example, if a user is running the French-language version of MapInfo
Professional, the following function call returns the French translation of "square kilometers":
UnitName$("sq km")
The UnitName$( ) function can operate on units of distance, area, paper, and time. For a listing of
MapInfo Professional's standard distance unit names (for example, "km"), see Set Distance Units
statement. For a listing of area unit names (for example, "sq km"), see Set Area Units statement. For
a listing of paper unit names (for example, "in" for inches on a page layout), see Set Paper Units
statement. Time unit names include seconds ("sec"), minutes ("min"), and hours ("hr").
The unit_name parameter can also be "degree" (in which case, UnitName$( ) returns "degrees").
See Also:
Set Area Units statement, Set Distance Units statement, Set Paper Units statement, UnitAbbr$(
) function
Unlink statement
Purpose
Unlinks a table which was downloaded and linked from a remote database with the Server Link Table
statement. You can issue this statement from the MapBasic window in MapInfo Professional.
Syntax
Unlink TableName
750
MapBasic 12.0
Update statement
Purpose
Modifies one or more rows in a table. You can issue this statement from the MapBasic window in MapInfo
Professional.
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
Reference
751
752
MapBasic 12.0
URL clause
Purpose
Specifies the library service URL. You can use this clause in the MapBasic window in MapInfo Professional.
Syntax
URL url
url is a valid Library Service URL.
Description
The URL clause specifies the default Library Service URL to use. It checks that the input is a valid Library
Service URL, and displays an error message if it is not valid.
The default Library service URL is set to an empty string "" to indicate that the Library Service is not
currently set. Once set to a valid URL, you can reset the Library Service URL to an empty string to reset
it.
Example
Include "MAPBASIC.DEF"
Set LibraryServiceInfo URL
http://localhost:8080/LibraryService/LibraryService
See Also:
Set LibraryServiceInfo statement, LibraryServiceInfo( ) function
USNGToPoint( ) function
Purpose
Converts a string representing an USNG (United States National Grid) coordinate into a point object in
the current MapBasic coordinate system. You can call this function from the MapBasic window in MapInfo
Professional.
Syntax
USNGToPoint( string )
string is a string expression representing a USNG grid reference.
Return Value
Object.
Reference
753
Val( ) function
Description
The returned point will be in the current MapBasic coordinate system, which by default is Long/Lat (no
datum). For the most accurate results when saving the resulting points to a table, set the MapBasic coordinate system to match the destination table's coordinate system before calling USNGToPoint( ). This
will prevent MapInfo Professional from doing an intermediate conversion to the datumless Long/Lat coordinate system, which can cause a significant loss of precision.
Example 1
dim obj1 as Object
dim s_USNG As String
dim obj2 as Object
obj1 = CreatePoint(-74.669, 43.263)
s_USNG = PointToUSNG$(obj1)
obj2 = USNGToPoint(s_USNG)
Example 2
Open Table "C:\Temp\MyTable.TAB" as USNGfile
' When using the PointToUSNG$( ) or USNGToPoint( ) functions,
' it is very important to make sure that the current MapBasic
' coordsys matches the coordsys of the table where the
' point object is being stored.
'Set the MapBasic coordsys to that of the table used
Set CoordSys Table USNGfile
'Update a Character column (for example COL2) with USNG strings from
'a table of points
Update USNGfile
Set Col2 = PointToUSNG$(obj)
'Update two float columns (Col3 & Col4) with
'CentroidX & CentroidY information
'from a character column (Col2) that contains USNG strings.
Update USNGfile
Set Col3 = CentroidX(USNGToPoint(Col2))
Update USNGtestfile ' USNGfile
Set Col4 = CentroidY(USNGToPoint(Col2))
Commit Table USNGfile
Close Table USNGfile
See Also:
PointToUSNG$(obj, datumid)
Val( ) function
Purpose
Returns the numeric value represented by a string. You can call this function from the MapBasic window
in MapInfo Professional.
Syntax
Val( string_expr )
string_expr is a string expression.
754
MapBasic 12.0
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(" 52 - 62 Brunswick Ave")
' f_num is now equal to 52
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$( ) function, Format$( ) function, Set Format statement, Str$( ) function
Weekday( ) function
Purpose
Returns an integer from 1 to 7, indicating the weekday of a specified date. You can call this function from
the MapBasic window in MapInfo Professional.
Syntax
Weekday( date_expr )
date_expr is a date expression.
Reference
755
756
MapBasic 12.0
WKTToCoordSysString$( ) function
Purpose
Converts a Well-Known Text (WKT) string into a MapBasic coordinate system (CoordSys) clause. The
CoordSys clause specifies the coordinate system used by the paper map. For more details, see CoordSys clause. You can issue this statement from the MapBasic window in MapInfo Professional.
Syntax
WKTToCoordSysString$( wkt_string )
wkt_string is a Well-Known Text (WKT) string value.
Return Value
String expression, representing a coordinate system. If no string value is found, returns an empty string.
Example
The following example:
print WKTToCoordSysString$("GEOGCS["+"""NAD27 Latitude/Longitude,Degrees"""+",DATUM["+"""North_American_Datum_1927"""+",SPHEROID["+"""Clarke 1866"""+",6378206.4,294.9786982139006],AUTHORITY["+"""EPSG"""+","+"""6267"""+"]],PRIMEM["+"""Greenwich"+""",0],UNIT["+"""degree"""+",0.0174532925199433]]")
Produces the following string:
CoordSys Earth Projection 1, 62
See Also:
CoordSys clause, CoordSysStringToWKT$( ) function, Set CoordSys statement
Reference
757
While...Wend statement
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 (for example, for the sake of those programmers
who prefer the While...Wend syntax over the Do...Loop statement 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:
758
MapBasic 12.0
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 (for example,
the Map is scrolled, zoomed or re-sized). Within the WinChangedHandler procedure, call the CommandInfo( ) function 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 the End
Program statement.
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, MapInfo Professional calls
WinChangedHandler after the tool action is completed or canceled.
For example, if you use MapInfo Professional's Ruler tool and you autoscroll the window during each
segment, MapInfo Professional 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, MapInfo Professional calls the tool's handler procedure, and then calls WinChangedHandler.
MapInfo Professional 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.
Reference
759
WinClosedHandler procedure
Example
For an example of using a WinChangedHandler procedure, see the OverView sample program.
See Also:
CommandInfo( ) function, WinClosedHandler procedure
WinClosedHandler procedure
Purpose
A reserved procedure, called automatically when a Map, Browse, Graph, Layout, Redistricting, Legend,
Legend Designer, 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( ) function, EndHandler procedure, RemoteMsgHandler procedure, SelChangedHandler procedure, ToolHandler procedure, WinChangedHandler procedure
WindowID( ) function
Purpose
Returns a MapInfo Professional window identifier. You can call this function from the MapBasic window
in MapInfo Professional.
760
MapBasic 12.0
Result
Zero ( 0 )
MapInfo Professional returns the window ID of the most recently opened document window, custom Legend window,
or ButtonPad; returns zero if no windows are open.
Error Conditions
ERR_BAD_WINDOW_NUM (648) error is generated if the window_num parameter is invalid.
See Also:
WindowInfo( ) function, FrontWindow( ) function, NumWindows( ) function
Reference
761
WindowInfo( ) function
WindowInfo( ) function
Purpose
Returns information about a window. You can call this function from the MapBasic window in MapInfo
Professional.
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:
762
Value of window_spec
Description
Integer window ID
Zero ( 0 )
MapBasic 12.0
Description
The attribute parameter dictates which window attribute the function should return. The attribute parameter must be one of the codes from the table below:
attribute code
ID
WIN_INFO_NAME
WIN_INFO_TYPE
WIN_INFO_WIDTH
WIN_INFO_HEIGHT
WIN_INFO_X
WIN_INFO_Y
WIN_INFO_TOPMOST
WIN_INFO_STATE
WIN_INFO_TABLE
10
WIN_INFO_ADORNMENTS_MAP
10
WIN_INFO_LEGENDS_MAP
10
Reference
763
WindowInfo( ) function
attribute code
ID
764
WIN_INFO_OPEN
11
WIN_INFO_WND
12
Integer value. On Windows, the value represents a Windows HWND for the window you are querying.
WIN_INFO_WINDOWID
13
WIN_INFO_WORKSPACE
14
WIN_INFO_CLONEWINDOW
15
WIN_INFO_SYSMENUCLOSE
16
WIN_INFO_AUTOSCROLL
17
WIN_INFO_SMARTPAN
18
WIN_INFO_SNAPMODE
19
WIN_INFO_SNAPTHRESHOLD
20
WIN_INFO_PRINTER_NAME
21
WIN_INFO_PRINTER_ORIENT
22
WIN_INFO_PRINTER_COPIES
23
WIN_INFO_PRINTER_PAPERSIZE
24
MapBasic 12.0
ID
WIN_INFO_PRINTER_LEFTMARGIN 25
WIN_INFO_PRINTER_RIGHTMARGIN
26
WIN_INFO_PRINTER_TOPMARGIN 27
WIN_INFO_PRINTER_BOTTOMMAR- 28
GIN
WIN_INFO_PRINTER_BORDER (29) 29
WIN_INFO_PRINTER_TRUECOLOR 30
WIN_INFO_PRINTER_DITHER
31
WIN_INFO_PRINTER_METHOD
32
WIN_INFO_PRINTER_TRANSPRAS- 33
TER
WIN_INFO_PRINTER_TRANSPVECTOR
34
WIN_INFO_EXPORT_BORDER
35
WIN_INFO_EXPORT_TRUECOLOR 36
WIN_INFO_EXPORT_DITHER
37
WIN_INFO_EXPORT_TRANSPRAS- 38
TER
WIN_INFO_EXPORT_TRANSPVECTOR
39
WIN_INFO_PRINTER_SCALE_PAT- 40
TERNS
WIN_INFO_EXPORT_ANTIALIASING 41
Reference
765
WindowInfo( ) function
attribute code
ID
WIN_INFO_EXPORT_THRESHOLD 42
WIN_INFO_EXPORT_MASKSIZE
43
WIN_INFO_EXPORT_FILTER
44
FILTER_VERTICALLY_AND_HORIZONTALLY (0)
FILTER_ALL_DIRECTIONS_1 (1)
FILTER_ALL_DIRECTIONS_2 (2)
FILTER_DIAGONALLY (3)
FILTER_HORIZONTALLY (4)
FILTER_VERTICALLY (5)
WIN_INFO_ENHANCED_RENDER- 45
ING
WIN_INFO_SMOOTH_TEXT
46
WIN_INFO_SMOOTH_IMAGE
47
WIN_INFO_SMOOTH_VECTOR
48
If you specify WIN_INFO_TYPE as the attribute, WindowInfo( ) returns one of these values:
766
Window type
ID
Window description
WIN_MAPPER
Map window
WIN_BROWSER
Browse window
WIN_LAYOUT
Layout window
WIN_GRAPH
Graph window
WIN_BUTTONPAD
19
A ButtonPad window
WIN_TOOLBAR
25
WIN_CART_LEGEND
27
WIN_3DMAP
28
WIN_ADORNMENT
32
MapBasic 12.0
ID
Window description
WIN_LEGEND_DESIGNER
35
WIN_HELP
WIN_MAPBASIC
WIN_MESSAGE
WIN_RULER
WIN_INFO
1008 The Info window (displays data when the user clicks with
the Info tool)
WIN_LEGEND
WIN_STATISTICS
WIN_MAPINFO
Each Map window has a special, temporary table, which represents the "cosmetic layer" for that map.
These tables (which have names like "Cosmetic1", "Cosmetic2", etc.) are invisible to the MapInfo Professional user. To obtain the name of a Cosmetic table, specify WIN_INFO_TABLE (10). Similarly, you
can obtain the name of a Layout window's temporary table (for example, "Layout1") by calling WindowInfo( ) with the WIN_INFO_TABLE (10) attribute.
Error Conditions
ERR_BAD_WINDOW (590) error is generated if the window_id parameter is invalid.
ERR_FCN_ARG_RANGE (644) error is generated if an argument is outside of the valid range.
Example
The following example opens the Statistics window if it isn't open already.
If Not WindowInfo(WIN_STATISTICS,WIN_INFO_OPEN) Then
Open Window WIN_STATISTICS
End If
See Also:
WindowID( ) function, Browse statement, Graph statement, Map statement
WinFocusChangedHandler procedure
Purpose
A reserved procedure name, called automatically when the window focus changes.
Syntax
Declare Sub WinFocusChangedHandler
Sub WinFocusChangedHandler
Reference
767
Write # statement
statement_list
End Sub
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 MapInfo Professional 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 the
SelChangedHandler procedure.
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)
If i_win_type = WIN_MAPPER Then
' here, we could enable a map-related menu item
Else
' here, we could disable a map-related menu item
End If
End Sub
See Also:
WinChangedHandler procedure
Write # statement
Purpose
Writes data to an open file.
768
MapBasic 12.0
Year( ) function
Purpose
Returns the year component of a date value. You can call this function from the MapBasic window in
MapInfo Professional.
Syntax
Year( date_expr )
date_expr is a date expression.
Return Value
SmallInt
Description
If the Set Date Window( ) statement is off, then the year also depends on your system clock.
Examples
The following example shows how you can use the Year( ) function to extract only the year component
of a particular date value.
Dim sampleDate as Date
Set Date Window Off
sampleDate=StringToDate("10/1/98")
Reference
769
Year( ) function
Print Year(sampleDate)
' 2098 (or 1998 if the computer's system date is set in the 1900's)
' because with date windowing off MapInfo uses the current century
Set Date Window 50
' now assume that two-digit dates fall in the period 1950-2049
print Year(sampleDate)
' still 2098, because date variable has already been assigned!
sampleDate=StringToDate("10/1/98")
' re-assign variable now that the date window has changed
print Year(sampleDate) ' 1998
Undim sampleDate
The Year( ) function can also take a string, rather than a Date variable. In that case, implicit conversion
to date format occurs. The following example illustrates this:
Set Date Window Off
Print Year("10/1/99") ' prints 2099
Set Date Window 50
Print Year("10/1/99") ' prints 1999
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 MapInfo Professional 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( ) function, Day( ) function, DateWindow( ) function, Minute( ) function, Month( ) function,
Second( ) function, Weekday( ) function
770
MapBasic 12.0
This appendix details the HTTP and FTP libraries that enable MapBasic programmers to use web-based technology. These libraries allow access to RSS feeds
and other web-based location information such as weather information, traffic
feeds, vehicle locations, etc., as well as the ability to set up FTP connections and
search, receive, and send files through a MapBasic program. This library uses
the common DEF files: HTTPLib.DEF, HTTPType.DEF, and HTTPUtil.DEF,
which are installed in <Your MapBasic Installation Directory>\Samples\MapBasic\INC. Make sure you include these files as header
files into your programs. All the functionality described in this appendix is also
dependent on the presence of GmlXlat.dll which is installed with MapInfo
Professional.
We have provided sample applications that demonstrate the use of these libraries.
See <Your MapBasic Installation Directory>\Samples\MapBasic\HTTPLib and <Your MapBasic Installation Directory>\Samples\MapBasic\FTPLib for the specific samples.
All of the functions and procedures listed in this appendix are wrappers of the
corresponding methods of Microsoft MFC Classes. The wrapped classes include
CInternetSession, CHttpConnection, CFtpConnection, CHttpFile,
and CFtpFileFind. For more detailed information about the usage of the related
classes refer to the MSDN reference for MFC classes (http://msdn2.microsoft.com/en-us/library/bk77x1wx(en-US,vs.80).aspx).
Note: As this is a library, the functions and procedures listed in this appendix
do not execute from a MapBasic window in MapInfo Professional.
In this section:
772
MapBasic 12.0
MICloseContent( ) procedure
Purpose
Closes and disposes of the CString handle and frees its memory.
Syntax
MICloseContent( ByVal hContent As CString )
hContent is the CString object handle to be disposed of.
Description
Use the MICloseContent( ) procedure to close and free the CString object handle, obtained by calling
the MIGetContent( ) function, when the handle is no longer in use.
See Also:
MIGetContent( ) function
MICloseFtpConnection( ) procedure
Purpose
Closes and disposes of the CFtpConnection handle and frees its memory.
Syntax
MICloseFtpConnection( ByVal hConnection As CFtpConnection )
hConnection is the CFtpConnection object handle to be disposed of.
Description
Use the MICloseFtpConnection( ) procedure to close and free the CFtpConnection handle, obtained
by calling the MIGetFtpConnection( ) function, when the handle is no longer in use.
See Also:
MIGetFtpConnection( ) function
Reference
773
MICloseFtpFileFind( ) procedure
MICloseFtpFileFind( ) procedure
Purpose
Closes and disposes of the CFtpFileFind handle and frees its memory.
Syntax
MICloseFtpFileFind( ByVal hFTPFind As CFtpFileFind )
hFTPFind is the handle to a CFtpFileFind object to be disposed of.
Description
Use the MICloseFtpFileFind( ) procedure to close and free the CFtpFileFind handle, obtained by calling
the MIGetFtpFileFind( ) function, when the handle is no longer in use.
See Also:
MIGetFtpFileFind( ) function
MICloseHttpConnection( ) procedure
Purpose
Closes and disposes of the CHttpConnection handle and frees its memory.
Syntax
MICloseHttpConnection( ByVal hConnection As CHttpConnection )
hConnection is the CHttpConnection object handle to be disposed of.
Description
Use the MICloseHttpConnection( ) to close and free the CHttpConnection handle, obtained by calling
the MIGetHttpConnection( ) function, when the handle is no longer in use.
See Also:
MIGetHttpConnection( ) function
774
MapBasic 12.0
MICloseHttpFile( ) procedure
Purpose
Closes and disposes of the CHttpFile handle and frees its memory.
Syntax
MICloseHttpFile( ByVal hFile As CHttpFile )
hFile is the CHttpFile object handle to be disposed of.
Description
Use the MICloseHttpFile( ) procedure to close and free the CHttpFile object handle, obtained by calling
the MIOpenRequest( ) function or the MIOpenRequestFull( ) function, when the handle is no longer
in use.
See Also:
MIOpenRequest( ) function, MIOpenRequestFull( ) function
MICloseSession( ) procedure
Purpose
Closes and disposes of the CInternetSession handle and frees its memory.
Syntax
MICloseSession( ByVal hSession As CInternetSession )
hSession is the CInternetSession object handle to be disposed of.
Description
Use the MICloseSession( ) procedure to close and free the CInternetSession handle, obtained by calling
the MICreateSession( ) function or the MICreateSessionFull( ) function, when the handle is no longer
in use.
See Also:
MICreateSession( ) function, MICreateSessionFull( ) function
Reference
775
MICreateSession( ) function
MICreateSession( ) function
Purpose
Creates a CInternetSession object and returns the handle to it.
Syntax
MICreateSession( ByVal strAgent As String ) As CInternetSession
strAgent is a string that identifies the name of the application or entity calling the Internet functions (for
example, "MapInfo Professional"). If the string is empty, the application name will be used.
Return Value
A handle to a CInternetSession object. If the call fails, Null is returned. To determine the cause of the
failure, call the MIGetErrorMessage( ) function.
Description
MICreateSession( ) is the first Internet function called by an application. Use CInternetSession to create
and initialize a single, or several simultaneous Internet sessions, and, if necessary, to describe your
connection to a proxy server. If you want to perform service-specific (for example, HTTP, FTP) actions
on files located on a server, you must establish the appropriate connection with that server. To open a
particular kind of connection directly to a particular service, use the proper functions, such as the MIGetHttpConnection( ) function or the MIGetFtpConnection( ) function. For detailed information, refer
to the Microsoft MSDN library.
The caller has to dispose of the handle by calling the MICloseSession( ) procedure when the handle
is no longer in use.
See Also:
MICloseSession( ) procedure
MICreateSessionFull( ) function
Purpose
Creates a CInternetSession object and returns the handle to it.
Syntax
MICreateSessionFull( ByVal strAgent As String, ByVal dwContext As Integer,
ByVal dwAccessType As Integer, ByVal strProxyName As String,
776
MapBasic 12.0
Definition
INTERNET_OPEN_TYPE_PRECONFIG
Connect using preconfigured settings in the registry. This access type is set as default. To connect through a TIS proxy, set dwAccessType to
this value; you then set the registry appropriately.
INTERNET_OPEN_TYPE_DIRECT
INTERNET_OPEN_TYPE_PROXY
strProxyName is the name of the preferred CERN proxy if dwAccessType is set as INTERNET_OPEN_TYPE_PROXY. Default is an empty string.
strProxyBypass is a string that contains an option list of server addresses. These addresses may be
bypassed when using proxy access. If an empty string is supplied, the bypass list will be read from the
registry. This parameter is meaningful only if dwAccessType is set to INTERNET_OPEN_TYPE_PROXY.
dwFlags indicates various caching options. The default is set to 0. The possible values include:
dwFlag value
Definition
INTERNET_FLAG_DONT_CACHE
INTERNET_FLAG_OFFLINE
Return Value
A handle to a CInternetSession object. If the call fails, Null is returned. To determine the cause of the
failure, call the MIGetErrorMessage( ) function.
Description
MICreateSessionFull( ) is the first Internet function called by an application. Use CInternetSession to
create and initialize a single or several simultaneous Internet sessions and, if necessary, to describe
your connection to a proxy server. If you want to perform service-specific (for example, HTTP, FTP) actions
on files located on a server, you must establish the appropriate connection with that server. To open a
particular kind of connection directly to a particular service, use the proper functions, such as the MIGetHttpConnection( ) function or the MIGetFtpConnection( ) function. For detailed information, refer
to the Microsoft MSDN library.
Reference
777
MIErrorDlg( ) function
The caller has to dispose of the handle by calling the MICloseSession( ) procedure when the handle
is no longer in use.
See Also:
MICreateSession( ) function, MICloseSession( ) procedure
MIErrorDlg( ) function
Purpose
Displays an error message dialog box.
Displays a dialog box for the error that is passed to MIErrorDlg, if an appropriate dialog box exists. The
function also checks the headers of the specified CHttpFile for any hidden errors and displays a dialog
box if needed.
Syntax
MIErrorDlg( ByVal hFile As CHttpFile, ByVal dwError As Integer) As Integer
hFile is a CHttpFile handle.
dwError is the error code which is used to get the error message.
Return Value
Returns one of the following values, otherwise returns an error value.
Error Code
Description
ERROR_SUCCESS
ERROR_CANCELLED
ERROR_INTERNET_FORCE_RETRY
Description
Use this function to get the error message in the form of a dialog box if an appropriate dialog box exists.
It also checks the headers for any hidden errors and displays a dialog box if needed. For more information,
refer to the Microsoft MSDN library. Allowable error codes are as follows:
778
MapBasic 12.0
Description
ERROR_INTERNET_HTTP_TO_HTTPS_ON_REDIR
Notifies the user that the function does not recognize the certificate authority that generated the
certificate for this Secure Socket Layer (SSL) site.
ERROR_INTERNET_POST_IS_NON_SECURE
ERROR_INTERNET_SEC_CERT_CN_INVALID
ERROR_INTERNET_SEC_CERT_DATE_INVALID Notifies the user that the SSL certificate has expired.
For more information, refer to the Microsoft MSDN Library.
See Also:
MIOpenRequest( ) function, MISendRequest( ) function
MIFindFtpFile( ) function
Purpose
Finds an FTP file with the given CFtpFileFind handle.
Syntax
MIFindFtpFile( ByVal hFTPFind As CFtpFileFind, ByVal strName As String )
As SmallInt
hFTPFind is a CFtpFileFind handle.
strDirName is a string that contains the name of the file to find. If it is empty, the call performs a wildcard
search (*).
Reference
779
MIFindNextFtpFile( ) function
Return Value
Nonzero if successful; otherwise 0. To determine the cause of the failure, call the MIGetErrorMessage(
) function.
Description
After calling MIFindFtpFile( ) to retrieve the first FTP file, you can call the MIFindNextFtpFile( ) function
to retrieve subsequent FTP files.
See Also:
MIGetFtpFileFind( ) function, MIFindNextFtpFile( ) function, MIGetFtpFileName( ) procedure,
MIIsFtpDirectory( ) function, MIIsFtpDots( ) function
MIFindNextFtpFile( ) function
Purpose
Continues a file search begun with a call to the MIFindFtpFile( ) function with the given CFtpFileFind
handle.
Syntax
MIFindNextFtpFile( ByVal hFTPFind As CFtpFileFind ) As SmallInt
hFTPFind is a CFtpFileFind handle.
Return Value
Nonzero if there are more files; zero if the file found is the last one in the directory or if an error occurred.
Description
You must call MIfindNextFtpFile( ) at least once before calling any attribute function, such as MIGetFtpFileName( ) procedure, MIIsFtpDirectory( ) function, and MIIsFtpDots( ) function.
See Also:
MIGetFtpFileFind( ) function, MIFindFtpFile( ) function, MIGetFtpFileName( ) procedure, MIIsFtpDirectory( ) function, MIIsFtpDots( ) function
780
MapBasic 12.0
MIGetContent( ) function
Purpose
Gets the content of the file.
Syntax
MIGetContent( ByVal hFile As CHttpFile )
As CString
MIGetContentBuffer( ) function
Purpose
Gets the content in the format of a string with the given size.
Syntax
MIGetContentBuffer( ByVal hContent As CString, pBuffer As String,
ByVal nLen As Integer As SmallInt
hContent is a CString handle.
pBuffer is a reference to a string that receives the content of the file.
nLen is the size of pBuffer in number of characters or bytes.
Reference
781
MIGetContentLen( ) function
Return Value
Nonzero if successful; otherwise 0. To determine the cause of the failure, call the MIGetErrorMessage(
) function.
Description
Use MIGetContentBuffer( ) to get the content of the file in string format with a given size. You have to
allocate memory for pBuffer before calling this function.
See Also:
MIGetContent( ) function, MIGetContentLen( ) function, MIGetContentString( ) function.
MIGetContentLen( ) function
Purpose
Gets the content length.
Syntax
MIGetContentLen( ByVal hContent As CString ) As Integer
hContent is a CString handle.
Return Value
The content length in number of characters or bytes. Zero could be either that the call fails or that content
is empty. To determine the cause of the failure, call the MIGetErrorMessage( ) function.
Description
Use MIGetContentLen( ) to get the content length of the file in number of characters or bytes.
See Also:
MIGetErrorMessage( ) function
MIGetContentString( ) function
Purpose
Gets the content in the format of string.
782
MapBasic 12.0
MIGetContentToFile( ) function
Purpose
Saves the contents to a given file.
Syntax
MIGetContentToFile( ByVal hFile As CHttpFile,
ByVal strFileName As String As SmallInt
hFile is a CHttpFile handle
strFileName is a string that identifies the local file name that receives the content of hFile.
Return Value
Nonzero if successful; otherwise 0. To determine the cause of the failure, call the MIGetErrorMessage(
) function.
Description
This function is used to save the content to a CHttpFile to a local file, which is an alternative to MIGetContent. It will create a new file with given file name. If the file exists already, it is truncated to 0 length.
It has to remember that MIGetContentToFile and MIGetContent are exclusive, which means you can
only use one of them during the life time of a CHttpFile object.
See Also:
MIOpenRequest( ) function, MISendRequest( ) function, MIGetContent( ) function.
Reference
783
MIGetContentType( ) function
MIGetContentType( ) function
Purpose
Gets the content type of the file.
Syntax
MIGetContentType( ByVal hFile As CHttpFile, pBuffer As String,
pBufferLength As Integer As SmallInt
hFile is a CHttpFile handle.
pBuffer is a reference to a string that receives the content type.
pBufferLength is a reference to an integer that contains the length of pBuffer in number of characters or
bytes on entry. When the function succeeds (a string is written to pBuffer), it contains the length of the
string in characters, minus 1 for the terminating NULL character.
Return Value
Nonzero if successful; otherwise 0. To determine the cause of the failure, call the MIGetErrorMessage(
) function.
Description
Use MIGetContentType( ) to get the content type of the file in string format. For example, written value
in pBuffer could be "image/jpeg" or "text/html".
See Also:
MIQueryInfo( ) function
MIGetCurrentFtpDirectory( ) function
Purpose
Gets the name of the current directory on the FTP server with the given CFtpConnection handle.
Syntax
MIGetCurrentFtpDirectory( Byval hConnection As CFtpConnection,
pDirName As String, pLen As Integer As SmallInt
hConnection is a CFtpConnection handle.
pDirName is a reference to a string that receives the name of the directory.
784
MapBasic 12.0
MIGetErrorCode( ) function
Purpose
Retrieves the last error that was set as a result of a call to a function in this library.
Syntax
MIGetErrorCode() As Integer
Return Value
Error code of the last error set.
Description
MIGetErrorCode( ) is called if the function's return value indicates its failure and you want to know the
error code. To obtain an error message as a String, call the MIGetErrorMessage( ) function.
The error value retrieved is only set when certain errors occur during calls to other functions in the HTTP
and FTP API. It is primarily useful for determining which error occurred as a result of a call to the MISendRequest( ) function or the MISendSimpleRequest( ) function so the correct value can be passed
to the MIErrorDlg( ) function.
See Also:
MIGetErrorMessage( ) function, MISendRequest( ) function, MISendSimpleRequest( ) function,
MIErrorDlg( ) function
Reference
785
MIGetErrorMessage( ) function
MIGetErrorMessage( ) function
Purpose
Retrieves the last error message.
Syntax
MIGetErrorMessage( ) As String
Return Value
A string that contains the error message.
Description
MIGetErrorMessage( ) should be called immediately to get useful data when a function's return value
indicates its failure and you want to know the cause. Many of the returned errors are system-set errors.
MIGetFileURL( ) function
Purpose
Gets the name of the HTTP file as a URL.
Syntax
MIGetFileURL( ByVal hFile As CHttpFile, pURL As String,
ByVal lURLLen As Integer ) As SmallInt
hFile is a CHttpFile handle.
pURL is a reference to a string that receives the name of the HTTP file as a URL.
pURLLen is the size of pURL in number of characters or bytes.
Return Value
Nonzero if successful; otherwise 0. To determine the cause of the failure, call the MIGetErrorMessage(
) function.
Description
Use MIGetFileURL( ) to get the name of the HTTP file as a URL.
786
MapBasic 12.0
MIGetFtpConnection( ) function
Purpose
Establishes an FTP connection and gets a handle to a CFtpConnection object.
Syntax
MIGetFtpConnection( ByVal hSession As CInternetSession,
ByVal strServer As String, ByVal strUserName As String,
ByVal strPassword As String, ByVal nPort As INTERNET_PORT )
As CFtpConnection
hSession is a CinternetSession handle.
strServer is a string that contains the FTP server name.
strUserName is a string that specifies the name of the user to log in.
strPassword is a string that specifies the password to use to log in.
nPort is a number that identifies the TCP/IP port to use on the server.
Return Value
A handle to a CFtpConnection object. If the call fails, Null is returned. To determine the cause of the
failure, call the MIGetErrorMessage( ) function.
Description
MIGetFtpConnection( ) connects to an FTP server, creates and returns a handle to a CFtpConnection
object. It does not perform any specific operation on the server. If you intend to get or put files, for example,
you must perform those operations as separate steps.
The caller has to dispose of the handle by calling the MICloseFtpConnection( ) procedure when the
handle is no longer in use.
See Also:
MICloseFtpConnection( ) procedure, MIGetHttpConnection( ) function, MICreateSession( ) function,
MICreateSessionFull( ) function, MIParseURL( ) function
Reference
787
MIGetFtpFile( ) function
MIGetFtpFile( ) function
Purpose
Gets a file from an FTP server with the given CFtpConnection handle and stores it on the local. machine.
Syntax
MIGetFtpFile( ByVal hConnection As CFtpConnection,
ByVal strRemoteFile As String, ByVal strLocalFile As String,
ByVal bFailIfExists As SmallInt, ByVal dwAttributes As Integer,
ByVal dwFlags As Integer ) As SmallInt
hConnection is a CFtpConnection handle.
strRemoteFile is a string that contains the name of a file to retrieve from the FTP server.
strLocalFile is a string that contains the name of the file to create on the local system.
bFailIfExists indicates whether the file name may already be used by an existing file. If the local file name
already exists, and this parameter is TRUE, MIGetFtpFile( ) fails. Otherwise, MIGetFtpFile( ) erases
the existing copy of the file.
dwAttributes indicates the attributes of the file. This can be any combination of the following FILE_ATTRIBUTE_* flags.
788
dwAttirbute value
Definition
FILE_ATTRIBUTE_ARCHIVE
The file is an archive file. Applications use this attribute to mark files for backup or removal.
FILE_ATTRIBUTE_COMPRESSED
FILE_ATTRIBUTE_DIRECTORY
FILE_ATTRIBUTE_NORMAL
FILE_ATTRIBUTE_HIDDEN
FILE_ATTRIBUTE_READONLY
FILE_ATTRIBUTE_SYSTEM
MapBasic 12.0
Definition
FILE_ATTRIBUTE_TEMPORARY
The file is being used for temporary storage. Applications should write to the file only if absolutely necessary. Most of the file's data remains in memory
without being flushed to the media because the file
will soon be deleted.
dwFlags specifies the conditions under which the transfer occurs. This parameter can be any of the following values:
dwFlags value
Definition
FTP_TRANSFER_TYPE_ASCII
FTP_TRANSFER_TYPE_BINARY
FTP_TRANSFER_TYPE_UNKNOWN
Defaults to FTP_TRANSFER_TYPE_BINARY.
Return Value
Nonzero if successful; otherwise 0. To determine the cause of the failure, call the MIGetErrorMessage(
) function.
Description
Both strRemoteFile and strLocalFile can be either partially qualified file names relative to the current
directory, or fully qualified. A backslash (\) or forward slash (/) can be used as the directory separator
for either name.
See Also:
MIGetFtpConnection( ) function, MIPutFtpFile( ) function
MIGetFtpFileFind( ) function
Purpose
Gets a handle to a CFtpFileFind object.
Syntax
MIGetFtpFileFind( ByVal hConnection As CFtpConnection ) As CFtpFileFind
Reference
789
MIGetFtpFileName( ) procedure
hConnection is a CFtpConnection handle.
Return Value
A handle to a CFtpFileFind object. If the call fails, Null is returned. To determine the cause of the failure,
call the MIGetErrorMessage( ) function.
Description
The CFtpFileFind class aids in Internet file searches of FTP servers.
The caller has to dispose of the handle by calling MICloseFtpFileFind( ) procedure when the handle
is no longer in use.
See Also:
MIGetFtpConnection( ) function, MICloseFtpFileFind( ) procedure
MIGetFtpFileName( ) procedure
Purpose
Gets the name of the found file with the given CFtpFileFind handle.
Syntax
MIGetFtpFileName( ByVal hFTPFind As CFtpFileFind, pFileName As String,
ByVal bufferlen As Integer )
hFTPFind is a CFtpFileFind handle.
pFileName is a reference to a string that will receive the name of the found file.
bufferlen is the size of the buffer referenced by pFileName.
Description
You must call MIFindNextFtpFile( ) function at least once before calling MIGetFtpFileName( ).
See Also:
MIGetFtpFileFind( ) function, MIFindNextFtpFile( ) function, MIFindFtpFile( ) function
790
MapBasic 12.0
MIGetHttpConnection( ) function
Purpose
Establishes an HTTP connection and gets a handle to a CHttpConnection object.
Syntax
MIGetHttpConnection( ByVal hSession As CInternetSession,
ByVal strServer As String, ByVal nPort As INTERNET_PORT
As CHttpConnection
hSession is a CinternetSession handle.
strServer is a string that contains the HTTP server name.
nPort is a number that identifies the TCP/IP port to use on the server.
Return Value
A handle to a CHttpConnection object. If the call fails, Null is returned. To determine the cause of the
failure, call the MIGetErrorMessage( ) function.
Description
MIGetHttpConnection( ) connects to an HTTP server, creates and returns a handle to a CHttpConnection
object. It does not perform any specific operation on the server. If you intend to query an HTTP header,
for example, you must perform this operation in separate steps.
The caller has to dispose of the handle by calling the MICloseHttpConnection( ) procedure when the
handle is no longer in use.
See Also:
MICloseHttpConnection( ) procedure, MIGetFtpConnection( ) function, MICreateSession( ) function,
MICreateSessionFull( ) function, MIParseURL( ) function
MIIsFtpDirectory( ) function
Purpose
Determines if the found file is a directory with the given CFtpFileFind handle.
Syntax
MIIsFtpDirectory( ByVal hFTPFind As CFtpFileFind ) As SmallInt
Reference
791
MIIsFtpDots( ) function
hFTPFind is a CFtpFileFind handle.
Return Value
Nonzero if the found file is a directory; otherwise 0.
Description
You must call MIFindNextFtpFile( ) function at least once before calling MIIsFtpDirectory( ).
See Also:
MIGetFtpFileFind( ) function, MIFindNextFtpFile( ) function, MIFindFtpFile( ) function, MIGetFtpFileName( ) procedure
MIIsFtpDots( ) function
Purpose
Tests for the current directory and parent directory markers while iterating through files with the given
CFtpFileFind handle.
Syntax
MIIsFtpDots( ByVal hFTPFind As CFtpFileFind ) As SmallInt
hFTPFind is a CFtpFileFind handle.
Return Value
Nonzero if the found file has the name "." or "..", which indicates that the found file is actually a directory.
Otherwise 0.
Description
You must call the MIFindNextFtpFile( ) function at least once before calling MIIsFtpDots( ).
See Also:
MIGetFtpFileFind( ) function, MIFindNextFtpFile( ) function, MIFindFtpFile( ) function, MIGetFtpFileName( ) procedure
792
MapBasic 12.0
MIOpenRequest( ) function
Purpose
Opens an HTTP connection.
Syntax
MIOpenRequest( ByVal hConnection As CHttpConnection,
ByVal nVerb As Integer, ByVal strObjectName As String
) As CHttpFile
hConnection is a CHttpConnection handle.
nVerb is a number associated with the HTTP request type. Can be one of the following:
HTTP_VERB_POST
HTTP_VERB_GET
HTTP_VERB_HEAD
HTTP_VERB_PUT
HTTP_VERB_LINK
HTTP_VERB_DELETE
HTTP_VERB_UNLINK
strObjectName is a string containing the target object of the specified verb. This is generally a file name,
an executable module, or a search specifier.
Return Value
A handle to a CHttpFile object requested. If the call fails, Null is returned. To determine the cause of the
failure, call the MIGetErrorMessage( ) function.
Description
This function opens an HTTP connection and returns a handle to a CHttpFile object, which provides
services requesting and reading files on an HTTP server. If your Internet session reads data from an
HTTP server, you must get a handle to CHttpFile object.
The caller has to dispose of the handle by calling MICloseHttpFile( ) procedure when the handle is no
longer in use.
See Also:
MIOpenRequestFull( ) function, MIParseURL( ) function
Reference
793
MIOpenRequestFull( ) function
MIOpenRequestFull( ) function
Purpose
Opens an HTTP connection.
Syntax
MIOpenRequestFull( ByVal hConnection As CHttpConnection,
ByVal nVerb As Integer, ByVal strObjectName As String,
ByVal strReferer As String, ByVal dwContext As Integer,
ByVal strVersion As String, ByVal dwFlags As Integer )
As CHttpFile
hConnection is a CHttpConnection handle.
nVerb is a number associated with the HTTP request type. Can be one of the following:
HTTP_VERB_POST
HTTP_VERB_GET
HTTP_VERB_HEAD
HTTP_VERB_PUT
HTTP_VERB_LINK
HTTP_VERB_DELETE
HTTP_VERB_UNLINK
strObjectName is a string containing the target object of the specified verb. This is generally a file name,
an executable module, or a search specifier.
strReferer is a string that specifies the address (URL) of the document from which the URL in the request
(strObjectName) was obtained. If the string is empty, no HTTP header is specified.
dwContext is the context identifier for the MIOpenRequestFull( ) operation. For detailed information,
refer to the Microsoft MSDN library.
strVersion is a string defining the HTTP version. If the string is empty, "HTTP/1.0" is used.
dwFlags is any combination of the following INTERNET_ FLAG_* flags:
794
dwFlag value
Definition
INTERNET_FLAG_RELOAD
INTERNET_ FLAG_DONT_CACHE
INTERNET_FLAG_MAKE_PERSISTENT
Adds the returned entity to the cache as a persistent entity. This means that standard cache cleanup,
consistency checking, or garbage collection cannot
remove this item from the cache.
MapBasic 12.0
Definition
INTERNET_ FLAG_SECURE
INTERNET_ FLAG_NO_AUTO_REDIRECT
Return Value
A handle to a CHttpFile object requested. If the call fails, Null is returned. To determine the cause of the
failure, call the MIGetErrorMessage( ) function.
Description
This function opens an HTTP connection and returns a handle to a CHttpFile object, which provides
services requesting and reading files on an HTTP server. If your Internet session reads data from an
HTTP server, you must get a handle to CHttpFile object. This function wraps the MFC function OpenRequest which has an additional parameter to indicate accepted types. In this version, the wrapper function
always sets this parameter to NULL.
The caller has to dispose of the handle by calling the MICloseHttpFile( ) procedure when the handle
is no longer in use.
See Also:
MIGetHttpConnection( ) function, MIOpenRequest( ) function, MIParseURL( ) function
MIParseURL( ) function
Purpose
Parses a URL string and returns the type of service and its components.
Syntax
MIParseURL( ByVal strURL As String, pServiceType As Integer,
pServer As String, ByVal nServerLen As Integer,
pObject As String, ByVal nObjectLen As Integer,
pPort As INTERNET_PORT )
As SmallInt
strURL is a string that contains the URL to be parsed.
pServiceType is a reference to a integer that receives the type of Internet service. The possible values
are one of the following:
INTERNET_SERVICE_FTP
Reference
795
MIPutFtpFile( ) function
INTERNET_SERVICE_GOPHER
INTERNET_SERVICE_HTTP
AFX_INET_SERVICE_UNK
AFX_INET_SERVICE_FILE
AFX_INET_SERVICE_MAILTO
AFX_INET_SERVICE_MID
AFX_INET_SERVICE_CID
AFX_INET_SERVICE_NEWS
AFX_INET_SERVICE_NNTP
AFX_INET_SERVICE_PROSPERO
AFX_INET_SERVICE_TELNET
AFX_INET_SERVICE_WAIS
AFX_INET_SERVICE_AFS
AFX_INET_SERVICE_HTTPS
strsServer is a reference to a string that specifies the first segment of the URL following the service type.
nServerLen is the size of the buffer referenced by strsServer.
pObject is a reference to an object that the URL refers to (may be empty).
nObjectLen is the size of the buffer referenced by pObject.
pPort is a reference to an integer that contains the determined port number from either the Server or
Object portions of the URL, if either exists. The port number is used to identify the TCP/IP port to use
on the server.
Return Value
Nonzero if the URL was successfully parsed; otherwise, 0 if it is empty or does not contain a known Internet service type. To determine the cause of the failure, call the MIGetErrorMessage( ) function.
Description
MIParseURL( ) parses a URL string and returns the type of service and its components. For example,
it parses URLs of the form: ftp://ftp.mysite.org/ and returns its components stored as follows:
pServer == "ftp.mysite.org"
pObject == "/"
nPort == #port
pServiceType == INTERNET_SERVICE_FTP
MIPutFtpFile( ) function
Purpose
Stores a file on an FTP server with the given CFtpConnection handle.
796
MapBasic 12.0
Definition
FTP_TRANSFER_TYPE_ASCII
FTP_TRANSFER_TYPE_BINARY
Return Value
Nonzero if successful; otherwise 0. To determine the cause of the failure, call the MIGetErrorMessage(
) function.
Description
Both strRemoteFile and strLocalFile can be either partially qualified file names relative to the current
directory, or fully qualified. A backslash (\) or forward slash (/) can be used as the directory separator
for either name.
See Also:
MIGetFtpConnection( ) function, MIGetFtpFile( ) function
MIQueryInfo( ) function
Purpose
Returns response or request headers from an HTTP request.
Reference
797
MIQueryInfoStatusCode( ) function
Syntax
MIQueryInfo( ByVal hFile As CHttpFile, ByVal dwInfoLevel As Integer,
pBuffer As String, pBufferLength As Integer ) As SmallInt
hFile is a CHttpFile handle.
dwInfoLevel is a combination of the attribute to query, and a modifier flag that specifies the type of information requested: For a list of the modifier flags, refer to the Microsoft MSDN library.
pBuffer is a reference to a string that receives the information. For the attribute HTTP_QUERY_CUSTOM,
pBuffer is also an input indicating which header name to query.
pBufferLength is a reference to an integer that contains the length of pBuffer in number of characters or
bytes on entry. When the function succeeds (a string is written to pBuffer), it contains the length of the
string in characters minus 1 for the terminating NULL character.
Return Value
Nonzero if successful; otherwise 0. To determine the cause of the failure, call the MIGetErrorMessage(
) function.
Description
Use this function to get response or request headers from an HTTP request. For a description of attribute
values, refer to the Microsoft MSDN library for information on Query Info flags (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wininet/wininet/query_info_flags.asp).
See Also:
MIOpenRequest( ) function, MISendRequest( ) function
MIQueryInfoStatusCode( ) function
Purpose
Gets the status code associated with an HTTP request.
Syntax
MIQueryInfoStatusCode( ByVal hFile As CHttpFile, pStatusCode As Integer
s SmallInt
hFile is a CHttpFile handle.
pStatusCode is a reference to an integer that receives the status code. Status codes indicate the success
or failure of the requested event. HTTP status codes fall into groups indicating the success or failure of
the request. The following tables outline the status code groups and the most common HTTP status
codes.
798
MapBasic 12.0
Meaning
200-299
Success
300-399
Information
400-499
Request error
500-599
Server error
Meaning
200
400
Unintelligible request.
404
405
500
503
Return Value
Nonzero if successful; otherwise 0. To determine the cause of the failure, call the MIGetErrorMessage(
) function.
Description
Use this function to get the status code associated with an HTTP request. For information, refer to the
Microsoft MSDN library.
See Also:
MIOpenRequest( ) function, MISendRequest( ) function
MISaveContent( ) function
Purpose
Saves the content to a given file.
Reference
799
MISendRequest( ) function
Syntax
MISaveContent( ByVal hContent As CString, ByVal strFileName As String
As SmallInt
hContent is a CString handle.
strFileName is a string that identifies the file name that receives the content.
Return Value
Nonzero if successful; otherwise 0. To determine the cause of the failure, call the MIGetErrorMessage(
) function.
Description
This function is used to save the content to a file. It will create a new file with the given file name. If the
file exists already, it is truncated to 0 length.
See Also:
MIGetContent( ) function
MISendRequest( ) function
Purpose
Sends a request to an HTTP server.
Syntax
MISendRequest( ByVal hFile As CHttpFile, ByVal strHeaders As String,
ByVal dwHeadersLen As Integer, ByVal strOptional As String,
ByVal dwOptionalLen As Integer, ByVal bAuthenticate As SmallInt
As SmallInt
hFile is a CHttpFile handle.
strHeaders is a string containing the name of the headers to send.
dwHeadersLen is the length of the headers identified by strHeaders.
strOptional is any optional data to send immediately after the request headers. This is generally used
for POST and PUT operations. This can be empty if there is no optional data to send.
dwOptionalLen is the length of strOptional.
bAuthenticate indicates whether to check authentication or not.
Return Value
Nonzero if successful; otherwise 0. To determine the cause of the failure, call the MIGetErrorMessage(
) function.
800
MapBasic 12.0
MISendSimpleRequest( ) function
Purpose
Sends a request to an HTTP server.
Syntax
MISendSimpleRequest( ByVal hFile As CHttpFile,
ByVal bAuthenticate As SmallInt ) As SmallInt
hFile is a CHttpFile handle.
bAuthenticate indicates whether to check authentication or not.
Return Value
Nonzero if successful; otherwise 0. To determine the cause of the failure, call the MIGetErrorMessage(
) function.
Description
This function sends a request to an HTTP server.
See Also:
MIOpenRequest( ) function, MIOpenRequestFull( ) function, MISendRequest( ) function
MISetCurrentFtpDirectory( ) function
Purpose
Changes to a different directory on the FTP server with the given CFtpConnection handle.
Syntax
MISetCurrentFtpDirectory( Byval hConnection As CFtpConnection,
Byval strDirName As String ) As SmallInt
Reference
801
MISetSessionTimeout( ) function
hConnection is a CFtpConnection handle.
strDirName is a string that contains the name of the directory.
Return Value
Nonzero if successful; otherwise 0. To determine the cause of the failure, call the MIGetErrorMessage(
) function.
Description
The pDirName parameter can be either a partially or fully qualified file name relative to the current directory. A backslash (\) or forward slash (/) can be used as the directory separator for either name.
MISetCurrentFtpDirectory( ) translates the directory name separators to the appropriate characters
before they are used.
See Also:
MIGetFtpConnection( ) function, MIGetCurrentFtpDirectory( ) function
MISetSessionTimeout( ) function
Purpose
Sets the time-out options for the Internet session.
Syntax
MISetSessionTimeout( ByVal hSession As CInternetSession,
ByVal Connect As Integer, ByVal Send As Integer,
ByVal Receive As Integer ) As SmallInt
hSession is the CInternetSession object handle.
Connect is an integer that contains time-out value in millisecond to use for the Internet connection request.
Send is an integer that contains the time-out value in milliseconds to use for sending a request.
Receive is an integer that contains the time-out value in milliseconds to use for receiving a request.
Return Value
Nonzero if successful; otherwise 0. To determine the cause of the failure, call the MIGetErrorMessage(
) function.
Description
Use this function to set time-out values for the Internet session. The default value of each setting (Connect,
Send, Receive) is 0. For detailed information, refer to the Microsoft MSDN library.
802
MapBasic 12.0
Reference
803
XML Library
This appendix details the XML document library that enables MapBasic programmers to create and parse XML documents and other web-based technology. This
library uses common DEF files: XMLLib.DEF and XMLTypes.DEF, which are
installed in <Your MapBasic Installation Directory>\Samples\MapBasic\INC. Make
sure you include these files as header files into your programs. All the functionality
described in this appendix is also dependent on the presence of GmlXlat.dll
which is installed with MapInfo Professional.
All of the functions and procedures listed in this appendix are wrappers of the
corresponding methods of Microsoft XML Interfaces and Classes. Wrapped
classes include: IXMLDOMNode, IXMLDOMNodeList, IXMLDOMNamedNodeMap,
IXMLDOMSchemaCollection2, and IXMLDOMDocument2. For more detailed
information about the usage of the related classes and interfaces refer to the
MSDN reference http://msdn.microsoft.com/library/default.asp?url=/library/enus/xmlsdk/html/39b17b9c-04c7-4fa8-bcee-1f7d57eefd74.asp
Note: As this is a library, the functions and procedures listed in this appendix
do not execute from a MapBasic window in MapInfo Professional.
In this section:
806
MapBasic 12.0
MIXmlAttributeListDestroy( ) procedure
Purpose
Disposes of the MIXmlNamedNodeMap object and frees its memory.
Syntax
MIXmlNodeListDestroy( ByVal hXMLNodeList As MIXmlNodeList )
hXMLAttributeList is The MIXmlNamedNodeMap object handle to be disposed of.
Description
The caller has to call this function to free the MIXmlNamedNodeMap handle obtained by calling the
MIXmlGetAttributeList( ) function, when the handle is no longer in use.
See Also:
MIXmlGetAttributeList( ) function
MIXmlDocumentCreate( ) function
Purpose
Creates an MIXmlDocument object and gets a handle to the object.
Syntax
MIXmlDocumentCreate( ) As MIXmlDocument
Return Value
A handle to the MIXmlDocument object. If the call fails, Null is returned. To determine the cause of the
failure, call the MIGetErrorMessage( ) function.
Description
MIXmlDocumentCreate( ) creates and returns a handle to an MIXmlDocument object. It represents the
top level of the XML source.
The caller has to dispose of the handle by calling the MIXmlDocumentDestroy( ) procedure when the
handle is no longer in use.
See Also:
MIXmlDocumentDestroy( ) procedure
Reference
807
MIXmlDocumentDestroy( ) procedure
MIXmlDocumentDestroy( ) procedure
Purpose
Disposes of the MIXmlDocument and frees its memory.
Syntax
MIXmlDocumentDestroy( ByVal hXMLDocument As MIXmlDocument )
hXMLDocument is the MIXmlDocument object handle to be disposed of.
Description
The caller has to call this function to close and free the MIXmlDocument handle obtained by calling the
MIXmlDocumentCreate( ) function when the handle is no longer in use.
See Also:
MIXmlDocumentCreate( ) function
MIXmlDocumentGetNamespaces( ) function
Purpose
Creates an MIXMLSchemaCollection object and gets a handle to the object.
Syntax
MIXmlDocumentGetNamespaces( ByVal hXMLDocument As MIXmlDocument )
As MIXMLSchemaCollection
hXMLDocument is the MIXmlDocument object handle.
Return Value
A handle to an MIXMLSchemaCollection object if successful; otherwise NULL.
Description
This method creates an MIXMLSchemaCollection object.
The caller has to dispose of the handle by calling the MIXmlSCDestroy( ) procedure when the handle
is no longer in use.
808
MapBasic 12.0
MIXmlDocumentGetRootNode( ) function
Purpose
Retrieves the root element of the document.
Syntax
MIXmlDocumentGetRootNode( ByVal hXMLDocument As MIXmlDocument )
As MIXmlNode
hXMLDocument is the MIXmlDocument object handle.
Return Value
A handle to an MIXmlNode object representing the root element of the document if successful; otherwise
NULL.
Description
MIXmlDocumentGetRootNode( ) retrieves a handle to an MIXmlNode object that represents the root
of the XML document tree. It returns NULL if no root exists.
The caller has to dispose of the handle by calling the MIXmlNodeDestroy( ) procedure when the handle
is no longer in use.
See Also:
MIXmlDocumentCreate( ) function, MIXmlNodeDestroy( ) procedure
MIXmlDocumentLoad( ) function
Purpose
Loads an XML document from the specified location.
Syntax
MIXmlDocumentLoad( ByVal hXMLDocument As MIXmlDocument,
ByVal strPath As String, pbParsingError As SmallInt,
ByVal bValidate As SmallInt, ByVal bResolveExternals As SmallInt )
As SmallInt
hXMLDocument is the MIXmlDocument object handle.
Reference
809
MIXmlDocumentLoadXML( ) function
strPath is a string containing the path/URL that specifies the location of the XML file.
pbParsingError is a reference to a SmallInt that indicates TRUE if the load succeeded; FALSE if the load
failed.
bValidate is a SmallInt that indicates whether the parser should validate this document. If TRUE (1), it
validates during parsing. If FALSE (0), it parses only for well-formed XML.
bResolveExternals is a SmallInt that indicates whether external definitions, resolvable namespaces,
document type definition (DTD) external subsets, and external entity references, are to be resolved at
parse time, independent of validation. When the bResolveExternals parameter is TRUE (1), external
definitions are resolved at parse time. This allows default attributes and data types to be defined on
elements from the schema and allows use of the DTD as a file inclusion mechanism. This setting is independent of whether validation is to be performed, as indicated by the value of the bValidate property.
If externals cannot be resolved during validation, a validation error occurs. When the value of bResolveExternals is FALSE (0), externals are not resolved and validation is not performed.
Return Value
Nonzero if successful, otherwise 0. To determine the cause of the failure, call the MIGetErrorMessage(
) function.
Description
If the URL cannot be resolved or accessed or does not reference an XML document, this method returns
FALSE. Calling MIXmlDocumentLoad( ) on an existing document immediately discards the content of
the document. If loading an XML document from a resource, the load must be performed asynchronously
or the load will fail.
See Also:
MIXmlDocumentCreate( ) function, MIXmlDocumentLoadXML( ) function, MIXmlDocumentLoadXMLString( ) function
MIXmlDocumentLoadXML( ) function
Purpose
Loads an XML document using the supplied string.
Syntax
MIXmlDocumentLoadXML( ByVal hXMLDocument As MIXmlDocument,
ByVal hContent As CString, pbParsingError As SmallInt,
ByVal bValidate As SmallInt, ByVal bResolveExternals As SmallInt )
As SmallInt
hXMLDocument is The MIXmlDocument object handle.
810
MapBasic 12.0
MIXmlDocumentLoadXMLString( ) function
Purpose
Loads an XML document using a supplied string.
Syntax
MIXmlDocumentLoadXMLString( ByVal hXMLDocument As MIXmlDocument,
ByVal strXML As String, pbParsingError As SmallInt,
ByVal bValidate As SmallInt, ByVal bResolveExternals As SmallInt )
As SmallInt
hXMLDocument is the MIXmlDocument object handle.
strXML is a string containing the XML string to load into this XML document object. This string can contain
an entire XML document or a well-formed fragment.
Reference
811
MIXmlDocumentSetProperty( ) function
pbParsingError is a reference to a SmallInt that indicates TRUE (nonzero) if the load succeeded; FALSE
(0) if the load failed.
bValidate is a SmallInt that Indicates whether the parser should validate this document. If TRUE (1), it
validates during parsing. If FALSE (0), it parses only for well-formed XML.
bResolveExternals is a SmallInt that indicates whether external definitions, resolvable namespaces,
document type definition (DTD) external subsets, and external entity references, are to be resolved at
parse time, independent of validation. When the bResolveExternals parameter is TRUE (1), external
definitions are resolved at parse time. This allows default attributes and data types to be defined on
elements from the schema and allows use of the DTD as a file inclusion mechanism. This setting is independent of whether validation is to be performed, as indicated by the value of the bValidate property.
If externals cannot be resolved during validation, a validation error occurs. When the value of bResolveExternals is FALSE (0), externals are not resolved and validation is not performed.
Return Value
Nonzero if successful, otherwise 0. To determine the cause of the failure, call the MIGetErrorMessage(
) function.
Description
Calling MIXmlDocumentLoadXMLString( ) on an existing document immediately discards the content
of the document. It will work only with UTF-16 or UCS-2 encodings.
See Also:
MIXmlDocumentCreate( ) function, MIXmlDocumentLoad( ) function, MIXmlDocumentLoadXML(
) function
MIXmlDocumentSetProperty( ) function
Purpose
Sets the properties for the MIXmlDocument object.
Syntax
MIXmlDocumentSetProperty( ByVal hXMLDocument As MIXmlDocument,
ByVal strPropertyName As String, ByVal strPropertyValue As String )
As SmallInt
hXMLDocument is the MIXmlDocument object handle.
strPropertyName is a string that contains the name of the property to be set. For a list of properties that
can be set using this method, refer to the Microsoft MSDN library.
strPropertyValue is a string that contains the value of the specified property. For a list of property values
that can be set using this method, refer to the Microsoft MSDN library.
812
MapBasic 12.0
MIXmlGetAttributeList( ) function
Purpose
Retrieves the MIXmlNamedNodeMap object with the given node.
Syntax
MIXmlGetAttributeList( ByVal hXMLNode As MIXmlNode ) As MIXmlNamedNodeMap
hXMLNode is the MIXmlNode object handle.
Return Value
A handle to the MIXmlNamedNodeMap object that contains the nodes which can return attributes. Returns
NULL for all other node types.
Description
MIXmlGetAttributeList( ) creates an MIXmlNamedNodeMap object and returns the handle to the object.
This object only contains the nodes which can return attributes (Element, Entity, and Notation nodes).
Null is returned for all other node types. For the valid node types, a handle to an MIXmlNamedNodeMap
object is always returned; when there are no attributes on the element, the list length is set to zero. For
detailed information and the list of valid node types, refer to the Microsoft MSDN library.
The caller has to dispose of the handle by calling the MIXmlAttributeListDestroy( ) procedure when
the returned handle is no longer in use.
See Also:
MIXmlDocumentGetRootNode( ) function, MIXmlAttributeListDestroy( ) procedure
Reference
813
MIXmlGetChildList( ) function
MIXmlGetChildList( ) function
Purpose
Gets an MIXmlNodeList object that contains the children nodes of the given node instance.
Syntax
MIXmlGetChildList( ByVal hXMLNode As MIXmlNode) As MIXmlNodeList
hXMLNode is the MIXmlNode object handle.
Return Value
A handle to the MIXmlNodeList object that contains the children nodes of the given node instance if
successful; otherwise NULL.
Description
MIXmlGetChildList( ) is used to get a list of children in the given node. An MIXmlNodeList object is returned even if there are no children of the node. In such a case, the length of the list is set to 0. This
value depends on the value of the node type. For more information, refer to the Microsoft MSDN library.
The caller has to dispose of the handle by calling the MIXmlNodeListDestroy( ) procedure when the
handle is no longer in use.
See Also:
MIXmlNodeListDestroy( ) procedure, MIXmlSelectNodes( ) function
MIXmlGetNextAttribute( ) function
Purpose
Returns the next node in the collection.
Syntax
MIXmlGetNextAttribute( ByVal hXMLAttributeList As MIXmlNamedNodeMap )
As MIXmlNode
hXMLAttributeList is the MIXmlNamedNodeMap object handle.
814
MapBasic 12.0
MIXmlGetNextNode( ) function
Purpose
Returns the next node in the collection.
Syntax
MIXmlGetNextNode( ByVal hXMLNodeList As MIXmlNodeList ) As MIXmlNode
hXMLNodeList is the MIXmlNodeList object handle.
Return Value
A handle to the MIXmlNode object which refers to the next node in the collection represented by, hXMLNodeList, if successful; returns NULL if there is no next node.
Description
The iterator initially points before the first node in the list so that the first call to the MIXmlGetNextNode(
) function returns the first node in the list. This functions returns NULL when the current node is the last
node or there are no items in the list.
The caller has to dispose of the returned handle by calling the MIXmlNodeDestroy( ) procedure when
the handle is no longer in use.
See Also:
MIXmlNodeDestroy( ) procedure, MIXmlSelectNodes( ) function, MIXmlGetChildList( ) function
Reference
815
MIXmlNodeDestroy( ) procedure
MIXmlNodeDestroy( ) procedure
Purpose
Disposes of the MIXmlNode object and frees its memory.
Syntax
MIXmlNodeDestroy( ByVal hXMLNode As MIXmlNode )
hXMLNode is the MIXmlNode object handle to be disposed of.
Description
The caller has to call this function to free a MIXmlNode object handle obtained, such as by calling
MIXmlDocumentGetRootNode( ) function, when the handle is no longer in use.
See Also:
MIXmlDocumentDestroy( ) procedure
MIXmlNodeGetAttributeValue( ) function
Purpose
Retrieves the text associated with the specified name.
Syntax
MIXmlNodeGetAttributeValue( ByVal hXMLNode As MIXmlNode,
ByVal strAttributeName As String, pValue As String,
ByVal nLen As Integer ) As SmallInt
hXMLNode is the MIXmlNode object handle.
strAttributeName is a string specifying the name of the attribute.
pValue is a reference to a string that receives the node value of the specified attribute.
nLen is the size of the buffer referenced by pValue.
Return Value
Nonzero if successful; otherwise 0.
816
MapBasic 12.0
MIXmlNodeGetFirstChild( ) function
Purpose
Retrieves the first child of the given node instance.
Syntax
MIXmlNodeGetFirstChild( ByVal hXMLNode As MIXmlNode ) As MIXmlNode
hXMLNode is the MIXmlNode object handle.
Return Value
A handle to the MIXmlNode object which is the first child of the given node instance, hXMLNode, if
successful; otherwise NULL.
Description
MIXmlNodeGetFirstChild( ) gets a handle to a MIXmlNode object that is the first child of the given node
instance. It returns NULL if no child exists.
The caller has to dispose of the handle by calling MIXmlNodeDestroy( ) procedure when the handle
is no longer in use.
See Also:
MIXmlNodeDestroy( ) procedure, MIXmlNodeGetParent( ) function
MIXmlNodeGetName( ) function
Purpose
Gets the node name of the given node instance.
Reference
817
MIXmlNodeGetParent( ) function
Syntax
MIXmlNodeGetName( ByVal hXMLNode As MIXmlNode, pName As String,
ByVal nLen As Integer ) As SmallInt
hXMLNode is the MIXmlNode object handle.
pName is a reference to a string that receives the node name, which varies depending on the node type.
nLen is the size of the buffer referenced by pName.
Return Value
Nonzero if successful; otherwise 0.
Description
This function is used to get the node name with a given node. The node name is the qualified name for
the element, attribute, or entity reference. The node name value varies, depending on the note type.
See Also:
MIXmlDocumentGetRootNode( ) function, MIXmlNodeGetText( ) function, MIXmlNodeGetValue(
) function
MIXmlNodeGetParent( ) function
Purpose
Retrieves the parent of the given node instance.
Syntax
MIXmlNodeGetParent( ByVal hXMLNode As MIXmlNode ) As MIXmlNode
hXMLNode is the MIXmlNode object handle.
Return Value
A handle to the MIXmlNode object which is the parent of the given node instance, hXMLNode, if successful; otherwise NULL.
Description
MIXmlNodegetParent( ) gets a handle to a MIXmlNode object that is the parent of the given node instance. It returns NULL if no parent exists.
The caller has to dispose of the handle by calling the MIXmlNodeDestroy( ) procedure when the handle
is no longer in use.
818
MapBasic 12.0
MIXmlNodeGetText( ) function
Purpose
Gets the text content of the given node or the concatenated text representing the node and its descendants.
Syntax
MIXmlNodeGetText( ByVal hXMLNode As MIXmlNode, pText As String,
ByVal nLen As Integer ) As SmallInt
hXMLNode is the MIXmlNode object handle.
pText is a reference to a string that receives the text content of the given node and its descendants. This
value varies depending on the value of the note type.
nLen is the size of the buffer referenced by pText.
Return Value
Nonzero if successful; otherwise 0.
Description
MIXmlNodegettext( ) is used to get the node text with a given node instance. Its value varies, depending
on the node type. For more details and more precise control over text manipulation in an XML document,
refer to the Microsoft MSDN library.
See Also:
MIXmlDocumentGetRootNode( ) function, MIXmlNodeGetName( ) function, MIXmlNodeGetValue(
) function
MIXmlNodeGetValue( ) function
Purpose
Gets the text associated with the given node instance.
Reference
819
MIXmlNodeListDestroy( ) procedure
Syntax
MIXmlNodeGetValue( ByVal hXMLNode As MIXmlNode, pValue As String,
ByVal nLen As Integer ) As SmallInt
hXMLNode is the MIXmlNode object handle.
pValue is a reference to a string that receives the value, which varies depending on the node type.
nLen is the size of the buffer referenced by pValue.
Return Value
Nonzero if successful; otherwise 0.
Description
This function is used to get the node value with a given node instance. The node value varies, depending
on the node type.
See Also:
MIXmlDocumentGetRootNode( ) function, MIXmlNodeGetName( ) function, MIXmlNodeGetText(
) function
MIXmlNodeListDestroy( ) procedure
Purpose
Disposes of the MIXmlNodeList object and frees its memory.
Syntax
MIXmlNodeListDestroy( ByVal hXMLNodeList As MIXmlNodeList )
hXMLNodeList is the MIXmlNodeList object handle to be disposed of.
Description
Use MIXmlNodeListDestroy( ) to free the MIXmlNodeList handle obtained with functions such as the
MIXmlSelectNodes( ) function, and the MIXmlGetChildList( ) function, when the MIXmlNodeList
handle is no longer in use.
See Also:
MIXmlDocumentDestroy( ) procedure, MIXmlGetChildList( ) function, MIXmlSelectNodes( ) function
820
MapBasic 12.0
MIXmlSCDestroy( ) procedure
Purpose
Disposes of the MIXMLSchemaCollection object and frees its memory.
Syntax
MIXmlSCDestroy( ByVal hXMLSchemaCollection As MIXMLSchemaCollection )
hXMLSchemaCollection is the MIXMLSchemaCollection object handle to be disposed of.
Description
Use MIXmlSCDestroy( ) to free the MIXMLSchemaCollection handle obtained with a function such as
the MIXmlDocumentGetNamespaces( ) function, when the handle is no longer in use.
See Also:
MIXmlDocumentGetNamespaces( ) function
MIXmlSCGetLength( ) function
Purpose
Gets the number of namespaces currently in the collection.
Syntax
MIXmlSCGetLength( ByVal hXMLSchemaCollection As MIXMLSchemaCollection )
As Integer
hXMLSchemaCollection is the MIXMLSchemaCollection object handle.
Return Value
The number of namespaces currently in the collection.
Description
MIXmlSCGetLength( ) allows you to retrieve the number of namespaces currently in the collection.
See Also:
MIXmlDocumentGetNamespaces( ) function, MIXmlSCGetNamespace( ) function
Reference
821
MIXmlSCGetNamespace( ) function
MIXmlSCGetNamespace( ) function
Purpose
Gets the namespace at the specified index.
Syntax
MIXmlSCGetNamespace( ByVal hXMLSchemaCollection As MIXMLSchemaCollection,
ByVal index As Integer, pNamespace As String, ByVal nLen As Integer )
As SmallInt
hXMLSchemaCollection is the MIXMLSchemaCollection object handle.
index is an integer that indicates the index between 0 and count -1.
pNamespace is a reference to a string that receives the name of the namespace.
nLen is the size of the buffer referenced by pNamespace.
Return Value
Nonzero if successful; otherwise 0. To determine the cause of the failure, call the MIGetErrorMessage(
) function.
Description
MIXmlSCGetNamespace( ) allows you to iterate through the collection to discover its contents.
See Also:
MIXmlDocumentGetNamespaces( ) function, MIXmlSCGetLength( ) function
MIXmlSelectNodes( ) function
Purpose
Applies the specified pattern-matching operation to this node's context and returns the list of matching
nodes as an MIXmlNodeList object.
Syntax
MIXmlSelectNodes( ByVal hXMLNode As MIXmlNode, ByVal strPattern As String
) As MIXmlNodeList
hXMLNode is the MIXmlNode object handle.
strPattern is a string specifying an XPath expression.
822
MapBasic 12.0
MIXmlSelectSingleNode( ) function
Purpose
Applies the specified pattern-matching operation to this node's context and returns the first matching
node as an MIXmlNode object.
Syntax
MIXmlSelectSingleNode( ByVal hXMLNode As MIXmlNode,
ByVal strPattern As String ) As MIXmlNode
hXMLNode is the MIXmlNode object handle.
strPattern is a string specifying an XPath expression.
Return Value
A handle to the MIXmlNode object. Returns the first node that matches the given pattern-matching operation. If no nodes match the expression, returns a NULL value.
Description
MIXmlSelectSingleNode( ) gets a handle to an MIXmlNode object that is the first matching node with
the given pattern-matching operation. It returns NULL if no child exists. MIXmlSelectSingleNode( ) is
similar to the MIXmlSelectNodes( ) function, but returns the first matching node rather than a list of all
the matching nodes.
The caller has to dispose of the handle by calling the MIXmlNodeDestroy( ) procedure when the handle
is no longer in use.
See Also
Reference
823
MIXmlSelectSingleNode( ) function
MIXmlNodeDestroy( ) procedure, MIXmlSelectNodes( ) function
824
MapBasic 12.0
In this section:
Character Code Table Definitions . . . . . . . . . . . . . . . . . .826
826
MapBasic 12.0
Summary of Operators
Operators act on one or more values to produce a result. Operators can be classified by the data types they use and the type result they produce.
In this section:
Numeric Operators
Numeric Operators
The following numeric operators act on two numeric values, producing a numeric result.
Operator
Performs
Example
addition
a + b
subtraction
a - b
multiplication
a * b
division
a / b
a \ b
Mod
a Mod b
exponentiation
a ^ b
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.
Operator
Performs
Example
numeric negation
- a
string concatenation
a + b
&
string concatenation
a & b
Comparison Operators
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, SmallInt, and float data types. Comparison
operators are often used in conditional expressions, such as If...Then.
828
MapBasic 12.0
Example
a is equal to b
a = b
<>
a is not equal to b
a <> b
<
a is less than b
a < b
>
a is greater than b
a > b
<=
a <= b
>=
a >= b
Logical Operators
The logical operators operate on logical values to produce a logical result of TRUE or FALSE:
Operator
Example
And
a And b
Or
a Or b
Not
Not a
Geographical Operators
The geographic operators act on objects to produce a logical result of TRUE or FALSE:
Reference
829
Precedence
Operator
Example
Contains
Contains Part
Contains Entire
Within
Partly Within
part of the first object is within the objectA Partly Within objectB
second object
Entirely Within
Intersects
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).
Priority
MapBasic Operator
(Highest Priority)
parenthesis
exponentiation
negation
multiplication, division, Mod, integer division
addition, subtraction
830
MapBasic 12.0
MapBasic Operator
geographic operators
(Lowest Priority)
Combination of Operands
Result
Date + Number
Date
Number + Date
Date
Integer + Integer
Integer
Number + Number
Float
Other + Other
String
Date - Number
Date
Reference
831
Wildcards
Operator
Combination of Operands
Result
Date - Date
Integer
Integer - Integer
Integer
Number - Number
Float
Integer * Integer
Integer
Number * Number
Float
Number / Number
Float
Number \ Number
Integer
MOD
Integer
Number ^ Number
Float
Wildcards
The LIKE operator uses the percent (%) and underscore ( _ ) characters as wildcards.
832
Wildcard
Performs
Example
MapBasic 12.0
In this section:
The MAPBASIC.DEF File . . . . . . . . . . . . . . . . . . . . . . . . .834
834
MapBasic 12.0
Reference
835
BLACK
WHITE
RED
GREEN
BLUE
CYAN
MAGENTA
YELLOW
0
16777215
16711680
65280
255
65535
16711935
16776960
836
MapBasic 12.0
Reference
837
'============================================================================
' FileAttr() defines
'============================================================================
Define FILE_ATTR_MODE
1
Define FILE_ATTR_FILESIZE
2
'--------------------------------------------------------------------------' File Access Modes, returned by FileAttr() for FILE_ATTR_MODE
'--------------------------------------------------------------------------Define MODE_INPUT
0
Define MODE_OUTPUT
1
Define MODE_APPEND
2
Define MODE_RANDOM
3
Define MODE_BINARY
4
'============================================================================
' GetFolderPath$() defines
'============================================================================
Define
Define
Define
Define
Define
Define
Define
Define
Define
Define
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
-1
-2
-3
-4
26
28
35
46
5
39
'============================================================================
' GetPreferencePath$(), GetCurrentPath$(), and Set Path defines
'============================================================================
Define
Define
Define
Define
Define
Define
Define
Define
Define
Define
Define
Define
Define
Define
PREFERENCE_PATH_TABLE
PREFERENCE_PATH_WORKSPACE
PREFERENCE_PATH_MBX
PREFERENCE_PATH_IMPORT
PREFERENCE_PATH_SQLQUERY
PREFERENCE_PATH_THEMETHEMPLATE
PREFERENCE_PATH_MIQUERY
PREFERENCE_PATH_NEWGRID
PREFERENCE_PATH_CRYSTAL
PREFERENCE_PATH_GRAPHSUPPORT
PREFERENCE_PATH_REMOTETABLE
PREFERENCE_PATH_SHAPEFILE
PREFERENCE_PATH_WFSTABLE
PREFERENCE_PATH_WMSTABLE
0
1
2
3
4
5
6
7
8
9
10
11
12
13
'============================================================================
' IntersectNodes() defines
'============================================================================
Define INCL_CROSSINGS
1
Define INCL_COMMON
6
Define INCL_ALL
7
'============================================================================
838
MapBasic 12.0
Reference
0
1
839
840
MapBasic 12.0
LAYER_INFO_LBL_AUTO_SIZE_STEP
LAYER_INFO_LBL_CURVED_BEST_POSITION
LAYER_INFO_LBL_CURVED_FALLBACK
LAYER_INFO_LBL_USE_ABBREVIATION
LAYER_INFO_ABBREVIATION_EXPR
LAYER_INFO_LBL_AUTO_CALLOUT
LAYER_INFO_LBL_ORDER
57
58
59
60
61
62
63
Reference
841
LAYER_INFO_TYPE_IMAGE
LAYER_INFO_TYPE_THEMATIC
LAYER_INFO_TYPE_GRID
LAYER_INFO_TYPE_WMS
LAYER_INFO_TYPE_TILESERVER
2
3
4
5
6
842
MapBasic 12.0
LBL_OVR_INFO_PARALLEL
8
LBL_OVR_INFO_POS
9
LBL_OVR_INFO_OVERLAP
10
LBL_OVR_INFO_DUPLICATES
11
LBL_OVR_INFO_OFFSET
12
LBL_OVR_INFO_MAX
13
LBL_OVR_INFO_PARTIALSEGS
14
LBL_OVR_INFO_ORIENTATION
15
LBL_OVR_INFO_ALPHA
16
LBL_OVR_INFO_AUTODISPLAY
17
LBL_OVR_INFO_POS_RETRY
18
LBL_OVR_INFO_LINE_PEN
19
LBL_OVR_INFO_PERCENT_OVER
20
LBL_OVR_INFO_AUTO_POSITION
21
LBL_OVR_INFO_AUTO_SIZES
22
LBL_OVR_INFO_SUPPRESS_IF_NO_FIT 23
LBL_OVR_INFO_AUTO_SIZE_STEP
24
LBL_OVR_INFO_CURVED_BEST_POSITION 25
LBL_OVR_INFO_CURVED_FALLBACK
26
LBL_OVR_INFO_USE_ABBREVIATION
27
LBL_OVR_INFO_ABBREVIATION_EXPR 28
LBL_OVR_INFO_AUTO_CALLOUT
29
Reference
843
844
MapBasic 12.0
FRAME_INFO_NUM_STYLES
FRAME_INFO_VISIBLE
FRAME_INFO_COLUMN
FRAME_INFO_LABEL
FRAME_INFO_COLUMNS
FRAME_INFO_NUM_VISIBLE_ROWS
FRAME_INFO_LINE_SAMPLE_WIDTH
FRAME_INFO_REGION_SAMPLE_WIDTH
FRAME_INFO_REGION_SAMPLE_HEIGHT
FRAME_INFO_AUTO_FONT_SIZE
13
14
15
16
17
18
19
20
21
22
'============================================================================
' LegendTextFrameInfo() defines
'============================================================================
Define TEXTFRAME_INFO_POS_X
1
Define TEXTFRAME_INFO_POS_Y
2
Define TEXTFRAME_INFO_WIDTH
3
Define TEXTFRAME_INFO_HEIGHT
4
Define TEXTFRAME_INFO_TEXT
5
Define TEXTFRAME_INFO_TEXT_FONT
6
'============================================================================
' Frame Types, returned by LegendFrameInfo() for FRAME_INFO_TYPE
'============================================================================
Define FRAME_TYPE_STYLE
1
Define FRAME_TYPE_THEME
2
'============================================================================
' Geocode Attributes, returned by GeocodeInfo()
'============================================================================
Define GEOCODE_STREET_NAME
1
Define GEOCODE_STREET_NUMBER
2
Define GEOCODE_MUNICIPALITY
3
Define GEOCODE_MUNICIPALITY2
4
Define GEOCODE_COUNTRY_SUBDIVISION
5
Define GEOCODE_COUNTRY_SUBDIVISION2
6
Define GEOCODE_POSTAL_CODE
7
Define
Define
Define
Define
Define
Define
Define
Define
Define
Define
Define
Define
Define
Define
Define
GEOCODE_DICTIONARY
GEOCODE_BATCH_SIZE
GEOCODE_FALLBACK_GEOGRAPHIC
GEOCODE_FALLBACK_POSTAL
GEOCODE_OFFSET_CENTER
GEOCODE_OFFSET_CENTER_UNITS
GEOCODE_OFFSET_END
GEOCODE_OFFSET_END_UNITS
GEOCODE_MIXED_CASE
GEOCODE_RESULT_MARK_MULTIPLE
GEOCODE_COUNT_GEOCODED
GEOCODE_COUNT_NOTGEOCODED
GEOCODE_UNABLE_TO_CONVERT_DATA
GEOCODE_MAX_BATCH_SIZE
GEOCODE_PASSTHROUGH
9
10
11
12
13
14
15
16
17
18
19
20
21
22
100
Define
Define
Define
Define
Define
DICTIONARY_ALL
DICTIONARY_ADDRESS_ONLY
DICTIONARY_USER_ONLY
DICTIONARY_PREFER_ADDRESS
DICTIONARY_PREFER_USER
1
2
3
4
5
'============================================================================
Reference
845
LOCATE_PREF_FILE
LOCATE_DEF_WOR
LOCATE_CLR_FILE
LOCATE_PEN_FILE
LOCATE_FNT_FILE
LOCATE_ABB_FILE
LOCATE_PRJ_FILE
LOCATE_MNU_FILE
LOCATE_CUSTSYMB_DIR
LOCATE_THMTMPLT_DIR
LOCATE_GRAPH_DIR
LOCATE_WMS_SERVERLIST
LOCATE_WFS_SERVERLIST
LOCATE_GEOCODE_SERVERLIST
LOCATE_ROUTING_SERVERLIST
LOCATE_LAYOUT_TEMPLATE_DIR
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
'============================================================================
' Map3DInfo() defines
'============================================================================
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
846
MapBasic 12.0
MAP3D_INFO_LIGHT_X
MAP3D_INFO_LIGHT_Y
MAP3D_INFO_LIGHT_Z
MAP3D_INFO_LIGHT_COLOR
MAP3D_INFO_CAMERA_X
MAP3D_INFO_CAMERA_Y
MAP3D_INFO_CAMERA_Z
MAP3D_INFO_CAMERA_FOCAL_X
MAP3D_INFO_CAMERA_FOCAL_Y
MAP3D_INFO_CAMERA_FOCAL_Z
MAP3D_INFO_CAMERA_VU_1
MAP3D_INFO_CAMERA_VU_2
MAP3D_INFO_CAMERA_VU_3
MAP3D_INFO_CAMERA_VPN_1
MAP3D_INFO_CAMERA_VPN_2
MAP3D_INFO_CAMERA_VPN_3
MAP3D_INFO_CAMERA_CLIP_NEAR
MAP3D_INFO_CAMERA_CLIP_FAR
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
'============================================================================
' 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
Define MAPPER_INFO_REPROJECTION
25
Define MAPPER_INFO_RESAMPLING
26
Define MAPPER_INFO_MERGE_MAP
27
Define MAPPER_INFO_ALL_LAYERS
28
Define MAPPER_INFO_GROUPLAYERS
29
Define MAPPER_INFO_NUM_ADORNMENTS
200
Define MAPPER_INFO_ADORNMENT
200
Define MAPPER_INFO_LABELS_SELECTABLE
30
'--------------------------------------------------------------------------' Display Modes, returned by MapperInfo() for MAPPER_INFO_DISPLAY_DMS
'--------------------------------------------------------------------------Define MAPPER_INFO_DISPLAY_DECIMAL
0
Reference
847
MAPPER_INFO_DISPLAY_DEGMINSEC
MAPPER_INFO_DISPLAY_MGRS
MAPPER_INFO_DISPLAY_USNG_WGS84
MAPPER_INFO_DISPLAY_USNG_NAD27
1
2
3
4
848
MapBasic 12.0
OBJ_GEO_ARCENDANGLE
OBJ_GEO_TEXTLINEY
OBJ_GEO_TEXTANGLE
OBJ_GEO_POINTZ
OBJ_GEO_POINTM
6
6
7
8
9
'============================================================================
' 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
Define OBJ_INFO_Z_UNIT_SET
12
Define OBJ_INFO_Z_UNIT
13
Define OBJ_INFO_HAS_Z
14
Define OBJ_INFO_HAS_M
15
'--------------------------------------------------------------------------' Object types, returned by ObjectInfo() for 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
'----------------------*
' RegionInfo() Defines
'----------------------*
Define REGION_INFO_IS_CLOCKWISE
'============================================================================
' PrismMapInfo() defines
'============================================================================
Define PRISMMAP_INFO_SCALE
Reference
849
PRISMMAP_INFO_BACKGROUND
PRISMMAP_INFO_LIGHT_X
PRISMMAP_INFO_LIGHT_Y
PRISMMAP_INFO_LIGHT_Z
PRISMMAP_INFO_LIGHT_COLOR
PRISMMAP_INFO_CAMERA_X
PRISMMAP_INFO_CAMERA_Y
PRISMMAP_INFO_CAMERA_Z
PRISMMAP_INFO_CAMERA_FOCAL_X
PRISMMAP_INFO_CAMERA_FOCAL_Y
PRISMMAP_INFO_CAMERA_FOCAL_Z
PRISMMAP_INFO_CAMERA_VU_1
PRISMMAP_INFO_CAMERA_VU_2
PRISMMAP_INFO_CAMERA_VU_3
PRISMMAP_INFO_CAMERA_VPN_1
PRISMMAP_INFO_CAMERA_VPN_2
PRISMMAP_INFO_CAMERA_VPN_3
PRISMMAP_INFO_CAMERA_CLIP_NEAR
PRISMMAP_INFO_CAMERA_CLIP_FAR
PRISMMAP_INFO_INFOTIP_EXPR
4
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
'============================================================================
' 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() defines
'--------------------------------------------------------------------------
850
MapBasic 12.0
SRV_COL_INFO_NAME
SRV_COL_INFO_TYPE
SRV_COL_INFO_WIDTH
SRV_COL_INFO_PRECISION
SRV_COL_INFO_SCALE
SRV_COL_INFO_VALUE
SRV_COL_INFO_STATUS
SRV_COL_INFO_ALIAS
1
2
3
4
5
6
7
8
Reference
851
0
1
2
'============================================================================
' SessionInfo() defines
'============================================================================
Define
Define
Define
Define
SESSION_INFO_COORDSYS_CLAUSE
SESSION_INFO_DISTANCE_UNITS
SESSION_INFO_AREA_UNITS
SESSION_INFO_PAPER_UNITS
1
2
3
4
'============================================================================
' 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
'============================================================================
' StringCompare() defines
'============================================================================
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() for SYMBOL_KIND
'--------------------------------------------------------------------------Define SYMBOL_KIND_VECTOR
1
Define SYMBOL_KIND_FONT
2
852
MapBasic 12.0
'============================================================================
' 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
Define SYS_INFO_MIBUILD_NUMBER
18
Define SYS_INFO_MIFULLVERSION
19
'--------------------------------------------------------------------------' Platform, returned by SystemInfo() for 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() for 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
Define MIPLATFORM_WIN64
7
'============================================================================
' 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
Reference
853
TAB_INFO_NROWS
TAB_INFO_EDITED
TAB_INFO_FASTEDIT
TAB_INFO_UNDO
TAB_INFO_MAPPABLE_TABLE
TAB_INFO_USERMAP
TAB_INFO_USERBROWSE
TAB_INFO_USERCLOSE
TAB_INFO_USEREDITABLE
TAB_INFO_USERREMOVEMAP
TAB_INFO_USERDISPLAYMAP
TAB_INFO_TABFILE
TAB_INFO_MINX
TAB_INFO_MINY
TAB_INFO_MAXX
TAB_INFO_MAXY
TAB_INFO_SEAMLESS
TAB_INFO_COORDSYS_MINX
TAB_INFO_COORDSYS_MINY
TAB_INFO_COORDSYS_MAXX
TAB_INFO_COORDSYS_MAXY
TAB_INFO_COORDSYS_CLAUSE
TAB_INFO_COORDSYS_NAME
TAB_INFO_NREFS
TAB_INFO_SUPPORT_MZ
TAB_INFO_Z_UNIT_SET
TAB_INFO_Z_UNIT
TAB_INFO_BROWSER_LIST
TAB_INFO_THEME_METADATA
TAB_INFO_COORDSYS_CLAUSE_WITHOUT_BOUNDS
TAB_INFO_DESCRIPTION
TAB_INFO_ID
TAB_INFO_PARENTID
TAB_INFO_ISMANAGED
TAB_INFO_ADSK_TEXTOBJECT
TAB_INFO_OVERRIDE_COORDINATE_ORDER
TAB_INFO_PERSIST
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
854
MapBasic 12.0
Reference
855
1
2
3
856
MapBasic 12.0
WIN_INFO_EXPORT_THRESHOLD
WIN_INFO_EXPORT_MASKSIZE
WIN_INFO_EXPORT_FILTER
WIN_INFO_ENHANCED_RENDERING
WIN_INFO_SMOOTH_TEXT
WIN_INFO_SMOOTH_IMAGE
WIN_INFO_SMOOTH_VECTOR
42
43
44
45
46
47
48
Reference
857
858
MapBasic 12.0
OBJ_TYPE_TEXT
'--------------------------------------------------------------------------' Codes for AdornmentInfo function to get info about an adornment win
'--------------------------------------------------------------------------Define ADORNMENT_INFO_TYPE
1
Define ADORNMENT_INFO_MAP_WINDOWID
2
Define ADORNMENT_INFO_IS_FIXED_POS
3
Define ADORNMENT_INFO_FIXED_POS_X
4
Define ADORNMENT_INFO_FIXED_POS_Y
5
Define ADORNMENT_INFO_FIXED_POS_UNITS
6
Define ADORNMENT_INFO_DOCKED_POS
7
Define ADORNMENT_INFO_DOCKED_OFFSET_X
8
Define ADORNMENT_INFO_DOCKED_OFFSET_Y
9
Define ADORNMENT_INFO_DOCKED_UNITS
10
Define ADORNMENT_INFO_BACKGROUND_PEN
11
Define ADORNMENT_INFO_BACKGROUND_BRUSH
12
Define ADORNMENT_INFO_SB_TYPE
20
Define ADORNMENT_INFO_SB_MAP_UNITS
21
Define ADORNMENT_INFO_SB_PAPER_UNITS
22
Define ADORNMENT_INFO_SB_BAR_LENGTH
23
Define ADORNMENT_INFO_SB_BAR_DRAW_LEN
24
Define ADORNMENT_INFO_SB_BAR_HEIGHT
25
Define ADORNMENT_INFO_SB_AUTO_SCALING
26
Define ADORNMENT_INFO_SB_CARTO_SCALE
27
Define ADORNMENT_INFO_SB_BAR_PEN
28
Define ADORNMENT_INFO_SB_BAR_BRUSH
29
Define ADORNMENT_INFO_SB_BAR_FONT
30
Define ADORNMENT_INFO_SB_DISPLAY_SCALE
31
Define ADORNMENT_INFO_SB_AUTOOFF_SCALE
32
Define ADORNMENT_INFO_SB_AUTOON_SCALE
33
Define ADORNMENT_INFO_SB_SCALE_STRING
34
Define ADORNMENT_INFO_SB_CARTO_VALUE
35
Define ADORNMENT_INFO_SB_CARTO_STRING
36
'============================================================================
' Codes used to position Adornments relative to mapper
'============================================================================
Define
Define
Define
Define
Define
Define
Define
Define
Define
Define
Define
Define
Define
ADORNMENT_INFO_MAP_POS_TL
0
ADORNMENT_INFO_MAP_POS_TC
1
ADORNMENT_INFO_MAP_POS_TR
2
ADORNMENT_INFO_MAP_POS_CL
3
ADORNMENT_INFO_MAP_POS_CC
4
ADORNMENT_INFO_MAP_POS_CR
5
ADORNMENT_INFO_MAP_POS_BL
6
ADORNMENT_INFO_MAP_POS_BC
7
ADORNMENT_INFO_MAP_POS_BR
8
SCALEBAR_INFO_BARTYPE_CHECKEDBAR
SCALEBAR_INFO_BARTYPE_SOLIDBAR
SCALEBAR_INFO_BARTYPE_LINEBAR
SCALEBAR_INFO_BARTYPE_TICKBAR
0
1
2
3
'============================================================================
' Coordinate system datum id's. These match the id's from mapinfow.prj.
'============================================================================
Define DATUMID_NAD27 62
Define DATUMID_NAD83 74
Define DATUMID_WGS84 104
Reference
859
'============================================================================
' end of MAPBASIC.DEF
'============================================================================
860
MapBasic 12.0
Index
^ (caret)
exponentiation 828
show/hide menu text 207
! (exclamation point) in menus 207
.Net Interoperability
Declare Method statement 258
( (open parenthesis) in menus 206
* (asterisk)
fixed length strings 273
multiplication 828
/ (slash)
division 828
in menus 204, 207
\ (backslash)
in menus 204
integer division 828
& (ampersand)
dialog hotkeys 266
finding street intersections 305
hexadecimal numbers 754
menu hotkeys 207
string concatenation 828
(less than) character
in menus 204
+ (plus) 828
3D maps
changing window settings 668
creating 203
prism maps 221
reading window settings 408
A
Abs( ) function 48
absolute value, Abs( ) function 48
accelerator keys
in dialog boxes 266
in menus 207
Access databases
connection string attributes 561
Acos( ) function 49
Add Cartographic Frame statement 50
Add Column statement 52
Add Designer Frame statement 57
Add Designer Text statement 60
Add Map statement 61
adding
animation layers 62
buttons 66
columns to a table 52, 57, 93
map layers 61
menu items 81, 84
nodes 88, 461, 477
addresses
finding 305
AdornmentInfo( ) function 63
aggregate functions 550, 551
alias variables 273
all-caps text 311
Alter Button statement 65
Alter ButtonPad statement 66
Alter Cartographic Frame statement 71
Alter Control statement 72
Alter Designer Frame statement 74
Alter Designer Text statement 78
Alter MapInfoDialog statement 79
Alter Menu Bar statement 85
Alter Menu Item statement 87
Alter Menu statement 81
Alter Object statement 88
Alter Table statement 93
animation layers
adding 62
removing 518
ApplicationDirectory$( ) function 95
ApplicationName$( ) function 96
arc objects
creating 168
determining length of 441
B
background colors
Brush clause 105
Font clause 311
MakeBrush( ) function 399
MakeFont( ) function 401
bar charts
in graph windows 340
in thematic maps 702
beep statement 102
beginning a transaction
Server Begin Transaction 556
binary file i/o
closing files 127
862
MapBasic 12.0
C
Call statement 110
Calling clause 169, 207
callout lines
map labels 638, 648, 652
text objects 239
CancelButton clause 143
capitalization
lower case 383
mixed case 497
upper case 747
CartesianArea( ) function 111
CartesianBuffer( ) function 112
CartesianConnectObjects( ) function 113
CartesianDistance( ) function 114
CartesianObjectDistance( ) function 115
CartesianObjectLen( ) function 115
CartesianOffset( ) function 116
CartesianOffsetXY( ) function 117
CartesianPerimeter( ) function 118
cartographic legends
adding frames, Add Cartographic Frame statement 50
changing a frame 71
controlling settings 602
creating 175, 182
removing a frame 517
case, converting
LCase$( ) function 383
Proper$( ) function 497
UCase$( ) function 747
Centroid( ) function 119
centroids
displaying 635, 643, 645
setting a region's 88
CentroidX( ) function 120
CentroidY( ) function 121
character codes
character sets 122
converting codes to strings 125
converting strings to codes 98
CharSet clause 122
checkable menu items, creating 204
CheckBox controls 143
checking
dialog box check boxes (custom) 72
dialog box check boxes (standard) 79
menu items 87
ChooseProjection$( ) function 124
Chr$( ) function 125
circle objects
creating 178, 188
determining area of 96
Reference
863
864
MapBasic 12.0
copying (continued)
objects
offset by specified distance 116
tables 137
copying objects
offset by XY values 117
Cos( ) function 164
cosmetic layer
accessing as a table 763
Count( ) aggregate function 550, 551
Create Adornment statement 165
Create Arc statement 168
Create ButtonPad statement 169
Create ButtonPads As Default statement 174
Create Cartographic Legend statement 175
Create Collection statement 180
Create Cutter statement 181
Create Designer Legend statement 182
Create Frame statement 189
Create Grid statement 191
Create Index statement 198
Create Legend statement 199
Create Line statement 201
Create Map statement 202
Create Map3D statement 203
Create Menu Bar statement 210
Create Menu statement 204
Create Multipoint statement 211
Create Object statement 213
Create Pline statement 218
Create Point statement 220
Create PrismMap statement 221
Create Query statement 223
Create Ranges statement 223
Create Rect statement 226
Create Redistricter statement 227
Create Region statement 228
Create Report From Table statement 230
Create RoundRect statement 230
Create Styles statement 231
Create Table statement 233
Create Text statement 239
CreateCircle( ) function 178
CreateLine( ) function 200
CreatePoint( ) function 219
CreateText( ) function 238
Create Adornment statement 165
Create Arc statement 168
Create ButtonPad As Default statement 174
Create ButtonPad statement 169
Create ButtonPads As Default statement 174
Create Collection statement 180
Create Cutter statement 181
Create Designer Legend statement 182
Reference
865
D
data aggregation
combining objects 450, 451
filling a column with data from another table 54,
57
grouping rows 550, 551
data disaggregation
erasing part of an object 455, 457
splitting objects 464
data structures 746
databases
using as tables 506, 512
date
variables 273
date functions
converting numbers to dates 430
converting strings to dates 618, 718
current date 240
date window setting 246
extracting day-of-month 247
extracting day-of-week 755
extracting the month 425
extracting the year 769
formatting based on locale 618
DateTime feature
description 273
DateWindow( ) function 246
Day( ) function 247
DBF files, exporting 293
DDE, acting as client
closing a conversation 254, 255
executing a command 248
initiating a conversation 248
reading data from the server 253, 254
sending data to the server 252
DDE, acting as server
handling execute event 514
handling peek request 515
retrieving execute string 133
DDEExecute statement 248
DDEInitiate( ) function 248
DDEPoke statement 252
DDERequest$( ) function 253
DDETerminate statement 254
DDETerminateAll statement 255
debugging
Continue statement 143
Stop statement 714
decimal separators 262, 318, 618
decision-making
Do Case...End Case statement 277
If...Then statement 345, 346
Declare Function statement 256
866
MapBasic 12.0
disabling (continued)
shortcut menus 204
system menu's Close command 683
discarding changes
to a local table 524
to a remote server 587
distance
spherical calculation 707
units of measure 615
Distance( ) function 276
DLG=1 connect option 561
DLLs
declaring as functions 256
declaring as procedures 260
Do Case...End Case statement 277
Do...Loop statement 279
dockable
ButtonPads, querying current status 108
document conventions 24, 48
DOS commands, executing 534
dot density maps
thematic maps 698
double byte character sets (DBCS)
extracting part of a DBCS string 423
double-clicking in dialog boxes 133, 148
dragging with the mouse
time threshold 616
turning off autoscroll 689
drawing
modes 66
drawing objects on a map
See objects, creating 47
drawing tools, custom 66
Drop Index statement 280
Drop Map statement 281
Drop Table statement 282
duplicating a map 529
DXF files
exporting 293
importing 347, 351
dynamic columns 57
dynamic link libraries. See DLLs 256
E
editable map layers 411, 635
editing objects
See arithmetic functions 47
See math functions 47
edits
determining if there are unsaved edits 732
discarding 524
saving 137
Reference
867
F
Farthest statement 297
Fetch statement 299
file input/output
closing a file 127
determining if file exists 302
end-of-file condition 284
file attributes, reading 301
length of file 395
opening a file 471, 473
reading current position 544
reading data in binary mode 331
reading data in random mode 331
reading data in sequential mode 353, 393
setting current position 545
writing data in binary mode 498
writing data in random mode 498
868
MapBasic 12.0
Reference
functions (continued)
CartesianObjectDistance( ) 115
CartesianObjectLen( ) 115
CartesianOffset( ) 116
CartesianOffsetXY( ) 117
CartesianPerimeter( ) 118
Centroid( ) 119
CentroidX( ) 120
CentroidY( ) 121
ChooseProjection$( ) 124
Chr$( ) 125
ColumnInfo( ) 130
Combine( ) 132
CommandInfo( ) 133
ConnectObjects( ) 142
ControlPointInfo( ) 151
ConvertToPline( ) 156
ConvertToRegion( ) 156
ConvexHull( ) 157
CoordSysName$( ) 161
CoordSysStringToEPSG( ) 162
CoordSysStringToPRJ$( ) 163
CoordSysStringToWKT( ) 163
Cos( ) 164
CreateCircle( ) 178
CreateLine( ) 200
CreatePoint( ) 219
CreateText( ) 238
CurDate( ) 240
CurDateTime( ) 241
CurrentBorderPen( ) 242
CurrentBrush( ) 242
CurrentFont( ) 243
CurrentLinePen( ) 244
CurrentPen( ) 244
CurrentSymbol( ) 245
CurrTime( ) 246
DateWindow( ) 246
Day( ) 247
DDEInitiate( ) 248
DDERequest$( ) 253
DeformatNumber$( ) 262
Distance( ) 276
EOF( ) 284
EOT( ) 285
EPSGToCoordSysString$( ) 286
Erase( ) 287
Err( ) 287
Error$( ) 289
Exp( ) 292
ExtractNodes( ) 296
FileAttr( ) 301
FileExists( ) 302
FileOpenDlg( ) 302
869
functions (continued)
FileSaveAsDlg( ) 304
Fix( ) 310
Format$( ) 315
FormatDate$( ) 317
FormatNumber$( ) 318
FormatTime$( ) 319
FrontWindow( ) 321
GeocodeInfo( ) 328
GetCurrentPath$( ) 332
GetDate( ) 333
GetFolderPath$( ) 334
GetGridCellValue( ) 335
GetMetadata$( ) 336
GetPreferencePath$( ) 336
GetSeamlessSheet( ) 337
GetTime( ) 338
GridTableInfo( ) 342
GroupLayerInfo 342
HomeDirectory$( ) 344
HotLinkInfo( ) 344
Hour( ) 345
InStr( ) 355
Int( ) 356
IntersectNodes( ) 357
IsGridCellNull( ) 357
IsogramInfo( ) 358
IsPenWidthPixels( ) 360
LabelFindByID( ) 362
LabelFindFirst( ) 363
LabelFindNext( ) 364
Labelinfo( ) 364
LabelOverrideInfo( ) 367
LayerControlInfo( ) 371
LayerControlSelectionInfo( ) 371
LayerInfo( ) 372
LayerListInfo( ) 380
LayerStyleInfo( ) 381
LCase$( ) 383
Left$( ) 384
LegendFrameInfo( ) 385
LegendInfo( ) 386
LegendStyleInfo( ) 388
LegendTextFrameInfo( ) 390
Len( ) 390
LibraryServiceInfo( ) 391
Like( ) 392
LocateFile$( ) 394
LOF( ) 395
Log( ) 396
LTrim$( ) 397
MakeBrush( ) 399
MakeCustomSymbol( ) 400
MakeDateTime( ) 401
870
functions (continued)
MakeFont( ) 401
MakeFontSymbol( ) 402
MakePen( ) 403
MakeSymbol( ) 404
Map3DInfo( ) 408
MapperInfo( ) 410
Maximum( ) 415
MBR( ) 416
MenuItemInfoByHandler( ) 417
MenuItemInfoByID( ) 418
MGRSToPoint( ) 421
Mid$( ) 423
MidByte$( ) 423
Minimum( ) 424
Minute( ) 425
Month( ) 425
NumAllWindows( ) 430
NumberToDate( ) 430
NumberToDateTime( ) 431
NumberToTime( ) 431
NumCols( ) 432
NumTables( ) 433
NumWindows( ) 434
ObjectDistance( ) 434
ObjectGeography( ) 435
ObjectInfo( ) 437
ObjectLen( ) 441
ObjectNodeHasM( ) 442
ObjectNodeHasZ( ) 443
ObjectNodeM( ) 444
ObjectNodeX( ) 445
ObjectNodeY( ) 446
ObjectNodeZ( ) 447
Offset( ) 466
OffsetXY( ) 467
Overlap( ) 476
OverlayNodes( ) 477
PathToDirectory$( ) 479
PathToFileName$( ) 479
PathToTableName$( ) 480
PenWidthToPoints( ) 484
Perimeter( ) 484
PointsToPenWidth( ) 486
PointToMGRS$( ) 486
PointToUSNG$( ) 488
PrismMapInfo( ) 492
ProgramDirectory$( ) 494
Proper$( ) 497
ProportionOverlap( ) 498
RasterTableInfo( ) 500
ReadControlValue( ) 502
RegionInfo( ) 502
RemoteQueryHandler( ) 515
MapBasic 12.0
functions (continued)
RGB( ) 522
Right$( ) 523
Rnd( ) 524
Rotate( ) 525
RotateAtPoint( ) 526
Round( ) 527
RTrim$( ) 528
SearchInfo( ) 539
SearchPoint( ) 542
SearchRect( ) 543
Second( ) 544
Seek( ) 544
SelectionInfo( ) 555
Server_ColumnInfo( ) 559
Server_Connect( ) 561
Server_ConnectInfo( ) 568
Server_DriverInfo( ) 576
Server_EOT( ) 577
Server_Execute( ) 577
Server_GetODBCHConn( ) 580
Server_GetODBCHStmt( ) 581
Server_NumCols( ) 584
Server_NumDrivers( ) 585
SessionInfo( ) 593
Sgn( ) 692
Sin( ) 704
Space( ) 705
SphericalArea( ) 705
SphericalConnectObjects( ) 706
SphericalDistance( ) 707
SphericalObjectDistance( ) 708
SphericalObjectLen( ) 709
SphericalOffset( ) 709
SphericalOffsetXY( ) 710
SphericalPerimeter( ) 711
Sqr( ) 712
Str$( ) 715
String$( ) 716
StringCompare( ) 717
StringCompareIntl( ) 717
StringToDate( ) 718
StringToDateTime( ) 719
StringToTime( ) 720
StyleAttr( ) 721
StyleOverrideInfo( ) 723
SystemInfo( ) 730
TableInfo( ) 732
TableListInfo( ) 737
TableListSelectionInfo( ) 738
Tan( ) 739
TempFileName$( ) 739
TextSize( ) 741
Time( ) 741
Reference
functions (continued)
Timer( ) 742
TriggerControl( ) 744
TrueFileName$( ) 745
UBound( ) 747
UCase$( ) 747
UnitAbbr$( ) 749
UnitName$( ) 750
Val( ) 754
Weekday( ) 755
WindowID( ) 760
WindowInfo( ) 762
WKTToCoordSysString$( ) 757
Year( ) 769
functions, creating
Declare Function statement 256
Exit Function statement 291
Function....End Function statement 322
G
gaps
checking in regions 448
cleaning 450
snapping nodes 462
Geocode statement 324
GeocodeInfo( ) function 328
geographic
operators 553
geographic calculations
area of object 96
area of overlap 97
distance 276
length of object 441
perimeter of object 484
See also objects, querying
See objects, querying 47
geographic operators 829
Get statement 331
GetCurrentPath$( ) function 332
GetDate( ) function 333
GetFolderPath$( ) function 334
GetGridCellValue( ) function 335
GetMetadata$( ) function 336
GetPreferencePath$( ) function 336
GetSeamlessSheet( ) function 337
GetTime( ) function 338
Global statement 339
GML files, importing 347, 351
Goto statement 340
GPS applications 62
Graph statement 340
871
Graph windows
closing 128
determining the name of the table 763
modifying 619, 683, 691
opening 333, 334, 340
great circle distance 276
grid
appearance description 195
cells, get information 357
change path location 672
convert to TAB 506
create 191
create with IDW Interpolator values 195
find cell value 335
find path location 332
get layer type 372
layer properties and appearance 635
layer style overrides 645
path location preference 336
set as read-only for TIN and IDW 198
surface theme description 193
tables, adding relief shade information 513
tables, get information 342, 500
templates description 195
translucency override 643
grid surface maps
in thematic maps 191, 193
modifying 630, 661
GridTableInfo( ) function 342
Group By clause 550, 553
group layers 656
GroupBox controls 147
GroupLayerInfo function 342
H
halo text 311
halting another application 740
handlers, assigning to menu items 204
hardware platform, determining 730
help messages
button tooltips 66, 169
status bar messages 66, 169
Help window
closing 128
modifying 683, 691
opening 475, 683, 691
hexadecimal numbers 754
hiding
ButtonPads 66
dialog box controls (custom) 72
dialog box controls (standard) 79
menu bar 416
872
hiding (continued)
progress bar dialog boxes 674
screen activity 616
hierarchical menus
Alter Menu statement 82
Create Menu statement 204
HomeDirectory$( ) function 344
HotLink tool
querying object attributes 133
HotLinkInfo( ) function 344
HotLinks 662
adding 665
modifying 666
querying 372
removing 667
reordering 667
Hour( ) function 345
HTTP and FTP Library
MICloseContent() procedure 773
MICloseFtpConnection() procedure 773
MICloseFtpFileFind() procedure 774
MICloseHttpConnection() procedure 774
MICloseHttpFile() procedure 775
MICloseSession() procedure 775
MICreateSession() function 776
MICreateSessionFull() function 776
MIErrorDlg() function 778
MIFindFtpFile() function 779
MIFindNextFtpFile() function 780
MIGetContent() function 781
MIGetContentBuffer() function 781
MIGetContentLen() function 782
MIGetContentString() function 782
MIGetContentToFile() function 783
MIGetContentType() function 784
MIGetCurrent FtpDirectory() function 784
MIGetErrorCode() function 785
MIGetErrorMessage() function 786
MIGetFileURL() function 786
MIGetFtpConnection() function 787
MIGetFtpFile() function 788
MIGetFtpFileFind() function 789
MIGetFtpFileName() procedure 790
MIGetHttpConnection() function 791
MIIsFtpDirectory() function 791
MIIsFtpDots() function 792
MIOpenRequest() function 793
MIOpenRequestFull() function 794
MIParseURL() function 795
MIPutFtpFile() function 796
MIQueryInfo() function 797
MIQueryInfoStatusCode() function 798
MISaveContent() function 799
MISendRequest() function 800
MapBasic 12.0
I
iconizing MapInfo
Set Window statement 683
suppressing progress bars 674
icons for ButtonPads 66
identifiers, defining 261
IDW Interpolator 195
If...Then statement 345, 346
Import statement 347
Include statement 352
indexed columns
creating an index 198
deleting an index 280
infinite loops, avoiding 623
Info tool
closing Info window 128
modifying Info window 683, 691
opening Info window 475
setting to read-only 690
setting which data displays 690
initializing variables 275
Input # statement 353
input/output 47
Insert statement 354
inserting
columns in a table 52, 57, 93
nodes in an object 88
rows in a table 354
InStr( ) function 355
Int( ) function 356
integer division 828
integer variables 273
integrated mapping
managing legends 199
reparenting dialog boxes 597
reparenting document windows 669
international
character sets 122
formatting 618
interpreting strings as commands 529
interrupting the selection 546
intersection of objects
Create Object statement 213
Intersects operator 553
Reference
J
joining tables 548
JPEG file interchange format (*.jpg)
creating 537
K
keys, metadata 419, 420
keywords 274, 550
Kill statement 361
L
LabelFindByID( ) function 362
LabelFindFirst( ) function 363
LabelFindNext( ) function 364
Labelinfo( ) function 364
LabelOverrideInfo( ) funtion 367
labels
in dialog boxes 155
in programs 340
on maps 101, 362, 363, 364, 638
reading label expressions 372
launching other applications
Run Application statement 528
Run Program statement 533
LayerControlSelectionInfo( ) function 371
LayerInfo( ) function 371, 372
LayerListInfo( ) function 380
layers
adding 61
cosmetic 763
group 656
groups 658, 659
modifying settings 630, 661
reading settings 372
removing 518
thematic maps 678, 692, 702
LayerStyleInfo( ) funtion 381
Layout statement 382
Layout windows
accessing as tables 763
873
874
M
Main procedure 398
MakeBrush( ) function 399
MakeCustomSymbol( ) function 400
MakeDateTime( ) function 401
MakeFont( ) function 401
MakeFontSymbol( ) function 402
MakePen( ) function 403
MakeSymbol( ) function 404
map projections
changing a table's projection 137
copying from a table or window 158, 161
querying a table's CoordSys 735
querying a window's CoordSys 412
setting 660
setting the current MapBasic CoordSys 609
map scale
determining in map windows 411
displaying 634
Map statement 405
Map windows
adding map layers 61
clipping 631
closing 128
controlling redrawing 61, 616, 631
creating thematic layers 692, 702
duplicating 529
handling window-changed event 133, 759
labeling 638
modifying 630, 661, 683, 691
modifying thematic layers 678
opening 405
prism 221
MapBasic 12.0
Reference
menus, customizing
adding hierarchical menus 82
adding menu items 81, 84
altering menu items 87
creating checkable menu items 204
creating new menus 204
disabling shortcut menus 204
querying menu item status 417, 418
redefining the menu bar 85, 210
removing menu items 81, 84
showing/hiding the menu bar 416
merging objects. See combining objects 450
messages
displaying in a Note dialog box 429
displaying on the status bar 713
opening the Message window 475
printing to the Message window 489
metadata
code example 421
keys 419, 420
managing in tables 419
reading keys 336
Metadata statement 419
metric units
area 598
distance 615
MGRSToPoint( ) function 421
MICloseContent( ) procedure 773
MICloseFtpConnection( ) procedure 773
MICloseFtpFileFind( ) procedure 774
MICloseHttpConnection( ) procedure 774
MICloseHttpFile( ) procedure 775
MICloseSession( ) procedure 775
MICreateSession( ) function 776
MICreateSessionFull( ) function 776
Microsoft Access tables
connection string attributes 561
Mid$( ) function 423
MidByte$( ) function 423
MIErrorDlg( ) function 778
MIF files
exporting 293
importing 347, 351
MIFindFtpFile( ) function 779
MIFindNextFtpFile( ) function 780
MIGetContent( ) function 781
MIGetContentBuffer( ) function 781
MIGetContentLen( ) function 782
MIGetContentString( ) function 782
MIGetContentToFile( ) function 783
MIGetContentType( ) function 784
MIGetCurrentFtpDirectory( ) function 784
MIGetErrorCode( ) function 785
MIGetErrorMessage( ) function 786
875
876
N
natural break
thematic ranges 223
Nearest statement 426
network file sharing 617
nodes
adding 88, 461, 477
displaying 635, 643, 645
extracting a range of nodes from an object 296
maximum number per object 218, 229
querying number of nodes 438
querying x/y coordinates 445, 446
removing 88
Noselect keyword 550
Note statement 429
null handling 579
NumAllWindows( ) function 430
number of characters in a string 390
NumberToDate( ) function 430
NumberToDateTime( ) function 431
NumberToTime( ) funtion 431
NumCols( ) function 432
numeric operators 828
NumTables( ) function 433
NumWindows( ) function 434
MapBasic 12.0
O
object variables 273
ObjectDistance( ) function 434
ObjectGeography( ) function 435
ObjectInfo( ) function 437
ObjectLen( ) function 441
ObjectNodeHasM( ) function 442
ObjectNodeHasZ( ) function 443
ObjectNodeM( ) function 444
ObjectNodeX( ) function 445
ObjectNodeY( ) function 446
ObjectNodeZ( ) function 447
objects
moving within input table 458
Objects Check statement 448
Objects Clean statement 450
Objects Combine statement 451
Objects Disaggregate statement 452
Objects Enclose statement 454
Objects Erase statement 455
Objects Intersect statement 457
Objects Move statement 458
Objects Offset statement 459
Objects Overlay statement 461
Objects Pline statement 461
Objects Snap statement 462
Objects Split statement 464
objects, copying
offset by distance 466, 467
to offset location 459
objects, creating
arcs 168
by buffering 107, 213, 217
by combining objects 132
by intersecting objects 476
circles 178, 188
convex hull 213
ellipses 178, 188
frames 189
lines 200, 201
map labels 101
multipoint 211
points 219, 220
polylines 218
rectangles 226
regions 228, 230
rounded rectangles 230
text 238, 239
voronoi polygons 213
objects, modifying
adding nodes 88, 461
combining 132, 451
converting to polylines 156
Reference
877
operators
automatic type conversions 831
summary of 827
optimizing performance
animation layers 61, 62
screen updates 616
table editing 680
Oracle
databases, connection string attributes 562
Oracle Spatial databases
connection string attributes 562, 564
Order By clause
sorting rows 553
ordering layers 658, 659
Overlap( ) function 476
overlaps
checking in regions 448
cleaning 450
snapping nodes 462
OverlayNodes( ) function 477
P
Pack Table statement 478
page layout, opening 382
paper units of measure 671
papersize attribute 764
parallel labels 638, 640, 648, 650, 654
parent windows
reparenting dialog boxes 597
reparenting document windows 669
partialsegments option 638, 648, 654
PathToDirectory$( ) function 479
PathToFileName$( ) function 479
PathToTableName$( ) function 480
pattern matching 392
peek requests 515
Pen clause 481
pen styles
creating 403
modifying an object's style 88
Pen clause defined 481
querying an object's style 437
querying parts of 719, 720, 721
reading current border style 242
reading current line style 244
reading current style 244
setting current style 679
pen variables 273
PenPicker controls 150
PenWidthToPoints( ) function 484
per-object styles 571
percent complete dialog box 495
878
performance, improving
animation layers 61, 62
screen updates 616
table editing 680
Perimeter( ) function 484
PICT files
creating 537
importing 347, 351
pie charts
in graph windows 333, 334, 340
in thematic maps 701
platform, determining 730
PNG files
creating 537
point objects
creating 219, 220
modifying 88
querying the symbol style 437
storing in a new row 354
storing in an existing row 751
point styles. See symbol styles 400
PointsToPenWidth( ) function 486
PointToMGRS$( ) function 486
PointToUSNG$( ) function 488
polygon draw mode 70
polyline objects
adding/removing nodes 88
Cartesian length of 115
converting objects to polylines 156
creating 218
creating cutter objects 181
determining length of 441
extracting a range of nodes from 296
modifying the pen style 88
querying the pen style 437
storing in a new row 354
storing in an existing row 751
PopupMenu controls 152
positioning the row cursor 299, 301
precedence of operators 830
Preferences dialog box(es) 532
preventing user from closing windows 683
Print # statement 490
Print statement 489
printer settings 683, 691
overriding default printer 690
printing
attributes 765
controlling the printer 690
PrintWin statement 491
prism maps
creating 221
properties 492
setting 673
MapBasic 12.0
Q
quantiled ranges 223
Reference
R
RadioGroup controls 154
random file i/o
closing files 127
opening files 471
reading data 331
writing data 498
random numbers
Randomize statement 499
Rnd( ) function 524
Randomize statement 499
range of values 77, 187
ranged thematic maps 223, 693
raster
translucency override 643
RasterTableInfo( ) function 500
ReadControlValue( ) function 502
realtime applications 61
rectangle objects
Cartesian area of 111
Cartesian perimeter of 118
creating 226, 230
determining area of 96
determining perimeter of 484
modifying 88
querying the pen or brush style 437
storing in a new row 354
storing in an existing row 751
ReDim statement 505
Redistricting windows
closing 128
modifying 675, 683, 691
opening 227
region objects
adding/removing nodes 88
Cartesian area of 111
Cartesian perimeter of 118
checking for data errors 448
converting objects to regions 156
creating 228, 230
creating convex hull objects 157
determining area of 96
determining perimeter of 484
extracting a range of nodes from 296
modifying the pen or brush style 88
querying the pen or brush style 437
returning a buffer region 112
setting a centroid 88
storing in a new row 354
storing in an existing row 751
regional settings 618
RegionInfo( ) function 502
Register Table statement 506
879
880
returning (continued)
a point size for a pen width
PenWidthToPoints( ) function 484
ODBC connection handle
Server_GetodbcHConn( ) function 580
ODBC statement handle
Server_GetodbcHStmt( ) function 581
pen width units
IsPenWidthPixels( ) function 360
RGB( ) function 522
Right$( ) function 523
Rnd( ) function 524
Rollback statement 524
Rotate( ) function 525
RotateAtPoint( ) function 526
rotated
map labels 638, 640, 648, 650, 654
symbols 402, 728
Round( ) function 527
rounded rectangle objects
Cartesian area of 111
Cartesian perimeter of 118
creating 230
modifying 88
querying the pen or brush style 437
storing in a new row 354
storing in an existing row 751
rounding off a number
Fix( ) function 310
Format$( ) function 315
Int( ) function 356
Round( ) function 527
RowID
after Find operations 133
with SelChangedHandler 133
rows in a Browser, positioning 599
rows in a table
deleting rows 263
end-of-table condition 285
inserting new rows 354
packing (purging deleted rows) 478
positioning the row cursor 299, 301
selecting rows that satisfy criteria 548
updating existing rows 751
RPC (Remote Procedure Calls) 260
RTrim$( ) function 528
Ruler tool
closing Ruler window 128
modifying Ruler window 683, 691
opening Ruler window 475
Run Application statement 528
Run Command statement 529
Run Menu Command statement 531
Run Program statement 533
MapBasic 12.0
S
Save File statement 534
Save MWS statement 535
Save Window statement 537
Save Workspace statement 539
saving
changes to a table 137
linked tables 137
work to the database, Server Commit 561
scale bar 63
scale of a map
determining 411
displaying 634
scope of variables
global 339
local 272
scroll bars
showing/hiding 689
scrolling
automatically 689
seamless tables
determine if table is seamless 735
prompt user to choose a sheet 336, 337, 338
turn seamless behavior on/off 680
SearchInfo( ) function 539
searching for map objects
at a point 542
processing search results 539
within a rectangle 543
SearchPoint( ) function 542
SearchRect( ) function 543
Second( ) function 544
seconds, elapsed 742
See file input/output 47
Seek statement 545
Seek( ) function 544
SelChangedHandler procedure 545
Select statement 546
selectable map layers 635
selection
handling selection-changed event 133, 545
interrupted by Esc key 546
querying current selection 555
Select statement 546
SelectionInfo( ) function 555
self-intersections
checking in regions 448
sequential file i/o
closing files 127
opening files 471
Reference
881
882
MapBasic 12.0
statements (continued)
Create Index 198
Create Legend 199
Create Map 202
Create Map3D 203
Create Menu 204
Create Menu Bar 210
Create MultiPoint 211
Create Object 213
Create Pline 218
Create Point 220
Create PrismMap 221
Create Query 223
Create Ranges 223
Create Rect 226
Create Redistricter 227
Create Region 228
Create Report From Table 230
Create RoundRect 230
Create Styles 231
Create Table 233
Create Text 239
DDEExecute 248
DDETerminate 254
DDETerminate All 255
Declare Function 256
Declare Method 258
Declare Sub 260
Define 261
Delete 263
Dialog 264
Dialog Preserve 270
Dialog Remove 271
Dim 272
Do Case...End Case 277
Do...Loop 279
Drop Index 280
Drop Map 281
Drop Table 282
End MapInfo 283
End Program 283
Error 289
Exit Do 290
Exit For 290
Exit Function 291
Exit Sub 292
Export 293
Farthest 297
Fetch 299
File Using 309
Find 305
FME Refresh Table 321
For...Next 313
Function...End 322
Reference
statements (continued)
Geocode 324
Get 331
Global 339
Goto 340
Graph 340
If...Then 346
Import 347
Include 352
Input # 353
Insert 354
Kill 361
Layout 382
Line Input 393
Map 405
Menu Bar 416
Metadata 419
Nearest 426
Note 429
Objects Check 448
Objects Clean 450
Objects Combine 451
Objects Disaggregate 452
Objects Enclose 454
Objects Erase 455
Objects Intersect 457
Objects Move 458
Objects Offset 459
Objects Overlay 461
Objects Pline 461
Objects Snap 462
Objects Split 464
OnError 468
Open Connection 469
Open File 471
Open Report 473
Open Table 473
Open Window 475
Pack Table 478
Print 489
Print # 490
PrintWin 491
ProgressBar 495
Put 498
Randomize 499
ReDim 505
Register Table 506
Relief Shade 513
Reload Symbols 513
Remove Cartographic Frame 517
Remove Designer Frame 517
Remove Map 518
Rename File 519
Rollback 524
883
statements (continued)
Run Application 528
Run Command 529
Run Menu Command 531
Run Program 533
Save File 534
Save MWS 535
Save Window 537
Save Workspace 539
Select 546
Selrver Begin Transaction 556
Serve Create Map 569
Server Bind Column 557
Server Close 558
Server Commit 561
Server Create Table 572
Server Create Workspace 574
Server Disconnect 575
Server Fetch 579
Server Link Table 582
Server Refresh 585
Server Remove Workspace 586
Server Rollback 587
Server Set Map 587
Server Versioning 588
Server Workspace Merge 590
Server Workspace Refresh 591
Set Adornment 594
Set Application Window 597
Set Area Units 598
Set Browse 599
Set Buffer Version 601
Set Cartographic Legend 602
Set Combine Version 603
Set Command Info 604
Set Connection Geocode 605
Set Connection Isogram 607
Set CoordSys 609
Set Date Window( ) 610
Set Datum Version 611
Set Designer Legend 612
Set Digitizer 613
Set Distance Units 615
Set Drag Threshold 616
Set Event Processing 616
Set File Timeout 617
Set Format 618
Set Graph 619
Set Handler 623
Set Layout 624
Set Legend 626
Set LibraryServiceInfo 629
Set Map 630
Set Map3D 668
884
statements (continued)
Set Next Document 669
Set Paper Units 671
Set Path 672
Set PrismMap 673
Set ProgressBars 674
Set Redistricter 675
Set Resolution 677
Set Shade 678
Set Style 679
Set Table 680
Set Target 682
Set Window 683
Shade 692
StatusBar 713
Stop 714
Sub...End Sub 725
Terminate Application 740
Type 746
UnDim 748
Unlink 750
Update 751
Update Window 752
WFS Refresh Table 756
While...Wend 758
WinFocusChangedHandler 767
Write # 768
StaticText controls 155
statistical calculations
average 54, 550, 551
count 54, 550, 551
min/max 54, 550, 551
quantile 223
standard deviation 223
sum 54, 550, 551
weighted average 54, 551, 552
Statistics window
closing 128
modifying 683, 691
opening 475
Status bar help 169
Status Bar help 66
StatusBar statement 713
Stop statement 714
Str$( ) function 715
street address, finding 305
string concatenation
& operator 828
+ operator 828
string functions
capitalization 383, 497, 747
comparison 717
converting codes to strings 125
converting strings to codes 98
MapBasic 12.0
Reference
T
TAB files, storing metadata in 419
tab order 267
table names
determining _ in Browse or Graph window 763
determining from file 480
determining table name from number 732
special names for Cosmetic layers 763
special names for Layout windows 763
table structure
3DMap 203
adding/removing columns 93
determining how many columns 432, 732
making a table mappable 202
making an ODBC table mappable 569
TableInfo( ) function 732
TableListInfo( ) function 737
TableListSelectionInfo( ) function 738
tables
CoordSys 161
tables, closing
Close All statement 126
Close Table statement 127
tables, copying 137
tables, creating
creating a new table 233
importing a file 347, 351
on remote databases 572
using a spreadsheet or database 506, 512
tables, deleting 282
tables, importing 347, 351
tables, modifying
adding columns 52, 57, 93
adding metadata 419
adding rows 354
creating an index 198
deleting a table's objects 281
deleting an index 280
deleting columns 93
deleting rows or objects 263
discarding changes 524
optimizing edit operations 680
packing 478
renaming 520
saving changes 137
setting a map's default view 638
setting a map's projection 137
885
886
U
UBound( ) function 747
UCase$( ) function 747
unchecking
dialog box check boxes (custom) 72
dialog box check boxes (standard) 79
menu items 87
underlined text 311
UnDim statement 748
undo system, disabling 680
UnitAbbr$( ) function 749
United States National Grid 488, 753
UnitName$( ) function 750
units
CoordSys Layout 160
units of measure
abbreviated names 749
area 598
distance 615
full names 750
paper 671
Unlink statement 750
unselecting 127
Update statement 751
Update Window statement 752
upper case, converting to 747
MapBasic 12.0
URL 629
URL clause 753
USNGToPoint( ) function 753
V
Val( ) function 754
value range 77, 187
variable length strings 273
variables
arrays 274, 505, 747
custom types 746
global variables 339
initializing 275
list of types 272
local variables 272
reading another application's variables 339
restrictions on names 274
strings variables 274
undefining 748
version number
.MBX version 731
MapInfo version 731
voronoi polygons
Create Object statement 213
W
Weekday( ) function 755
weighted averages 551, 552
Add Column statement 54
WFS Refresh Table statement 756
While...Wend statement 758
wildcard
matching 392
WinChangedHandler procedure 759
WinClosedHandler procedure 760
WindowID( ) function 760
WindowInfo( ) function 762
windows
CoordSys 161
Help 689
labeling in Map 638
Map and Layout syntax 689
Open Window statement 475
windows operating system, 16- v. 32-bit 731
windows, closing
Close Window statement 128
preventing user from closing windows 683
windows, modifying
adding map layers 61
browser windows 599
forcing windows to redraw 752
Reference
X
XCMDs 260
XFCNs 256
XLS files, opening 506, 512
XML Library
MIXmlAttributeListDestroy( ) procedure 807
MIXmlDocumentCreate( ) function 807
MIXmlDocumentDestroy( ) procedure 808
MIXmlDocumentGetNamespaces( ) function 808
MIXmlDocumentGetRootNode( ) function 809
MIXmlDocumentLoad( ) function 809
MIXmlDocumentLoadXML( ) function 810
MIXmlDocumentLoadXMLString( ) function 811
MIXmlDocumentSetProperty( ) function 812
MIXmlGetAttributeList( ) function 813
887
888
Y
Year( ) function 769
MapBasic 12.0