% @(#) $Id: tutorial.tex,v 1.119 2006/04/08 20:31:27 simoc Exp $

\section{Tutorial and Cookbook}

The following examples demonstrate how to use Mapyrus.  Each example is also
included as a file in the \texttt{userdoc} subdirectory.  All example files
have file suffix \texttt{.mapyrus}.  This suffix is not required but makes
identification of files that are to be interpreted by Mapyrus easier.

If the Ghostscript program or a printer is not available, then change the
\texttt{"eps"} arguments in \texttt{newpage} commands in examples to
\texttt{"screen"}
to display the output in a window on the screen instead.

\subsection{First Step}

Enter the following lines into a text file named \texttt{first.mapyrus}.

\verbatiminput{tutorialfirst1.mapyrus}

Each line in the file is a command for Mapyrus.  First, output is set to
a 30mm square Encapsulated PostScript format file named
\texttt{tutorialfirst1.eps} with the \texttt{newpage} command, then a
line is drawn with the given color and linestyle.

Open a terminal window (known as an "MS-DOS Prompt" in MicroSoft Windows)
and run Mapyrus using following command to execute the
commands in the file \texttt{first.mapyrus}.

\begin{alltt}
java -classpath \textit{mapyrus-dir}/mapyrus.jar org.mapyrus.Mapyrus first.mapyrus
\end{alltt}

When Mapyrus reaches the end of the file \texttt{first.mapyrus}
the output file \texttt{tutorialfirst1.eps} is saved and Mapyrus exits.
When the PostScript file is then printed, it appears as in
Figure \ref{tutorialfirst1}.

\begin{figure}[htb]
\includegraphics{tutorialfirst1.eps}
\caption{First Step}
\label{tutorialfirst1}
\end{figure}

To perform these steps on a MicroSoft Windows machine where the
the ZIP file containing Mapyrus has been unpacked in directory
\texttt{C:\textbackslash{}temp},
the following commands are used:

\begin{alltt}
C:\textbackslash{}>cd temp

C:\textbackslash{}temp>dir /b *.jar \hspace{30pt} \textit{-- Check that Mapyrus is installed here}
mapyrus.jar

C:\textbackslash{}temp>notepad first.mapyrus \hspace{30pt} \textit{-- Create file with text editor}

C:\textbackslash{}temp>java -classpath mapyrus.jar org.mapyrus.Mapyrus first.mapyrus

C:\textbackslash{}temp>gswin32 tutorialfirst1.eps \hspace{30pt} \textit{-- View output with GhostScript}
\end{alltt}

\subsection{Second Step}

Change the file \texttt{first.mapyrus} to contain the following lines,
then run Mapyrus again to create a new output file.

\verbatiminput{tutorialfirst2.mapyrus}

In this example, color is set as a hex value instead of a name,
a rectangle is defined with the \texttt{box} command
and the \texttt{fill} command is used to
flood fill it.
The characters on lines following a hash (\texttt{\#}) character that
is not enclosed in quotes are ignored by Mapyrus.
Figure \ref{tutorialfirst2} shows the output of these commands.

\begin{figure}[htb]
\includegraphics{tutorialfirst2.eps}
\caption{Second Step}
\label{tutorialfirst2}
\end{figure}

Change the file \texttt{first.mapyrus} to contain the following lines.

\verbatiminput{tutorialfirst3.mapyrus}

This example demonstrates drawing circular arcs,
giving the direction (a positive value for clockwise and a negative
value for anti-clockwise), center point and end point,
drawing line segments relative to the last point in the path
with the \texttt{rdraw} command,
closing the path back to the starting point
with the \texttt{closepath} command and
yet another way of defining color.
After being filled, the path remains and is used again to draw the outline
of the shape.
To clear the path before drawing another shape the
\texttt{clearpath}
command is used.
The second shape contains an island (or hole).  When a shape is
self-intersecting or contains islands, the winding rule is
used for determining which areas get filled.
The output of these commands is shown in Figure \ref{tutorialfirst3}.

\begin{figure}[htb]
\includegraphics{tutorialfirst3.eps}
\caption{Third Step}
\label{tutorialfirst3}
\end{figure}

Change the file \texttt{first.mapyrus} to contain the following lines.

\verbatiminput{tutorialfirst4.mapyrus}

This example demonstrates setting the page size in
screen pixels and setting a scale so that coordinates
are also given as pixels.
Various shapes
are drawn using \texttt{circle},
\texttt{hexagon}, \texttt{triangle}, \texttt{star},
\texttt{wedge}, \texttt{ellipse}, \texttt{bezier},
\texttt{roundedbox}, \texttt{box3d},
\texttt{pentagon}, \texttt{spiral},
\texttt{cylinder}, \texttt{raindrop}
\texttt{sinewave} and \texttt{chessboard}
commands.
The output of these commands is shown in Figure \ref{tutorialfirst4}.

\begin{figure}[htb]
\includegraphics{tutorialfirst4.eps}
\caption{Fourth Step}
\label{tutorialfirst4}
\end{figure}

\subsection{Using Variables}

Use variables and conditional tests to vary the appearance
of the display.
Variables named \texttt{c1} and \texttt{c2} are used in the
following example.  The variable
\texttt{Mapyrus.page.width}
is set by Mapyrus automatically.
The output of this example is shown in Figure \ref{tutorialvar1}.

\verbatiminput{tutorialvar1.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialvar1.eps}
\caption{Variables And Loops}
\label{tutorialvar1}
\end{figure}

The second example demonstrates the use of the
\texttt{length} and \texttt{substr}
functions
and stepping through a string one element at a time.
The output of this example is shown in Figure \ref{tutorialvar2}.

\verbatiminput{tutorialvar2.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialvar2.eps}
\caption{Variables And Functions}
\label{tutorialvar2}
\end{figure}


\subsection{Building Procedures}

Store frequently used sequences of commands in a procedure.
A procedure has a unique name, takes a fixed number of arguments and
may be called from any place where a command is expected.

Private variables in a procedure are defined with the 
\texttt{local} command.

When a procedure is called, the graphics state
is saved (see page \pageref{graphicsstate}),
the commands for the procedure are executed and then the
graphics state is restored before returning.

The following example shows a simple procedure named \texttt{trail}.
The output of this example is shown in Figure \ref{tutorialprocedures1}.

\verbatiminput{tutorialprocedures1.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialprocedures1.eps}
\caption{Calling Procedures}
\label{tutorialprocedures1}
\end{figure}

If the current path contains only points added with \texttt{move}
commands when a procedure is called, then the
procedure is called once for each point with the origin
moved to that point.  This permits several symbols to be drawn
easily and is demonstrated in the following example.  The 
output of this example is shown in Figure \ref{tutorialprocedures2}.

\verbatiminput{tutorialprocedures2.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialprocedures2.eps}
\caption{Procedures And Move Points}
\label{tutorialprocedures2}
\end{figure}


Put frequently used procedures in a separate file and use an
\texttt{include}
line to include it in other files.  When this is done for the
previous example, the procedure is put in a file.

\verbatiminput{tutorialprocedures3.mapyrus}

and the file containing the commands to execute

\verbatiminput{tutorialprocedures4.mapyrus}

\subsection{Displaying Lines}

Simple solid line styles or dashed line styles
are set with the
\texttt{linestyle} command.  More complex line styles are built using
symbols repeated along a line or combinations of linestyles, plotted
on top of each other.

To draw a line with repeated symbols, use the
\texttt{samplepath}
command to replace the path with evenly spaced sample points and
then call a procedure to draw a symbol at each sample point.
The following example demonstrates this,
with the output shown in Figure \ref{tutoriallines1}.

\verbatiminput{tutoriallines1.mapyrus}

\begin{figure}[htb]
\includegraphics{tutoriallines1.eps}
\caption{Repeating Symbols Along A Line}
\label{tutoriallines1}
\end{figure}

To vary the symbols that are drawn along the line, use a variable
to count the number of symbols along the line and a conditional
test to draw different symbols at different positions along the line.
The following example demonstrates this,
with the output shown in Figure \ref{tutoriallines2}.

\verbatiminput{tutoriallines2.mapyrus}

\begin{figure}[htb]
\includegraphics{tutoriallines2.eps}
\caption{Varying Repeated Symbols Along A Line}
\label{tutoriallines2}
\end{figure}

The next example demonstrates
combining solid and dashed linestyles.
For best results display all lines with a solid linestyle,
then display all lines again with a dashed linestyle.
The output of this example is shown in Figure \ref{tutoriallines3}.

\verbatiminput{tutoriallines3.mapyrus}

\begin{figure}[htb]
\includegraphics{tutoriallines3.eps}
\caption{Combining Solid And Dashed Linestyles}
\label{tutoriallines3}
\end{figure}

The following example demonstrates combining thick and
thin linestyles and symbols at sampled points.
For best results display all lines with a thick linestyle,
then display all lines again with a thin linestyle.
The output of this example is shown in Figure \ref{tutoriallines4}.

\verbatiminput{tutoriallines4.mapyrus}

\begin{figure}[htb]
\includegraphics{tutoriallines4.eps}
\caption{Combining Several Linestyles}
\label{tutoriallines4}
\end{figure}

The following two examples demonstrate creating sample points
from the path to generate further line styles,
with the output shown in Figures \ref{tutoriallines5}
and \ref{tutoriallines6}.

\verbatiminput{tutoriallines5.mapyrus}

\begin{figure}[htb]
\includegraphics{tutoriallines5.eps}
\caption{Linestyle Using Begin And End Points}
\label{tutoriallines5}
\end{figure}

\verbatiminput{tutoriallines6.mapyrus}

\begin{figure}[htb]
\includegraphics{tutoriallines6.eps}
\caption{Linestyle Using Sample Points}
\label{tutoriallines6}
\end{figure}

The next example demonstrates using the \texttt{parallelpath}
command to display parallel lines following the original path,
with the output shown in Figure \ref{tutoriallines7}.

\verbatiminput{tutoriallines7.mapyrus}

\begin{figure}[htb]
\includegraphics{tutoriallines7.eps}
\caption{Parallel Linestyle}
\label{tutoriallines7}
\end{figure}

The next example demonstrates using the \texttt{selectpath}
command to select short sections at the start and end of
the path and displaying them in different colors to indicate
the polarity of the connection between two points.
The output of this example is shown in Figure \ref{tutoriallines8}.

\verbatiminput{tutoriallines8.mapyrus}

\begin{figure}[htb]
\includegraphics{tutoriallines8.eps}
\caption{Selecting Parts Of Path}
\label{tutoriallines8}
\end{figure}

The \texttt{selectpath} command is also useful for displaying lines that stop
short of the start and end points of the path, and for displaying
lines that have thicker and thinner sections in the middle, or
at the ends of the lines.

The next example demonstrates combining the \texttt{selectpath}
and \texttt{samplepath} commands to display a different linestyle
in the middle of each line.
The output of this example is shown in Figure \ref{tutoriallines9}.

\verbatiminput{tutoriallines9.mapyrus}

\begin{figure}[htb]
\includegraphics{tutoriallines9.eps}
\caption{Selecting and Sampling Path}
\label{tutoriallines9}
\end{figure}

Use the \texttt{sinewave} command to display a curved line between
two points instead of a straight line.

This is demonstrated in the following example,
with the output shown in Figure \ref{tutoriallines10}.

\verbatiminput{tutoriallines10.mapyrus}

\begin{figure}[htb]
\includegraphics{tutoriallines10.eps}
\caption{Sine Wave Curves}
\label{tutoriallines10}
\end{figure}

\subsection{Displaying Polygons}

Polygon outlines are drawn with the \texttt{stroke}
command and filled with the \texttt{fill} command.
To draw repeated stripes (also known as hatching) through
the polygon, use the \texttt{clip}
command to limit the area displayed to inside the polygon,
then the \texttt{stripepath}
command to replace the path with evenly spaced stripes and
then draw each stripe.  The following example demonstrates this,
with the output shown in Figure \ref{tutorialpolygons1}.

\verbatiminput{tutorialpolygons1.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialpolygons1.eps}
\caption{Hatching Polygons}
\label{tutorialpolygons1}
\end{figure}

To fill a polygon with cross-hatching use procedures to
draw each set of hatch lines at different angles.  Two procedures
are used so that modifying the current path with the
\texttt{stripepath}
command is isolated in one procedure and the original path
remains unmodified in the calling procedure.
This is demonstrated in the following example, with the output
shown in Figure \ref{tutorialpolygons2}.

\verbatiminput{tutorialpolygons2.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialpolygons2.eps}
\caption{Cross-Hatching Polygons}
\label{tutorialpolygons2}
\end{figure}

Use the \texttt{stripepath} and \texttt{samplepath}
commands in combination to generate a grid of points through the
polygon, then call a procedure to draw a symbol at each point.
This is demonstrated in the following example, with the output
shown in Figure \ref{tutorialpolygons3}.

\verbatiminput{tutorialpolygons3.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialpolygons3.eps}
\caption{Displaying Points in Polygons}
\label{tutorialpolygons3}
\end{figure}

To display a border around the inside of the polygon
use the \texttt{clip}
command to limit the area displayed to inside the polygon
and then draw the outline with a thick linestyle.
The following example demonstrates this, with the output shown
in Figure \ref{tutorialpolygons4}.
Give the argument \texttt{outside}
to the \texttt{clip} command
to display a border around the outside of a polygon instead.

\verbatiminput{tutorialpolygons4.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialpolygons4.eps}
\caption{Displaying Polygon Borders}
\label{tutorialpolygons4}
\end{figure}

To display polygons with a gradient fill pattern use
the \texttt{gradientfill} command.
This command fills the current path with colors that fade
across the polygon.
The following example demonstrates fading from olive at the
lower-left corner of each polygon to white in all other corners
of the polygon.  The output is shown in Figure \ref{tutorialgradient}.

\verbatiminput{tutorialgradient.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialgradient.eps}
\caption{Displaying Polygons With Gradient Fill}
\label{tutorialgradient}
\end{figure}

\subsection{Displaying Labels}

Labels are displayed using the \texttt{move}
command to define one or more points for labelling, followed by a
\texttt{label} command.  The font and justification for labels
are set with the \texttt{font} and \texttt{justify} commands.
Setting fonts, justification and displaying multiple lines
are demonstrated in the following example, with output
shown in Figure \ref{tutoriallabels1}.

\verbatiminput{tutoriallabels1.mapyrus}

\begin{figure}[htb]
\includegraphics{tutoriallabels1.eps}
\caption{Displaying Labels}
\label{tutoriallabels1}
\end{figure}

Labels are displayed horizontally.  Rotate the axes with the \texttt{rotate}
command before setting the font to display labels at an angle.
This is demonstrated in the following example,
with output shown in Figure \ref{tutoriallabels2}.

\verbatiminput{tutoriallabels2.mapyrus}

\begin{figure}[htb]
\includegraphics{tutoriallabels2.eps}
\caption{Rotated Labels}
\label{tutoriallabels2}
\end{figure}

Several methods are available for changing the appearance of labels.

To highlight a label, draw the outline of each letter with a thick line.
Then draw the label again at the same position in a different color.

The \texttt{stringwidth} function (see Table \ref{functions}
on page \pageref{functions}) calculates the
width of a label.  This value is used to underline a label, draw a box
surrounding a label, or to join several labels together on a single line.

These techniques are demonstrated in the following example,
with output shown in Figure \ref{tutoriallabels3}.

\verbatiminput{tutoriallabels3.mapyrus}

\begin{figure}[htb]
\includegraphics{tutoriallabels3.eps}
\caption{Highlighted Labels}
\label{tutoriallabels3}
\end{figure}

The \texttt{flowlabel} command is used to draw a label
following along a line.  This is useful for labelling streets or
rivers.

Use of this command is demonstrated in the following example,
with output shown in Figure \ref{tutoriallabels4}.

\verbatiminput{tutorialflowlabel1.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialflowlabel1.eps}
\caption{Labels Along a Line}
\label{tutoriallabels4}
\end{figure}

The \texttt{sinkhole} command is used determine a position
for a label in a polygon.  This command
replaces the current path defining a polygon with a single point in
the middle of the polygon.  This is demonstrated in the following
example, with output shown in Figure \ref{tutorialsinkhole}.

\verbatiminput{tutorialsinkhole.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialsinkhole.eps}
\caption{Labelling Polygons}
\label{tutorialsinkhole}
\end{figure}

If polygons are partially outside the page then
use the \texttt{guillotine} command to chop the
polygon at the edge of the page before using the \texttt{sinkhole}
command.

To calculate two label positions for a polygon, use the \texttt{guillotine}
command to cut the polygon into left and right (or top and bottom)
halves and use the \texttt{sinkhole} command to calculate a
position in each half.

\subsection{Displaying Data Stored In Text Files}

The simplest source of data is a text file, with one record per line.  The
filename and type of dataset to read is given in a \texttt{dataset} command.
Then a \texttt{fetch} command is used in a loop to read each record
and split it into fields.
Fields are assigned to variables
\texttt{\$1}, \texttt{\$2}, \texttt{\$3}, \dots and the whole record is
assigned to variable \texttt{\$0}.

Coordinates in GIS datasets are normally stored
in a world coordinate system such as
Universal Transverse Mercator.  To transform these coordinates to millimeter
coordinates on the page use the \texttt{worlds} command.  This sets a
transformation to map a range of world coordinates onto the whole page.  All
coordinates given for later \texttt{addpath}, \texttt{move}, \texttt{arc},
\texttt{box},
\texttt{box3d},
\texttt{draw},
\texttt{circle},
\texttt{ellipse},
\texttt{hexagon},
\texttt{pentagon},
\texttt{raindrop},
\texttt{spiral},
\texttt{star},
\texttt{triangle}
and
\texttt{wedge}
commands are converted from world coordinate to page coordinates
through this transformation.

The following example demonstrates
setting a world coordinate system,
reading geographic positions from text file shown in Figure
\ref{tutorialdatasets1txt}, converting the positions to decimal
values using the \texttt{parsegeo} function and displaying them.
The output of this example is shown in
Figure \ref{tutorialdatasets1}.

\begin{figure}[htb]
\verbatiminput{tutorialdatasets1.txt}
\caption{Text File tutorialdatasets1.txt}
\label{tutorialdatasets1txt}
\end{figure}

\verbatiminput{tutorialdatasets1.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialdatasets1.eps}
\caption{Displaying Contents Of A Text File}
\label{tutorialdatasets1}
\end{figure}

Gazeteer files, GPS waypoint files and export files of GIS datasets
are also read as text files.

For files containing lines and polygons, a loop and counter
are used to read all coordinates for each line and polygon.

The following example demonstrates
reading and displaying the GenaMap GIS ZF19 format export file shown in Figure
\ref{streetsEE} containing line
features.
The output is shown in Figure \ref{tutorialdatasets2}.

\begin{figure}[htb]
\verbatiminput{streets.EE}
\caption{GIS Export File streets.EE}
\label{streetsEE}
\end{figure}

\verbatiminput{tutorialdatasets2.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialdatasets2.eps}
\caption{Displaying GIS Export Files}
\label{tutorialdatasets2}
\end{figure}

\subsection{Displaying Data Stored In Shape Files}

Reading data from an ESRI Shape file format is similar to reading a text file.
A Shape file defines a bounding rectangle so the internal variables
\texttt{Mapyrus.dataset.min.x}, \texttt{Mapyrus.dataset.min.y},
\texttt{Mapyrus.dataset.max.x}, and \texttt{Mapyrus.dataset.max.y} are
available to set world coordinates to the bounding rectangle of the dataset.

An ESRI Shape file also defines field names.  Fields fetched with the
\texttt{fetch} command are assigned to variables with the same name as the
field.  The geometry for each record is assigned to a variable named
\texttt{GEOMETRY} and is added to the current path with the \texttt{addpath}
command.

The following example demonstrates reading an ESRI Shape file containing points
and attribute fields named \texttt{HOTELNAME} and \texttt{STARRATING}.  The
attribute fields are used as labels and to control the appearance of the
symbols.

\verbatiminput{tutorialdatasets3.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialdatasets3.eps}
\caption{Displaying ESRI Shape Files}
\label{tutorialdatasets3}
\end{figure}

\subsection{Displaying Data Using \texttt{ogrinfo}}

The \texttt{ogrinfo} program is part of the OGR library, a freely-available
library for reading several GIS data formats.

\texttt{ogrinfo} writes the geometry and attributes of a GIS dataset
to a common format.

Mapyrus runs the \texttt{ogrinfo} program, and reads the
geometry and attributes written by ogrinfo and makes them available
for display.

The following example demonstrates reading a MapInfo TAB format
file containing street network data.  Mapyrus runs the
given \texttt{ogrinfo} command ending with a pipe (\texttt{|})
and reads the output of this command.

\verbatiminput{tutorialdatasets4.mapyrus}

First run a \texttt{ogrinfo} command outside of Mapyrus
to check that it gives the expected output.

On UNIX operating systems, it is possible to pipe the output of
\texttt{ogrinfo} program directly to Mapyrus.  This is demonstrated in the
following example, reading \texttt{ogrinfo} output containing points as
standard input (\texttt{-})
in Mapyrus and displaying them in a PostScript file.
The \texttt{ogrinfo -where} option is used to limit displayed
data to monuments.

\begin{verbatim}
ogrinfo -where "TYPE = 'monument'" /tmp/landmarks.tab landmarks | \
  java -classpath mapyrus.jar org.mapyrus.Mapyrus -e '
dataset "ogrinfo", "-", ""
newpage "ps", "landmarks.ps", 210, 297, ""
worlds Mapyrus.dataset.min.x, Mapyrus.dataset.min.y, \
  Mapyrus.dataset.max.x, Mapyrus.dataset.max.y

begin hex1
  color "red"
  hexagon 0, 0, 2
  fill
end

while Mapyrus.fetch.more
do
  fetch
  clearpath
  addpath GEOMETRY
  hex1
done'
\end{verbatim}

\subsection{Displaying Data Stored In A Database}

A simplistic method of reading from a relational database is to use a database
front-end program to print selected records to a file and then to read this in
Mapyrus.

Given the file \texttt{simplistic.mapyrus} containing the following
commands,

\begin{verbatim}
newpage "png", "simplistic.png", 100, 100, "background=white"
worlds 1000, 1000, 2000, 2000
dataset "textfile", "-", "delimiter=|"
while Mapyrus.fetch.more
do
  fetch
  clearpath
  color $3
  star $1, $2, 3, 5
  fill
done
\end{verbatim}

Then data read from an sqlite database is displayed as stars in a
PNG image using commands like:

\begin{verbatim}
sqlite db77 "select X, Y, Color from SITES" > sites.txt
java -classpath mapyrus.jar org.mapyrus.Mapyrus simplistic.mapyrus < sites.txt
\end{verbatim}

On UNIX operating systems, pipe the output directly from the database
front-end program to Mapyrus.  This is demonstrated in the following
example, displaying roads fetched as OGC WKT strings from a PostGIS database.

\begin{verbatim}
psql -A -t -c 'select AsText(Geom) from ROADS' pogo | \
  java -classpath mapyrus.jar org.mapyrus.Mapyrus -e '
newpage "png", "simplistic.png", 100, 100, "background=white"
worlds 170000, 470000, 220000, 540000
dataset "textfile", "-", "delimiter=|"
while Mapyrus.fetch.more
do
  fetch
  clearpath
  addpath $1
  stroke
done'
\end{verbatim}

A more efficient solution is to read from a relational database within Mapyrus
using the Java JDBC interface and a JDBC driver provided
as part of the database.  The JAR file containing the
JDBC driver must be included in the \texttt{-classpath} option
when Mapyrus is run.

For example, when accessing a PostgreSQL database from a Linux
machine, ensure that the \texttt{postgresql-jdbc} package is
installed and use a command like:

\begin{alltt}
java -classpath mapyrus.jar:/usr/share/pgsql/pg73b1jdbc1.jar \textbackslash
  org.mapyrus.Mapyrus tutorialdataset5.mapyrus
\end{alltt}

The JDBC driver for PostgreSQL is available from
\texttt{http://jdbc.postgresql.org}.

A JDBC driver for MySQL is available from
\newline
\texttt{http://www.mysql.com/products/connector/j}.

Each field in a database table has a name.
Fields fetched with the
\texttt{fetch}
command are assigned to variables with the same name as the field.
In the following example three fields are fetched from each
row and assigned to variables named
\texttt{longitude}, \texttt{latitude} and \texttt{assetcode}.

An SQL where clause is used to limit data read from
the database to inside the area of interest.

\verbatiminput{tutorialdatasets5.mapyrus}

For databases supporting the \textit{OpenGIS Simple Features Specification For
SQL}, add fields containing OGC WKT geometry strings or WKB geometry values
to the current path with an \texttt{addpath} command.  Using WKT geometry
strings is less efficient than WKB geometry strings because all geometry
must be converted to a text string and then back to a geometry.

The following example demonstrates fetching a geometry field named \texttt{geom}
from the database as a WKT string and displaying it.

\verbatiminput{tutorialdatasets6.mapyrus}

\subsection{Displaying Geo-Referenced Images}

To display a geo-referenced image use the \texttt{geoimage} command.
A "worlds" file with \texttt{.tfw} suffix is required, containing
the world coordinate range covered by the image.

The following example demonstrates
displaying the image \texttt{australia.png} as a background image,
then displaying the data contained in an ESRI Shape file over the image.
The output is shown in Figure \ref{tutorialgeoimage1}.

\verbatiminput{tutorialgeoimage1.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialgeoimage1.eps}
\caption{Displaying Geo-Referenced Images}
\label{tutorialgeoimage1}
\end{figure}

Some sets of geo-referenced images are provided as a grid
of trapezoidal shaped images.
To display several of these images it is necessary to clip
each image as it is displayed to avoid overwriting neighbouring
images.  To define a clip polygon for a geo-referenced image, use
the \texttt{clipfile} option to the \texttt{geoimage} command.

An alternative method of clipping an image is to use the
\texttt{clip} command to set a clip path to polygons read from a dataset.
The following example demonstrates this, clipping the image so
that only parts of the image inside coastline polygons are displayed.
The output is shown in Figure \ref{tutorialgeoimage2}.

\verbatiminput{tutorialgeoimage2.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialgeoimage2.eps}
\caption{Clipping Geo-Referenced Images}
\label{tutorialgeoimage2}
\end{figure}

\subsection{Displaying Images From An OGC Web Mapping Service}

An OGC Web Mapping Service (WMS) is an HTTP server that provides
geo-referenced images.
To fetch a geo-referenced image from a WMS and display it
on the page use the \texttt{geoimage} command.

The following example demonstrates building a URL for a WMS request
from a UMN Mapserver,
defining the layers to be fetched and world coordinate range
of the area of interest.
The UMN Mapserver must be configured to return 24 bit PNG images
as Mapyrus cannot read the default PNG format returned by Mapserver.

\verbatiminput{tutorialgeoimage3.mapyrus}

\subsection{Displaying Many Datasets or Geo-Referenced Images}

To display data contained in many files, use the \texttt{listfiles}
function to obtain a list of files in one or more directories matching
a filename pattern.  Then display each dataset in a loop.
Displaying from many ESRI Shape files is demonstrated in the following
example.

\verbatiminput{tutorialdatasets7.mapyrus}

A common method of efficiently selecting the data that overlaps the page from
hundreds of possible datasets and geo-referenced images is to create an index
ESRI Shape file with a polygon containing the bounding rectangle of each
dataset or image.

This ESRI Shape file index is then searched for overlapping polygons.

For ESRI Shape file datasets, the \texttt{tile4ms} program included in 
UMN Mapserver\footnote{Available from http://mapserver.gis.umn.edu} is used
to create an ESRI Shape file index.

For geo-referenced images, the
\texttt{gdaltindex} program included in the
gdal\footnote{Available from http://www.gdal.org}
library is used to create an ESRI Shape file index.

The following example demonstrates searching an ESRI Shape file index
for images to display.

\verbatiminput{tutorialdatasets8.mapyrus}

\subsection{Updating Existing Output Files}

To edit or draw over an existing image file or PostScript file use
the \texttt{update=true} option to the \texttt{newpage} command.
This allows further data to be drawn over a base map, or a watermark
or logo to be added to a map.

Updating works for both files created by Mapyrus and files created
by other software.

This is demonstrated in the following example, drawing a grid over
the output file \texttt{tutorialexisting1.eps} (a copy of the output file
from Figure \ref{tutorialdatasets1} from page \pageref{tutorialdatasets1}).
The output of this example is shown in figure
Figure \ref{tutorialexisting1}.

\verbatiminput{tutorialexisting1.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialexisting1.eps}
\caption{Updating An Existing Output File}
\label{tutorialexisting1}
\end{figure}

\subsection{Display Performance}

The following techniques help improve the display speed of large datasets.

Check the internal variable \texttt{Mapyrus.worlds.scale} before displaying a
large, detailed dataset.  If the scale is too high then the details will not be
legible so skip display of the detailed part of the dataset.  For example,
display all streets when zoomed in, but only highways when zoomed out.

Store two copies of the same data.  One at high resolution and one at low
resolution.  Select the dataset with the resolution closest to the current
display scale.

For dense data, with many points very close to each other, skip every second
piece of data in the dataset using two \texttt{fetch} commands together.  When
the dataset is in a database this is more efficiently done by ignoring odd
numbered rows using an SQL statement like:

\begin{verbatim}
select X, Y, Freq from SCATTER where MOD(rowid, 2) = 0
\end{verbatim}

Set an upper limit on the number of rows fetched or the time for display by
checking the internal variables \texttt{Mapyrus.fetch.count} and
\texttt{Mapyrus.timer} in a loop and ending when the limit is exceeded.

\subsection{Displaying A Legend}

A cartographic rule is that a map display must include a legend.  The
\texttt{key} command is used to save each entry to be include in a legend and
the \texttt{legend} command displays a legend.

A \texttt{key} command in a procedure defines a legend entry.  Mapyrus saves
each legend entry encountered whilst executing commands.  Each legend entry has
a description label and a type, defining whether the entry appears as a point,
line or box in the legend.

When display of all data is complete, points for legend entries are defined
with \texttt{move} commands and the \texttt{legend} command is used to display
each legend entry.  Each legend entry is automatically displayed by calling the
procedure in which it was defined.

If insufficient \texttt{move} points are defined then some legend entries
remain undisplayed.

Display the legend in a separate image file to prevent overwriting the map.

This is demonstrated in the following example.
The two output files are shown in Figure \ref{tutoriallegend1}.
Note that the legend entry for the procedure \texttt{road} is
not included in the legend because this procedure is not
executed in the example.

\verbatiminput{tutoriallegend1.mapyrus}

\begin{figure}[htb]
\includegraphics{tutoriallegend1.eps}
\includegraphics{tutoriallegend1legend.eps}
\caption{Displaying A Legend}
\label{tutoriallegend1}
\end{figure}

To display each legend entry in a separate file use a loop, checking the
internal variable \texttt{Mapyrus.key.count} to find how many legend entries
remain to be displayed.

In each loop iteration, create a new output file, set a single \texttt{move}
point and then display a single legend entry with a \texttt{legend} command.
Continue until all legend entries are displayed.

This is demonstrated in the following example, with each separate legend entry
PostScript file inserted into a table.  The output is shown in Figure
\ref{tutoriallegend2}.  This approach is also useful for inserting legend
entries into an HTML table.

\verbatiminput{tutoriallegend2.mapyrus}

\begin{figure}[htb]
\includegraphics{tutoriallegend2.eps}
\vspace{10pt}

\begin{tabular}{|c|}
\hline
Individual Legend PostScript Files \\
\hline
\includegraphics{tutoriallegend2legend1.eps} \\
\hline
\includegraphics{tutoriallegend2legend2.eps} \\
\hline
\includegraphics{tutoriallegend2legend3.eps} \\
\hline
\includegraphics{tutoriallegend2legend4.eps} \\
\hline
\end{tabular}

\caption{Displaying Legend Entries Individually}
\label{tutoriallegend2}
\end{figure}

To show the number of times a legend entry has been used on
a map, include the special string \texttt{(\#)} in legend entry descriptions.
This string is replaced in the legend by the number of times the legend entry
was encountered whilst executing commands.
This feature is demonstrated in the following example,
with output shown in 
Figure \ref{tutoriallegend3}.

\verbatiminput{tutoriallegend3.mapyrus}

\begin{figure}[htb]
\includegraphics{tutoriallegend3.eps}
\includegraphics{tutoriallegend3legend.eps}
\caption{Displaying Frequency Count Of Legend Entries}
\label{tutoriallegend3}
\end{figure}

\subsection{Using Attributes To Control Display}

Use attributes of geographic data to control
color, size, shape, labelling, highlighting and alignment of symbols, lines
and polygons.
Use \texttt{if}-\texttt{then}-\texttt{endif}
statements to display different classes of data
differently.  For example, display private, local, and major roads
with different types of lines.

To display data with a known range of attribute values in different
colors based on the attribute value, define colors for minimum and
maximum values and use interpolation to determine the color for
each point, line or polygon.  This is demonstrated in the following
example by passing a temperature attribute value for each point
that is displayed.  The output is shown in Figure \ref{tutorialattribute1}.
A legend is also created to show how the coloring works.

\verbatiminput{tutorialattribute1.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialattribute1.eps}
\includegraphics{tutorialattribute1legend.eps}
\caption{Using Attributes}
\label{tutorialattribute1}
\end{figure}

Another possibility is varying the size of a symbol depending
on an attribute value.  The next example demonstrates this, using the
population value for each city to control the height of a
cylinder drawn at each point.
The output is shown in Figure \ref{tutorialattribute2}.

\verbatiminput{tutorialattribute2.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialattribute2.eps}
\includegraphics{tutorialattribute2legend.eps}
\caption{Using More Attributes}
\label{tutorialattribute2}
\end{figure}

Further examples are varying line width depending on traffic between
two points, varying labelling depending on the importance of data,
or varying the symbols plotted inside
polygons depending on soil or rock type.

Extend this technique to display two attribute values together to show
relationships between the attributes (such as the correlation between fox
populations and rabbit populations).  Alternatively, display the same attribute
measured at different times to show trends in the attribute data.

To display values of several attributes at point locations, draw a
piechart or histogram (see page \pageref{piechart}) at each point.

When reading from a relational database table,
SQL aggregate functions are available for calculating
statistics from the data.

The following SQL statement demonstrates calculating how many
standard deviations each reading is from the average.  Use
the result of this calculation to control the display of the data,
showing readings that are far from average differently to readings
that are close to average.

\begin{verbatim}
select X, Y, (Reading - (select AVG(Reading) from Pollution)) /
(select STDDEV(Reading) from Pollution) as R from Pollution
\end{verbatim}


\subsection{Displaying A Scalebar}
\label{tutorialscalebar}

Another cartographic rule is that a map display must include a scalebar.  The
following example creates two PostScript files using the internal variable
\texttt{Mapyrus.worlds.scale} to add a scale bar to the lower-left corner
of each map display.

The included file \texttt{scalebar.mapyrus} (available in the \texttt{userdoc}
subdirectory) defines a procedure named \texttt{scalebar}.  This procedure
performs the task of displaying the scalebar.  Include this file and call the
\texttt{scalebar} procedure whenever a scalebar is required for a map display.

Output from the example is shown in Figure \ref{tutorialscalebar1}.

An alternative approach for displaying scalebars is to save the scale value in
a variable, use the \texttt{newpage} command to create a new output file and
display the scalebar in a separate file from the map.

\verbatiminput{tutorialscalebar1.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialscalebar1.eps}
\includegraphics{tutorialscalebar2.eps}
\caption{Displaying A Scalebar}
\label{tutorialscalebar1}
\end{figure}

\subsection{Displaying Piecharts And Histograms}
\label{piechart}

Piecharts and histograms
are used to represent relative values of several attributes at
different locations.  For example, production levels or voting patterns.  The
following example demonstrate this using fixed data values.
In a real application this information is read from a
database or GIS dataset.

The included files
\texttt{piechart.mapyrus}
and
\texttt{histogram.mapyrus}
(available in the \texttt{userdoc}
subdirectory) define procedures named
\texttt{piechart}
and
\texttt{histogram}.
These procedures
perform the task of displaying piecharts and histograms.
Include one of these files and call the
\texttt{piechart}
or
\texttt{histogram}
procedure whenever piecharts or histograms are to be displayed.

The output of this example is shown in Figures
\ref{tutorialpiechart1}
and
\ref{tutorialhistogram1}.

\verbatiminput{tutorialpiechart1.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialpiechart1.eps}
\caption{Displaying Piecharts}
\label{tutorialpiechart1}
\end{figure}

\begin{figure}[htb]
\includegraphics{tutorialhistogram1.eps}
\caption{Displaying Histograms}
\label{tutorialhistogram1}
\end{figure}

\subsection{Random Effects}

Random effects are generated using the \texttt{random}
function and help give a map a less mechanical appearance.
Random effects are also useful for giving data that is not
precise a blurred, inaccurate appearance.
The following example demonstrates setting color randomly.
The output is shown in Figure \ref{tutorialrand1}.

\verbatiminput{tutorialrand1.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialrand1.eps}
\caption{Random Color}
\label{tutorialrand1}
\end{figure}

The next example demonstrates setting rotation randomly, with output shown in
Figure \ref{tutorialrand2}.

\verbatiminput{tutorialrand2.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialrand2.eps}
\caption{Random Rotation}
\label{tutorialrand2}
\end{figure}

The next example demonstrates setting position randomly for polygon fill, with
output shown in Figure \ref{tutorialrand3}.

\verbatiminput{tutorialrand3.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialrand3.eps}
\caption{Random Position}
\label{tutorialrand3}
\end{figure}

\subsection{Using Transparency}

To set a partially transparent color in Mapyrus, give a
transparency value (also known as an alpha value) for the color.
The background will be partly visible behind shapes and labels
drawn with transparent colors.

The following example demonstrates using transparent colors, with
output shown in Figure \ref{tutorialtrans1}.

Transparent colors cannot be set in PostScript files using
\texttt{eps} or \texttt{ps}
format output.
Transparent colors are only available in a Encapsulated PostScript file
containing an image created using
\texttt{epsimage}
format output.

\verbatiminput{tutorialtrans1.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialtrans1.eps}
\caption{Transparent Colors}
\label{tutorialtrans1}
\end{figure}

Transparency is also used to produce fading effects.
This technique is demonstrated in the following example, with
lines fading from an opaque color to transparent.
The output of this example is shown in Figure \ref{tutorialtrans2}.

\verbatiminput{tutorialtrans2.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialtrans2.eps}
\caption{Fading Lines}
\label{tutorialtrans2}
\end{figure}

When creating PDF output, the method of blending transparent colors
with the background is modified using the
\texttt{blend} command.

\subsection{Shadow Effects}
\label{tutorialshadow}

To highlight polygons with a shadow, draw the outline of the polygon, use a
\texttt{clip "outside"}
command to prevent the interior of the polygon being drawn,
then repeatedly use the \texttt{shiftpath} command to move the polygon a small
distance from its original position, drawing it each time.  This is
demonstrated in the following example, with output shown in Figure
\ref{tutorialshadow1}.  Change the sign of the shift values in the
\texttt{shiftpath} command to draw the highlight on a different side of the
polygon.

\verbatiminput{tutorialshadow1.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialshadow1.eps}
\caption{Shadow Effects}
\label{tutorialshadow1}
\end{figure}

\subsection{Displaying Tables}

Attribute information read from a dataset is often best
displayed in a table.

Tables are displayed in Mapyrus by creating arrays containing
the row and column values and then using the \texttt{table} command.

The following example shows the positions of several vehicles,
giving information about each vehicle as a table at the vehicle
position.  The output of this example is shown in Figure \ref{tutorialtable1}.

\verbatiminput{tutorialtable1.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialtable1.eps}
\caption{Displaying Tables In A Map}
\label{tutorialtable1}
\end{figure}

Other uses of tables are to show a summary of the data 
displayed on the page and to show a title block for a page.

The following example demonstrates both types of tables.
The output of this example is shown in Figure \ref{tutorialtable2}.

\verbatiminput{tutorialtable2.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialtable2.eps}
\caption{Displaying Map And Tables Separately}
\label{tutorialtable2}
\end{figure}

Give several background colors in the \texttt{table} command to make rows or
columns in a table easier to read.  For example, in a table with 2 columns,
using background colors \texttt{white,white,yellow,yellow} results
in rows having white and yellow backgrounds alternately.

\subsection{Wordwrapped Labels}

To split a long sentence into several lines for display as a label, use
the \texttt{wordwrap} function.
This function breaks lines at word boundaries like a word-processor
and is useful for displaying speech bubbles, or tooltip type
labels on the page.
The following example shows sentences being word-wrapped and
displayed inside a box using the \texttt{table} command.
The output of this example
is shown in Figure \ref{tutorialwordwrap1}.

\verbatiminput{tutorialwordwrap1.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialwordwrap1.eps}
\caption{Wordwrapped Labels}
\label{tutorialwordwrap1}
\end{figure}

\subsection{Avoiding Overlapping Labels}

Mapyrus maintains a list of rectangular
areas on the page that have been marked as protected by the
\texttt{protect} command.
To avoid overlapping labels, check that the area that will be
covered by a label is not protected before displaying the
label using the \texttt{stringwidth} and \texttt{protected} functions.
After displaying a label use the \texttt{protect} command to mark
the area covered by the label as protected.

This is demonstrated in the following example, with labels
drawn to the right or left of a point, to avoid overlapping
other labels.
Output is shown in Figure \ref{tutorialprotect1}.

\verbatiminput{tutorialprotect1.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialprotect1.eps}
\caption{Label Positioning}
\label{tutorialprotect1}
\end{figure}

For best results, display the most important labels first to maximise the
chances of finding a position for a label that does not overlap previous
labels.  For example, label large towns before villages.

This method can be extended to draw labels left, right, above, below or offset
from their true position, wherever they do not overlap other labels.

Areas of the page containing important symbols or icons can be
protected too.  However, in many cases it is simpler to
display most important data last to ensure it is not overwritten.

Use the \texttt{unprotect} command to clear protected areas.

\subsection{Displaying Image Icons}
\label{icons}

Display color image icons and clip-art using the \texttt{icon} command.
Icons are scaled and rotated to any size and rotation angle.
Displaying icons is demonstrated in the following example
with output shown in Figure \ref{tutorialicon1}.

\verbatiminput{tutorialicon1.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialicon1.eps}
\caption{Icon Display}
\label{tutorialicon1}
\end{figure}

Combine the \texttt{icon} command with
\texttt{stripepath} and
\texttt{samplepath} commands to
repeat the icon in a tile pattern inside a polygon.
This is demonstrated in the following example
with output shown in Figure \ref{tutorialicon2}.

\verbatiminput{tutorialicon2.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialicon2.eps}
\caption{Icon Fill Pattern}
\label{tutorialicon2}
\end{figure}

Another use for icons is to achieve a spray paint effect,
with scattered dots.
This effect is demonstrated in the following example
with output shown in Figure \ref{tutorialicon3}.

\verbatiminput{tutorialicon3.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialicon3.eps}
\caption{Spray Paint Pattern}
\label{tutorialicon3}
\end{figure}

\subsection{Including Encapsulated PostScript Files}

When creating PostScript or Encapsulated PostScript output it 
is possible to display the contents of another Encapsulated PostScript
file on the page one or more times.

Both Encapsulated PostScript files
Files generated by Mapyrus and other software may be included.

Using an Encapsulated PostScript file named \texttt{flag.eps}
in a fill pattern is demonstrated in the following example
with output shown in Figure \ref{tutorialeps1}.

\verbatiminput{tutorialeps1.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialeps1.eps}
\caption{Displaying An Encapsulated PostScript File}
\label{tutorialeps1}
\end{figure}

\subsection{Mapyrus and Java Topology Suite Functions}
\label{tutorialjts}

Advanced geometric functions in Mapyrus
(see Figure \ref{functions} on page \pageref{functions})
are provided by the
\textit{Java Topology Suite},
available from
(\texttt{http://www.vividsolutions.com}).

If any of these functions are used then the
\textit{Java Topology Suite} JAR file must be included in the
classpath when running Mapyrus.  The following command demonstrates this:

\begin{alltt}
java -classpath \textit{install-dir}/mapyrus.jar:\textit{jts-dir}/jts-1.5.jar \textbackslash
  org.mapyrus.Mapyrus tutorialjts1.mapyrus
\end{alltt}

The following example demonstrates using the \texttt{buffer} function to
create a hatched buffer around a line
with the output shown in Figure \ref{tutorialjts1}.

\verbatiminput{tutorialjts1.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialjts1.eps}
\caption{Buffer Function}
\label{tutorialjts1}
\end{figure}

The \texttt{contains} function is used to determine whether one geometry
is contained inside another.  This is useful for displaying sample points
differently, depending on which polygon they are inside.
A simple use of the \texttt{contains} function is
demonstrated in the following example
with the output shown in Figure \ref{tutorialjts1}.

\verbatiminput{tutorialjts2.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialjts2.eps}
\caption{Contains Function}
\label{tutorialjts2}
\end{figure}

Combine the \texttt{buffer} and \texttt{contains} functions to
display data differently depending on whether it falls within
a certain distance of another geometry.

Use the \texttt{overlaps} function to test whether two
polygons or two lines overlap.

Use the \texttt{difference}, \texttt{intersection} and \texttt{union}
functions to perform operations on geometries.
Use of the \texttt{difference} function is demonstrated in the
following example to find the parts of a polygon that are not inside a second
polygon.  The output of this example is shown in Figure \ref{tutorialjts3}.

\verbatiminput{tutorialjts3.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialjts3.eps}
\caption{Difference Function}
\label{tutorialjts3}
\end{figure}

\subsection{Creating Landscape Output on Portrait Pages}

Many PostScript printers accept only portrait orientation pages.
To print a landscape orientation page, 
give the \texttt{turnpage=true} option to the \texttt{newpage} command.
This option turns a landscape page 90 degrees to fit on a portrait page
and is demonstrated in the following example,
with output shown in Figure \ref{tutorialturnpage1}.

\verbatiminput{tutorialturnpage1.mapyrus}

\begin{figure}[htb]
\includegraphics{tutorialturnpage1.eps}
\caption{Rotated Landscape Page}
\label{tutorialturnpage1}
\end{figure}

\subsection{Page Layout With Mapyrus}

Place a map, a legend, a scalebar, a title, a logo and other information on
a page to create a complete page layout.

Calculate a page position in millimeters at which to display each item.
A map is displayed in a given region of the page using
the \texttt{worlds} command with both world coordinates
and a page position.

The following example demonstrates placing each item on an A6 size
page with output shown in Figure \ref{tutoriallayout1}
on page \pageref{tutoriallayout1}.

\verbatiminput{tutoriallayout1.mapyrus}

\begin{figure}[htb]
\includegraphics{tutoriallayout1.eps}
\caption{Page Layout}
\label{tutoriallayout1}
\end{figure}

Use a single page layout as a template for many map plots.  Read the map title,
map filename, colors and other settings from files at the start of each plot.
An example of this is creating a daily weather map, with the map and title
changing each day.

An alternative page layout method is to create three Encapsulated PostScript
files for the map, legend and scalebar and to position these Encapsulated
PostScript files on a page using page layout software such as MicroSoft Word.

\subsection{Creating Multiple Page Output}

To create multi-page PDF files, create each page as a separate
PostScript file in Mapyrus.  Then use the following GhostScript command to
merge the pages into a single PDF file:

\begin{verbatim}
gs -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=p.pdf p1.ps p2.ps -c quit
\end{verbatim}

\subsection{Using PostScript Fonts In PostScript Output}
\label{psfonts}

PostScript printers and the Ghostscript program
understand a limited number of fonts,
normally only 35 basic fonts including
AvantGarde,
Bookman,
Courier,
Helvetica,
NewCenturySchlbk,
Palatino,
Symbol,
Times-Roman,
ZapfChancery,
ZapfDingbats
and the bold
and oblique (italic) variations of these fonts.

When a PostScript printer prints a file containing an unknown font,
a substitute font is used.

To make a font known to the printer, include the ASCII definition of
the font in the PostScript file being printed.

An ASCII PostScript Type 1 font is defined in two files with suffixes
\texttt{.pfa} and \texttt{.afm}.  PostScript
font definition files are included in a PostScript file created
by Mapyrus using the
\textit{extras} \texttt{pfafiles} and \texttt{afmfiles}
options to the \texttt{newpage} command.
Include filenames of PostScript font definition files for all fonts to be used
in the page that are not known by the printer.

The first line of an ASCII PostScript Type 1 font definition file
contains the name of the font defined in the file.

To convert a True Type Font file to an ASCII PostScript Type 1 font use the
ttf2pt1\footnote{Available from http://ttf2pt1.sourceforge.net} program.  The
following command converts the font in the file \texttt{BEANTOWN.TTF} to a
PostScript Type 1 font in files
\texttt{BEANTOWN.pfa} and
\texttt{BEANTOWN.afm}.

\begin{verbatim}
ttf2pt1 -e BEANTOWN.TTF BEANTOWN
\end{verbatim}

\subsection{Using PostScript Fonts In PDF Output}
\label{pdffonts}

PDF format defines the following 14 standard fonts
that are always available:
Times-Roman, Times-Bold, Times-Italic, Times-BoldItalic,
Helvetica, Helvetica-Bold, Helvetica-Oblique, Helvetica-BoldOblique,
Courier, Courier-Bold, Courier-Oblique, Courier-BoldOblique,
Symbol, ZapfDingbats.

For other fonts, the definition of the font must be included
in the PDF file as a binary PostScript Type 1 font.

A binary PostScript Type 1 font is defined in two files with suffixes
\texttt{.pfb} and \texttt{.afm}.  A binary PostScript Type 1
font is included in a PDF file created
by Mapyrus using the
\textit{extras} \texttt{pfbfiles} and \texttt{afmfiles}
options to the \texttt{newpage} command.
Include filenames of PostScript font definition files for all
non-standard fonts to be used in the PDF file.

Binary PostScript Type 1 font definition files are binary files.
However, many parts are plain text and the first plain text
line in the file with \texttt{.pfb} suffix contains the name
of the font defined in the file.

To convert a True Type Font file to a binary  PostScript Type 1 font use the
ttf2pt1\footnote{Available from http://ttf2pt1.sourceforge.net} program.  The
following command converts the font in the file \texttt{BEANTOWN.TTF} to a
binary PostScript Type 1 font in files
\texttt{BEANTOWN.pfb} and
\texttt{BEANTOWN.afm}.

\begin{verbatim}
ttf2pt1 -b BEANTOWN.TTF BEANTOWN
\end{verbatim}

\subsection{Using TrueType Fonts In Output to Image Formats}
\label{ttffonts}

For output to image formats, TrueType format fonts are used.

MicroSoft Windows and Macintosh operating systems support TrueType
fonts directly and all installed TrueType fonts are available
for use in the \texttt{font} command.
Additional TrueType fonts are installed using operating system commands.

A TrueType font is defined in a binary file with suffix
\texttt{.ttf}.
The name of a TrueType font normally does not match the filename exactly.
MicroSoft Windows Explorer and font display programs show the name of
a font contained in a TrueType font file.

Other operating systems do not support TrueType fonts.  To use TrueType fonts
on other operating systems using the \textit{extras} \texttt{ttffiles} option
to the \texttt{newpage} command.  Include filenames of TrueType font definition
files to be used in the page.

Some TrueType fonts do not include a complete set of characters.
For example, letters with accents or the copyright symbol are often
missing.  To view the available characters in a font on MicroSoft Windows
use the Character map program in the Program-Accessories
menu.  On UNIX operating systems use the font editor
pfaedit\footnote{Available from http://pfaedit.sourceforge.net}.

\subsection{Using Fonts In SVG Output}
\label{svgfonts}

When creating Scalable Vector Graphics format output files,
limit the use of fonts to commonly used fonts such as \texttt{Courier}
and \texttt{Arial}, or fonts that are known to be available in the
software to be used to display the SVG output files.

\subsection{Running Mapyrus As An HTTP Server}
\label{tutorialhttpserver}

Enter the following lines into a text file named
\texttt{tutorialhttpserver1.mapyrus}.

\verbatiminput{tutorialhttpserver1.mapyrus}

Copy the file \texttt{coastline.shp} from the \texttt{userdoc}
subdirectory in the
Mapyrus installation into the same directory as the file
\texttt{tutorialhttpserver1.mapyrus}.  In a terminal window, change to the
directory containing the two files and start Mapyrus as an HTTP server on port
8410 with the following command
(where \textit{install-dir} is the directory in which Mapyrus is installed).

\begin{alltt}
java -classpath \textit{install-dir}/mapyrus.jar org.mapyrus.Mapyrus -s 8410
\end{alltt}

Then enter the URL \texttt{http://localhost:8410/tutorialhttpserver1.mapyrus} in a
web browser.  Mapyrus receives the request, executes the commands in the file
\texttt{tutorialhttpserver1.mapyrus} and returns the PNG image that is written to
standard output to the web browser.

To return a PDF file instead of a PNG image,
enter the following lines into a text file named
\texttt{tutorialhttpserver2.mapyrus}.

\verbatiminput{tutorialhttpserver2.mapyrus}

Then enter the URL \texttt{http://localhost:8410/tutorialhttpserver2.mapyrus}
in a web browser.  Mapyrus generates a PDF file instead of a PNG image and
returns it to the web browser.

To return a Scalable Vector Graphics (SVG) file instead of a PNG image,
enter the following lines into a text file named
\texttt{tutorialhttpserver3.mapyrus} and enter the URL
\texttt{http://localhost:8410/tutorialhttpserver3.mapyrus}
in a web browser.

\verbatiminput{tutorialhttpserver3.mapyrus}

\subsection{Passing Variables To Mapyrus HTTP Server Through URLs}
\label{urlvariables}

To vary the display that is created by the Mapyrus HTTP Server, include
variables in the URL.  For example,

\begin{verbatim}
http://localhost:8410/tutorialurl.mapyrus?x=11.13&y=48.24&pLabels=off
\end{verbatim}

The variables \texttt{X}, \texttt{Y}
and \texttt{PLABELS} are automatically set in Mapyrus with the values
passed in the URL before interpreting
the commands in the file \texttt{tutorialurl.mapyrus}.
Note that variable names are always uppercase.

For applications that manage state
and provide a graphical user interface (such as clients written in
Java or PHP), use this method for returning data to the
application.

\subsection{Returning HTML Pages From Mapyrus HTTP Server}

An application for web browsers is based on HTML pages.
Generate HTML in Mapyrus and return it with \texttt{print} commands.
Generate temporary images for the HTML page with
unique filenames using the
\texttt{tempname}
function and return references to the images in the HTML.

The example file \texttt{tutorialhtmlpage1.mapyrus} demonstrates
this, displaying ESRI Shape file
\texttt{coastline.shp}
and text file
\texttt{aust\_temperatures.dat}
and using an HTML form to allow
the user to change the map display.
These three files are stored in the \texttt{userdoc} subdirectory
in a Mapyrus installation.
In a terminal window change to this directory and
start Mapyrus with the HTTP Server option, as described in section
\ref{tutorialhttpserver}.
Then enter the following URL in a web browser.

\begin{verbatim}
http://localhost:8410/tutorialhtmlpage1.mapyrus
\end{verbatim}

To simplify editing of HTML pages for an application, setup
template HTML pages with placeholders for the information that
Mapyrus provides.  This enables the HTML interface to be designed
independently from Mapyrus.

In Mapyrus, return the HTML pages with the placeholders
replaced by real values using the
\texttt{replace}
function.  The Mapyrus commands in the file \texttt{tutorialhtmlpage2.mapyrus}
and the template HTML file \texttt{tutorialhtmlpage2.txt}
demonstrate this.  Both files are found in the
\texttt{userdoc} subdirectory.

\subsection{Using JavaScript with Mapyrus HTTP Server}
\label{tutorialjavascript}

Images generated by Mapyrus are made interactive by defining hyperlinks and
JavaScript functions to execute when the mouse is moved or clicked over the
image.  This is achieved by using an HTML imagemap for an image.

A file containing an HTML imagemap is created using the \textit{extras}
\texttt{imagemap} option to the \texttt{newpage} command.

A hyperlink or JavaScript function is defined for an area in the image using
the \texttt{eventscript} command.  The list of areas in the image and
hyperlinks and JavaScript functions are written to the imagemap file.

The image and imagemap file are then combined in an HTML file
and returned to the web browser.

The following example file \texttt{tutorialhtmlpage3.mapyrus}
demonstrates this, displaying a tooltip when
the mouse is moved over Australia.

\verbatiminput{tutorialhtmlpage3.mapyrus}

The JavaScript library \texttt{overlib.js}
\footnote{Available from http://www.bosrup.com/web/overlib/} is
used to display the tooltips and must be copied to the same
directory as the file \texttt{tutorialhtmlpage3.mapyrus}.

Enter the following URL in a web browser to display the HTML page.

\begin{verbatim}
http://localhost:8410/tutorialhtmlpage3.mapyrus
\end{verbatim}

Some knowledge of JavaScript is necessary to understand this example.

This method is also suitable for generating static HTML pages
and imagemaps.

\subsection{Setting Expiry Dates, Cookies and Redirections from
Mapyrus HTTP Server}
\label{cookies}

For images that change infrequently, setting an expiry date prevents
a web browser from making the same request to the HTTP server again.

Change the \texttt{httpresponse} command in the example
from section \ref{tutorialhttpserver} to the following value to
stop a web browser from repeating the same HTTP request within
the next 60 seconds.

\begin{alltt}
httpresponse "HTTP/1.0 200 OK
Content-Type: image/png
Expires: " . timestamp(60)
\end{alltt}

To track the number of times a web browser makes a request to the
HTTP server, include a cookie in the response to an HTTP request.
The web browser then returns this cookie in the HTTP header of
the next request.  The following \texttt{httpresponse} command
demonstrates this.

\begin{alltt}
let cookie = Mapyrus.http.header['Cookie']
let cookie = replace(cookie, "^count=", "")
httpresponse "HTTP/1.0 200 OK
Content-Type: image/png
Set-Cookie: count=" . (cookie + 1)
\end{alltt}

To redirect a web browser to a different location,
return the following HTTP header using the \texttt{httpresponse}
command.

\begin{alltt}
httpresponse "HTTP/1.0 301 OK
Content-Type: image/png
Location: other-image.png"
\end{alltt}

\subsection{Returning Additional Information From Mapyrus HTTP Server}

Further ideas for building a complete HTML application are:

\begin{itemize}
\item
For datasets covering a wide area generate two images for
each HTML page.  Create a detailed map display and an overview map display
with a box showing the position of the detailed map in the dataset.

\item
Generate an image containing a scalebar
and include this in the HTML page.  See section \ref{tutorialscalebar}
on page \pageref{tutorialscalebar}.

\item
Restrict datasets to a limited scale range by checking the
internal variable
\texttt{Mapyrus.worlds.scale} before displaying a dataset.

\item
Return a map image as an HTML imagemap.  This enables the user to click
in the map to re-center or zoom the display.  When the user clicks
in the map another HTTP request is generated.  When Mapyrus receives
an HTTP request from a mouse click in an image map the internal variables
\texttt{Mapyrus.imagemap.x} and
\texttt{Mapyrus.imagemap.y} are automatically set with the pixel position
clicked in the image (with origin in top-left corner of the image).
Use these variables to calculate the new area to display.
\end{itemize}

\subsection{Using Mapyrus In A PHP Application}

Make the output of Mapyrus available to a PHP application by running as an
HTTP server, as described in section \ref{tutorialhttpserver}
on page \pageref{tutorialhttpserver}.

This avoids restarting Java each time a map is to be displayed.

Web format images are requested and fetched by the PHP
application and returned to the web browser using a
web page containing the following PHP functions.

\begin{verbatim}
<?php
header("Content-Type: image/png");
$im = imagecreatefrompng("http://localhost:8410/tutorialhttpserver1.mapyrus");
imagepng($im);
imagedestroy($im);
?>
\end{verbatim}

Pass variables to Mapyrus in the URL to vary the map display,
as described in section \ref{urlvariables}
on page \pageref{urlvariables}.

\subsection{Combining Mapyrus With Other Software}

To combine Mapyrus with other software use the following
techniques.

Pass parameters from calling environment to Mapyrus using the Java
\texttt{-D} option.

To use Mapyrus in a pipeline of commands,
give \texttt{-} as the output filename in a
\texttt{newpage}
command to write an image file to standard output.

Give \texttt{-} as the input filename in a
\texttt{dataset}
command to read standard input as a textfile.

Give Mapyrus commands with the \texttt{-e} option
instead of reading commands from a file.

Use Mapyrus in combination with the freely available software
Netpbm\footnote{Available from http://netpbm.sourceforge.net} and
Ghostscript\footnote{Available from http://www.ghostscript.com} to post-process
image output and convert images and PostScript output to other formats.

The following three examples demonstrate these methods.
The first example creates a PPM image file and then converts it to ASCII art.

\begin{verbatim}
java -DDATADIR=$DATADIR -DNameidx=Q7B80L -classpath mapyrus.jar \
  org.mapyrus.Mapyrus mycommands.mapyrus | ppmtopgm | \
  pgmtopbm | pbmtoascii -2x4
\end{verbatim}

The second example creates a PostScript file and then converts it
to a fax format.

\begin{verbatim}
java -classpath mapyrus.jar org.mapyrus.Mapyrus \
  $HOME/common.mapyrus mycommands.mapyrus > myfile.ps
gs -sDEVICE=faxg3 -sOutputFile=myfile.fax \
  -TextAlphaBits=4 myfile.ps
\end{verbatim}

The third example reads a file listing and displays it in an
PNG image.

\begin{verbatim}
/bin/ls -l | java -classpath mapyrus.jar org.mapyrus.Mapyrus -e '
newpage "png", "-", 210, 120, "background=white"  # write to stdout
font "Courier", 4
let y = Mapyrus.page.height - 4
dataset "textfile", "-", ""  # read from stdin
while Mapyrus.fetch.more
do
  fetch 
  clearpath
  move 1, y
  # Display files with suffix "txt" in red, others in black.
  color match($0, ".txt$") ? "red" : "black"
  label $0
  let y = y - 4
done' > ls.png
\end{verbatim}

The fourth example creates a PNG image containing a banner,
running in headless mode on a server with no graphics display available.

\begin{verbatim}
java -Djava.awt.headless=true -classpath mapyrus.jar org.mapyrus.Mapyrus -e '
newpage "png", "banner.png", 180, 30, "ttffiles=BEANTOWN.ttf"
font "BeanTown", 24
color "red"
move 5, 5
label "HERE IS MY BANNER"
'
\end{verbatim}

\subsection{Creating Animations Using Mapyrus}

To create an animated GIF image, create each frame as a separate
GIF image using Mapyrus and the Netpbm program \texttt{ppmtogif}.
The following example demonstrates this, creating frames that slowly
zoom in.

\verbatiminput{tutorialanimate1.mapyrus}

Then combine all frames using the freely available program
Gifsicle\footnote{Available from http://www.lcdf.org/gifsicle}.
The following command makes an animated GIF file from all frames.

\begin{verbatim}
gifsicle frame*.gif > anim.gif
\end{verbatim}

\subsection{Building Mapyrus From Source}

To build Mapyrus from source code, the following development tools
are required:

\begin{itemize}
\item
CVS Version Control System.
\item
Ant build tool.
\item
Java 2 SDK 1.4.2, or higher.
\item
Java Topology Suite 1.5, or higher from \texttt{http://www.vividsolutions.com}.
\item
\LaTeX.
\end{itemize}

First, checkout the source code from the Mapyrus anonymous CVS server
using the following command.

\begin{verbatim}
cvs -z3 -d :pserver:anonymous@cvs.sourceforge.net:/cvsroot/mapyrus co mapyrus
\end{verbatim}

The build process build is defined in the file \texttt{build.xml} in the
Mapyrus installation directory.  To build the software, documentation and zip
file for distribution, create a terminal window, change to the directory in
which Mapyrus is installed and execute the following command.

\begin{verbatim}
ant -v
\end{verbatim}

The build process also generates the PDF manual and manual examples in the
\texttt{userdoc} subdirectory from source files using \LaTeX.

All source code is in Java and contains javadoc style comments.  To view and
edit the source code, use a Java development environment such as Eclipse and
import the source code into a new project.


\subsection{Sample Shapes And Patterns}
The file \texttt{symbols.mapyrus} included in the subdirectory
\texttt{userdoc} contains many examples of shapes and patterns
for lines and fills.  A legend for all examples in this file is shown
in Figure \ref{samplesymbols}.

\begin{figure}[htb]
\label{samplesymbols}
\includegraphics{symbols1.eps}
\caption{Sample Shapes And Patterns 1}
\end{figure}

\begin{figure}[htb]
\includegraphics{symbols2.eps}
\caption{Sample Shapes And Patterns 2}
\end{figure}

